three.webgpu.js 1.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '167dev';
  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 = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 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 TangentSpaceNormalMap = 0;
  160. const ObjectSpaceNormalMap = 1;
  161. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  162. const NoColorSpace = '';
  163. const SRGBColorSpace = 'srgb';
  164. const LinearSRGBColorSpace = 'srgb-linear';
  165. const DisplayP3ColorSpace = 'display-p3';
  166. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  167. const LinearTransfer = 'linear';
  168. const SRGBTransfer = 'srgb';
  169. const Rec709Primaries = 'rec709';
  170. const P3Primaries = 'p3';
  171. const ZeroStencilOp = 0;
  172. const KeepStencilOp = 7680;
  173. const ReplaceStencilOp = 7681;
  174. const IncrementStencilOp = 7682;
  175. const DecrementStencilOp = 7683;
  176. const IncrementWrapStencilOp = 34055;
  177. const DecrementWrapStencilOp = 34056;
  178. const InvertStencilOp = 5386;
  179. const NeverStencilFunc = 512;
  180. const LessStencilFunc = 513;
  181. const EqualStencilFunc = 514;
  182. const LessEqualStencilFunc = 515;
  183. const GreaterStencilFunc = 516;
  184. const NotEqualStencilFunc = 517;
  185. const GreaterEqualStencilFunc = 518;
  186. const AlwaysStencilFunc = 519;
  187. const NeverCompare = 512;
  188. const LessCompare = 513;
  189. const EqualCompare = 514;
  190. const LessEqualCompare = 515;
  191. const GreaterCompare = 516;
  192. const NotEqualCompare = 517;
  193. const GreaterEqualCompare = 518;
  194. const AlwaysCompare = 519;
  195. const StaticDrawUsage = 35044;
  196. const DynamicDrawUsage = 35048;
  197. const StreamDrawUsage = 35040;
  198. const StaticReadUsage = 35045;
  199. const DynamicReadUsage = 35049;
  200. const StreamReadUsage = 35041;
  201. const StaticCopyUsage = 35046;
  202. const DynamicCopyUsage = 35050;
  203. const StreamCopyUsage = 35042;
  204. const GLSL1 = '100';
  205. const GLSL3 = '300 es';
  206. const WebGLCoordinateSystem = 2000;
  207. const WebGPUCoordinateSystem = 2001;
  208. /**
  209. * https://github.com/mrdoob/eventdispatcher.js/
  210. */
  211. class EventDispatcher {
  212. addEventListener( type, listener ) {
  213. if ( this._listeners === undefined ) this._listeners = {};
  214. const listeners = this._listeners;
  215. if ( listeners[ type ] === undefined ) {
  216. listeners[ type ] = [];
  217. }
  218. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  219. listeners[ type ].push( listener );
  220. }
  221. }
  222. hasEventListener( type, listener ) {
  223. if ( this._listeners === undefined ) return false;
  224. const listeners = this._listeners;
  225. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  226. }
  227. removeEventListener( type, listener ) {
  228. if ( this._listeners === undefined ) return;
  229. const listeners = this._listeners;
  230. const listenerArray = listeners[ type ];
  231. if ( listenerArray !== undefined ) {
  232. const index = listenerArray.indexOf( listener );
  233. if ( index !== - 1 ) {
  234. listenerArray.splice( index, 1 );
  235. }
  236. }
  237. }
  238. dispatchEvent( event ) {
  239. if ( this._listeners === undefined ) return;
  240. const listeners = this._listeners;
  241. const listenerArray = listeners[ event.type ];
  242. if ( listenerArray !== undefined ) {
  243. event.target = this;
  244. // Make a copy, in case listeners are removed while iterating.
  245. const array = listenerArray.slice( 0 );
  246. for ( let i = 0, l = array.length; i < l; i ++ ) {
  247. array[ i ].call( this, event );
  248. }
  249. event.target = null;
  250. }
  251. }
  252. }
  253. 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' ];
  254. let _seed = 1234567;
  255. const DEG2RAD = Math.PI / 180;
  256. const RAD2DEG = 180 / Math.PI;
  257. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  258. function generateUUID() {
  259. const d0 = Math.random() * 0xffffffff | 0;
  260. const d1 = Math.random() * 0xffffffff | 0;
  261. const d2 = Math.random() * 0xffffffff | 0;
  262. const d3 = Math.random() * 0xffffffff | 0;
  263. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  264. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  265. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  266. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  267. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  268. return uuid.toLowerCase();
  269. }
  270. function clamp$1( value, min, max ) {
  271. return Math.max( min, Math.min( max, value ) );
  272. }
  273. // compute euclidean modulo of m % n
  274. // https://en.wikipedia.org/wiki/Modulo_operation
  275. function euclideanModulo( n, m ) {
  276. return ( ( n % m ) + m ) % m;
  277. }
  278. // Linear mapping from range <a1, a2> to range <b1, b2>
  279. function mapLinear( x, a1, a2, b1, b2 ) {
  280. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  281. }
  282. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  283. function inverseLerp( x, y, value ) {
  284. if ( x !== y ) {
  285. return ( value - x ) / ( y - x );
  286. } else {
  287. return 0;
  288. }
  289. }
  290. // https://en.wikipedia.org/wiki/Linear_interpolation
  291. function lerp( x, y, t ) {
  292. return ( 1 - t ) * x + t * y;
  293. }
  294. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  295. function damp( x, y, lambda, dt ) {
  296. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  297. }
  298. // https://www.desmos.com/calculator/vcsjnyz7x4
  299. function pingpong( x, length = 1 ) {
  300. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  301. }
  302. // http://en.wikipedia.org/wiki/Smoothstep
  303. function smoothstep$1( x, min, max ) {
  304. if ( x <= min ) return 0;
  305. if ( x >= max ) return 1;
  306. x = ( x - min ) / ( max - min );
  307. return x * x * ( 3 - 2 * x );
  308. }
  309. function smootherstep( x, min, max ) {
  310. if ( x <= min ) return 0;
  311. if ( x >= max ) return 1;
  312. x = ( x - min ) / ( max - min );
  313. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  314. }
  315. // Random integer from <low, high> interval
  316. function randInt( low, high ) {
  317. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  318. }
  319. // Random float from <low, high> interval
  320. function randFloat( low, high ) {
  321. return low + Math.random() * ( high - low );
  322. }
  323. // Random float from <-range/2, range/2> interval
  324. function randFloatSpread( range ) {
  325. return range * ( 0.5 - Math.random() );
  326. }
  327. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  328. function seededRandom( s ) {
  329. if ( s !== undefined ) _seed = s;
  330. // Mulberry32 generator
  331. let t = _seed += 0x6D2B79F5;
  332. t = Math.imul( t ^ t >>> 15, t | 1 );
  333. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  334. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  335. }
  336. function degToRad( degrees ) {
  337. return degrees * DEG2RAD;
  338. }
  339. function radToDeg( radians ) {
  340. return radians * RAD2DEG;
  341. }
  342. function isPowerOfTwo( value ) {
  343. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  344. }
  345. function ceilPowerOfTwo( value ) {
  346. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  347. }
  348. function floorPowerOfTwo( value ) {
  349. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  350. }
  351. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  352. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  353. // rotations are applied to the axes in the order specified by 'order'
  354. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  355. // angles are in radians
  356. const cos = Math.cos;
  357. const sin = Math.sin;
  358. const c2 = cos( b / 2 );
  359. const s2 = sin( b / 2 );
  360. const c13 = cos( ( a + c ) / 2 );
  361. const s13 = sin( ( a + c ) / 2 );
  362. const c1_3 = cos( ( a - c ) / 2 );
  363. const s1_3 = sin( ( a - c ) / 2 );
  364. const c3_1 = cos( ( c - a ) / 2 );
  365. const s3_1 = sin( ( c - a ) / 2 );
  366. switch ( order ) {
  367. case 'XYX':
  368. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  369. break;
  370. case 'YZY':
  371. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  372. break;
  373. case 'ZXZ':
  374. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  375. break;
  376. case 'XZX':
  377. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  378. break;
  379. case 'YXY':
  380. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  381. break;
  382. case 'ZYZ':
  383. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  384. break;
  385. default:
  386. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  387. }
  388. }
  389. function denormalize( value, array ) {
  390. switch ( array.constructor ) {
  391. case Float32Array:
  392. return value;
  393. case Uint32Array:
  394. return value / 4294967295.0;
  395. case Uint16Array:
  396. return value / 65535.0;
  397. case Uint8Array:
  398. return value / 255.0;
  399. case Int32Array:
  400. return Math.max( value / 2147483647.0, - 1.0 );
  401. case Int16Array:
  402. return Math.max( value / 32767.0, - 1.0 );
  403. case Int8Array:
  404. return Math.max( value / 127.0, - 1.0 );
  405. default:
  406. throw new Error( 'Invalid component type.' );
  407. }
  408. }
  409. function normalize$1( value, array ) {
  410. switch ( array.constructor ) {
  411. case Float32Array:
  412. return value;
  413. case Uint32Array:
  414. return Math.round( value * 4294967295.0 );
  415. case Uint16Array:
  416. return Math.round( value * 65535.0 );
  417. case Uint8Array:
  418. return Math.round( value * 255.0 );
  419. case Int32Array:
  420. return Math.round( value * 2147483647.0 );
  421. case Int16Array:
  422. return Math.round( value * 32767.0 );
  423. case Int8Array:
  424. return Math.round( value * 127.0 );
  425. default:
  426. throw new Error( 'Invalid component type.' );
  427. }
  428. }
  429. const MathUtils = {
  430. DEG2RAD: DEG2RAD,
  431. RAD2DEG: RAD2DEG,
  432. generateUUID: generateUUID,
  433. clamp: clamp$1,
  434. euclideanModulo: euclideanModulo,
  435. mapLinear: mapLinear,
  436. inverseLerp: inverseLerp,
  437. lerp: lerp,
  438. damp: damp,
  439. pingpong: pingpong,
  440. smoothstep: smoothstep$1,
  441. smootherstep: smootherstep,
  442. randInt: randInt,
  443. randFloat: randFloat,
  444. randFloatSpread: randFloatSpread,
  445. seededRandom: seededRandom,
  446. degToRad: degToRad,
  447. radToDeg: radToDeg,
  448. isPowerOfTwo: isPowerOfTwo,
  449. ceilPowerOfTwo: ceilPowerOfTwo,
  450. floorPowerOfTwo: floorPowerOfTwo,
  451. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  452. normalize: normalize$1,
  453. denormalize: denormalize
  454. };
  455. class Vector2 {
  456. constructor( x = 0, y = 0 ) {
  457. Vector2.prototype.isVector2 = true;
  458. this.x = x;
  459. this.y = y;
  460. }
  461. get width() {
  462. return this.x;
  463. }
  464. set width( value ) {
  465. this.x = value;
  466. }
  467. get height() {
  468. return this.y;
  469. }
  470. set height( value ) {
  471. this.y = value;
  472. }
  473. set( x, y ) {
  474. this.x = x;
  475. this.y = y;
  476. return this;
  477. }
  478. setScalar( scalar ) {
  479. this.x = scalar;
  480. this.y = scalar;
  481. return this;
  482. }
  483. setX( x ) {
  484. this.x = x;
  485. return this;
  486. }
  487. setY( y ) {
  488. this.y = y;
  489. return this;
  490. }
  491. setComponent( index, value ) {
  492. switch ( index ) {
  493. case 0: this.x = value; break;
  494. case 1: this.y = value; break;
  495. default: throw new Error( 'index is out of range: ' + index );
  496. }
  497. return this;
  498. }
  499. getComponent( index ) {
  500. switch ( index ) {
  501. case 0: return this.x;
  502. case 1: return this.y;
  503. default: throw new Error( 'index is out of range: ' + index );
  504. }
  505. }
  506. clone() {
  507. return new this.constructor( this.x, this.y );
  508. }
  509. copy( v ) {
  510. this.x = v.x;
  511. this.y = v.y;
  512. return this;
  513. }
  514. add( v ) {
  515. this.x += v.x;
  516. this.y += v.y;
  517. return this;
  518. }
  519. addScalar( s ) {
  520. this.x += s;
  521. this.y += s;
  522. return this;
  523. }
  524. addVectors( a, b ) {
  525. this.x = a.x + b.x;
  526. this.y = a.y + b.y;
  527. return this;
  528. }
  529. addScaledVector( v, s ) {
  530. this.x += v.x * s;
  531. this.y += v.y * s;
  532. return this;
  533. }
  534. sub( v ) {
  535. this.x -= v.x;
  536. this.y -= v.y;
  537. return this;
  538. }
  539. subScalar( s ) {
  540. this.x -= s;
  541. this.y -= s;
  542. return this;
  543. }
  544. subVectors( a, b ) {
  545. this.x = a.x - b.x;
  546. this.y = a.y - b.y;
  547. return this;
  548. }
  549. multiply( v ) {
  550. this.x *= v.x;
  551. this.y *= v.y;
  552. return this;
  553. }
  554. multiplyScalar( scalar ) {
  555. this.x *= scalar;
  556. this.y *= scalar;
  557. return this;
  558. }
  559. divide( v ) {
  560. this.x /= v.x;
  561. this.y /= v.y;
  562. return this;
  563. }
  564. divideScalar( scalar ) {
  565. return this.multiplyScalar( 1 / scalar );
  566. }
  567. applyMatrix3( m ) {
  568. const x = this.x, y = this.y;
  569. const e = m.elements;
  570. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  571. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  572. return this;
  573. }
  574. min( v ) {
  575. this.x = Math.min( this.x, v.x );
  576. this.y = Math.min( this.y, v.y );
  577. return this;
  578. }
  579. max( v ) {
  580. this.x = Math.max( this.x, v.x );
  581. this.y = Math.max( this.y, v.y );
  582. return this;
  583. }
  584. clamp( min, max ) {
  585. // assumes min < max, componentwise
  586. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  587. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  588. return this;
  589. }
  590. clampScalar( minVal, maxVal ) {
  591. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  592. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  593. return this;
  594. }
  595. clampLength( min, max ) {
  596. const length = this.length();
  597. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  598. }
  599. floor() {
  600. this.x = Math.floor( this.x );
  601. this.y = Math.floor( this.y );
  602. return this;
  603. }
  604. ceil() {
  605. this.x = Math.ceil( this.x );
  606. this.y = Math.ceil( this.y );
  607. return this;
  608. }
  609. round() {
  610. this.x = Math.round( this.x );
  611. this.y = Math.round( this.y );
  612. return this;
  613. }
  614. roundToZero() {
  615. this.x = Math.trunc( this.x );
  616. this.y = Math.trunc( this.y );
  617. return this;
  618. }
  619. negate() {
  620. this.x = - this.x;
  621. this.y = - this.y;
  622. return this;
  623. }
  624. dot( v ) {
  625. return this.x * v.x + this.y * v.y;
  626. }
  627. cross( v ) {
  628. return this.x * v.y - this.y * v.x;
  629. }
  630. lengthSq() {
  631. return this.x * this.x + this.y * this.y;
  632. }
  633. length() {
  634. return Math.sqrt( this.x * this.x + this.y * this.y );
  635. }
  636. manhattanLength() {
  637. return Math.abs( this.x ) + Math.abs( this.y );
  638. }
  639. normalize() {
  640. return this.divideScalar( this.length() || 1 );
  641. }
  642. angle() {
  643. // computes the angle in radians with respect to the positive x-axis
  644. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  645. return angle;
  646. }
  647. angleTo( v ) {
  648. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  649. if ( denominator === 0 ) return Math.PI / 2;
  650. const theta = this.dot( v ) / denominator;
  651. // clamp, to handle numerical problems
  652. return Math.acos( clamp$1( theta, - 1, 1 ) );
  653. }
  654. distanceTo( v ) {
  655. return Math.sqrt( this.distanceToSquared( v ) );
  656. }
  657. distanceToSquared( v ) {
  658. const dx = this.x - v.x, dy = this.y - v.y;
  659. return dx * dx + dy * dy;
  660. }
  661. manhattanDistanceTo( v ) {
  662. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  663. }
  664. setLength( length ) {
  665. return this.normalize().multiplyScalar( length );
  666. }
  667. lerp( v, alpha ) {
  668. this.x += ( v.x - this.x ) * alpha;
  669. this.y += ( v.y - this.y ) * alpha;
  670. return this;
  671. }
  672. lerpVectors( v1, v2, alpha ) {
  673. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  674. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  675. return this;
  676. }
  677. equals( v ) {
  678. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  679. }
  680. fromArray( array, offset = 0 ) {
  681. this.x = array[ offset ];
  682. this.y = array[ offset + 1 ];
  683. return this;
  684. }
  685. toArray( array = [], offset = 0 ) {
  686. array[ offset ] = this.x;
  687. array[ offset + 1 ] = this.y;
  688. return array;
  689. }
  690. fromBufferAttribute( attribute, index ) {
  691. this.x = attribute.getX( index );
  692. this.y = attribute.getY( index );
  693. return this;
  694. }
  695. rotateAround( center, angle ) {
  696. const c = Math.cos( angle ), s = Math.sin( angle );
  697. const x = this.x - center.x;
  698. const y = this.y - center.y;
  699. this.x = x * c - y * s + center.x;
  700. this.y = x * s + y * c + center.y;
  701. return this;
  702. }
  703. random() {
  704. this.x = Math.random();
  705. this.y = Math.random();
  706. return this;
  707. }
  708. *[ Symbol.iterator ]() {
  709. yield this.x;
  710. yield this.y;
  711. }
  712. }
  713. class Matrix3 {
  714. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  715. Matrix3.prototype.isMatrix3 = true;
  716. this.elements = [
  717. 1, 0, 0,
  718. 0, 1, 0,
  719. 0, 0, 1
  720. ];
  721. if ( n11 !== undefined ) {
  722. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  723. }
  724. }
  725. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  726. const te = this.elements;
  727. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  728. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  729. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  730. return this;
  731. }
  732. identity() {
  733. this.set(
  734. 1, 0, 0,
  735. 0, 1, 0,
  736. 0, 0, 1
  737. );
  738. return this;
  739. }
  740. copy( m ) {
  741. const te = this.elements;
  742. const me = m.elements;
  743. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  744. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  745. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  746. return this;
  747. }
  748. extractBasis( xAxis, yAxis, zAxis ) {
  749. xAxis.setFromMatrix3Column( this, 0 );
  750. yAxis.setFromMatrix3Column( this, 1 );
  751. zAxis.setFromMatrix3Column( this, 2 );
  752. return this;
  753. }
  754. setFromMatrix4( m ) {
  755. const me = m.elements;
  756. this.set(
  757. me[ 0 ], me[ 4 ], me[ 8 ],
  758. me[ 1 ], me[ 5 ], me[ 9 ],
  759. me[ 2 ], me[ 6 ], me[ 10 ]
  760. );
  761. return this;
  762. }
  763. multiply( m ) {
  764. return this.multiplyMatrices( this, m );
  765. }
  766. premultiply( m ) {
  767. return this.multiplyMatrices( m, this );
  768. }
  769. multiplyMatrices( a, b ) {
  770. const ae = a.elements;
  771. const be = b.elements;
  772. const te = this.elements;
  773. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  774. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  775. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  776. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  777. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  778. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  779. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  780. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  781. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  782. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  783. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  784. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  785. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  786. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  787. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  788. return this;
  789. }
  790. multiplyScalar( s ) {
  791. const te = this.elements;
  792. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  793. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  794. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  795. return this;
  796. }
  797. determinant() {
  798. const te = this.elements;
  799. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  800. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  801. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  802. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  803. }
  804. invert() {
  805. const te = this.elements,
  806. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  807. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  808. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  809. t11 = n33 * n22 - n32 * n23,
  810. t12 = n32 * n13 - n33 * n12,
  811. t13 = n23 * n12 - n22 * n13,
  812. det = n11 * t11 + n21 * t12 + n31 * t13;
  813. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  814. const detInv = 1 / det;
  815. te[ 0 ] = t11 * detInv;
  816. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  817. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  818. te[ 3 ] = t12 * detInv;
  819. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  820. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  821. te[ 6 ] = t13 * detInv;
  822. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  823. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  824. return this;
  825. }
  826. transpose() {
  827. let tmp;
  828. const m = this.elements;
  829. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  830. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  831. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  832. return this;
  833. }
  834. getNormalMatrix( matrix4 ) {
  835. return this.setFromMatrix4( matrix4 ).invert().transpose();
  836. }
  837. transposeIntoArray( r ) {
  838. const m = this.elements;
  839. r[ 0 ] = m[ 0 ];
  840. r[ 1 ] = m[ 3 ];
  841. r[ 2 ] = m[ 6 ];
  842. r[ 3 ] = m[ 1 ];
  843. r[ 4 ] = m[ 4 ];
  844. r[ 5 ] = m[ 7 ];
  845. r[ 6 ] = m[ 2 ];
  846. r[ 7 ] = m[ 5 ];
  847. r[ 8 ] = m[ 8 ];
  848. return this;
  849. }
  850. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  851. const c = Math.cos( rotation );
  852. const s = Math.sin( rotation );
  853. this.set(
  854. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  855. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  856. 0, 0, 1
  857. );
  858. return this;
  859. }
  860. //
  861. scale( sx, sy ) {
  862. this.premultiply( _m3.makeScale( sx, sy ) );
  863. return this;
  864. }
  865. rotate( theta ) {
  866. this.premultiply( _m3.makeRotation( - theta ) );
  867. return this;
  868. }
  869. translate( tx, ty ) {
  870. this.premultiply( _m3.makeTranslation( tx, ty ) );
  871. return this;
  872. }
  873. // for 2D Transforms
  874. makeTranslation( x, y ) {
  875. if ( x.isVector2 ) {
  876. this.set(
  877. 1, 0, x.x,
  878. 0, 1, x.y,
  879. 0, 0, 1
  880. );
  881. } else {
  882. this.set(
  883. 1, 0, x,
  884. 0, 1, y,
  885. 0, 0, 1
  886. );
  887. }
  888. return this;
  889. }
  890. makeRotation( theta ) {
  891. // counterclockwise
  892. const c = Math.cos( theta );
  893. const s = Math.sin( theta );
  894. this.set(
  895. c, - s, 0,
  896. s, c, 0,
  897. 0, 0, 1
  898. );
  899. return this;
  900. }
  901. makeScale( x, y ) {
  902. this.set(
  903. x, 0, 0,
  904. 0, y, 0,
  905. 0, 0, 1
  906. );
  907. return this;
  908. }
  909. //
  910. equals( matrix ) {
  911. const te = this.elements;
  912. const me = matrix.elements;
  913. for ( let i = 0; i < 9; i ++ ) {
  914. if ( te[ i ] !== me[ i ] ) return false;
  915. }
  916. return true;
  917. }
  918. fromArray( array, offset = 0 ) {
  919. for ( let i = 0; i < 9; i ++ ) {
  920. this.elements[ i ] = array[ i + offset ];
  921. }
  922. return this;
  923. }
  924. toArray( array = [], offset = 0 ) {
  925. const te = this.elements;
  926. array[ offset ] = te[ 0 ];
  927. array[ offset + 1 ] = te[ 1 ];
  928. array[ offset + 2 ] = te[ 2 ];
  929. array[ offset + 3 ] = te[ 3 ];
  930. array[ offset + 4 ] = te[ 4 ];
  931. array[ offset + 5 ] = te[ 5 ];
  932. array[ offset + 6 ] = te[ 6 ];
  933. array[ offset + 7 ] = te[ 7 ];
  934. array[ offset + 8 ] = te[ 8 ];
  935. return array;
  936. }
  937. clone() {
  938. return new this.constructor().fromArray( this.elements );
  939. }
  940. }
  941. const _m3 = /*@__PURE__*/ new Matrix3();
  942. function arrayNeedsUint32$1( array ) {
  943. // assumes larger values usually on last
  944. for ( let i = array.length - 1; i >= 0; -- i ) {
  945. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  946. }
  947. return false;
  948. }
  949. const TYPED_ARRAYS = {
  950. Int8Array: Int8Array,
  951. Uint8Array: Uint8Array,
  952. Uint8ClampedArray: Uint8ClampedArray,
  953. Int16Array: Int16Array,
  954. Uint16Array: Uint16Array,
  955. Int32Array: Int32Array,
  956. Uint32Array: Uint32Array,
  957. Float32Array: Float32Array,
  958. Float64Array: Float64Array
  959. };
  960. function getTypedArray( type, buffer ) {
  961. return new TYPED_ARRAYS[ type ]( buffer );
  962. }
  963. function createElementNS( name ) {
  964. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  965. }
  966. function createCanvasElement() {
  967. const canvas = createElementNS( 'canvas' );
  968. canvas.style.display = 'block';
  969. return canvas;
  970. }
  971. const _cache$1 = {};
  972. function warnOnce( message ) {
  973. if ( message in _cache$1 ) return;
  974. _cache$1[ message ] = true;
  975. console.warn( message );
  976. }
  977. /**
  978. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  979. * or clipping. Based on W3C specifications for sRGB and Display P3,
  980. * and ICC specifications for the D50 connection space. Values in/out
  981. * are _linear_ sRGB and _linear_ Display P3.
  982. *
  983. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  984. *
  985. * Reference:
  986. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  987. */
  988. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  989. 0.8224621, 0.177538, 0.0,
  990. 0.0331941, 0.9668058, 0.0,
  991. 0.0170827, 0.0723974, 0.9105199,
  992. );
  993. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  994. 1.2249401, - 0.2249404, 0.0,
  995. - 0.0420569, 1.0420571, 0.0,
  996. - 0.0196376, - 0.0786361, 1.0982735
  997. );
  998. /**
  999. * Defines supported color spaces by transfer function and primaries,
  1000. * and provides conversions to/from the Linear-sRGB reference space.
  1001. */
  1002. const COLOR_SPACES = {
  1003. [ LinearSRGBColorSpace ]: {
  1004. transfer: LinearTransfer,
  1005. primaries: Rec709Primaries,
  1006. toReference: ( color ) => color,
  1007. fromReference: ( color ) => color,
  1008. },
  1009. [ SRGBColorSpace ]: {
  1010. transfer: SRGBTransfer,
  1011. primaries: Rec709Primaries,
  1012. toReference: ( color ) => color.convertSRGBToLinear(),
  1013. fromReference: ( color ) => color.convertLinearToSRGB(),
  1014. },
  1015. [ LinearDisplayP3ColorSpace ]: {
  1016. transfer: LinearTransfer,
  1017. primaries: P3Primaries,
  1018. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1019. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1020. },
  1021. [ DisplayP3ColorSpace ]: {
  1022. transfer: SRGBTransfer,
  1023. primaries: P3Primaries,
  1024. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1025. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1026. },
  1027. };
  1028. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1029. const ColorManagement = {
  1030. enabled: true,
  1031. _workingColorSpace: LinearSRGBColorSpace,
  1032. get workingColorSpace() {
  1033. return this._workingColorSpace;
  1034. },
  1035. set workingColorSpace( colorSpace ) {
  1036. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1037. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1038. }
  1039. this._workingColorSpace = colorSpace;
  1040. },
  1041. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1042. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1043. return color;
  1044. }
  1045. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1046. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1047. return targetFromReference( sourceToReference( color ) );
  1048. },
  1049. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1050. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1051. },
  1052. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1053. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1054. },
  1055. getPrimaries: function ( colorSpace ) {
  1056. return COLOR_SPACES[ colorSpace ].primaries;
  1057. },
  1058. getTransfer: function ( colorSpace ) {
  1059. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1060. return COLOR_SPACES[ colorSpace ].transfer;
  1061. },
  1062. };
  1063. function SRGBToLinear( c ) {
  1064. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1065. }
  1066. function LinearToSRGB( c ) {
  1067. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1068. }
  1069. let _canvas;
  1070. class ImageUtils {
  1071. static getDataURL( image ) {
  1072. if ( /^data:/i.test( image.src ) ) {
  1073. return image.src;
  1074. }
  1075. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1076. return image.src;
  1077. }
  1078. let canvas;
  1079. if ( image instanceof HTMLCanvasElement ) {
  1080. canvas = image;
  1081. } else {
  1082. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1083. _canvas.width = image.width;
  1084. _canvas.height = image.height;
  1085. const context = _canvas.getContext( '2d' );
  1086. if ( image instanceof ImageData ) {
  1087. context.putImageData( image, 0, 0 );
  1088. } else {
  1089. context.drawImage( image, 0, 0, image.width, image.height );
  1090. }
  1091. canvas = _canvas;
  1092. }
  1093. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1094. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1095. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1096. } else {
  1097. return canvas.toDataURL( 'image/png' );
  1098. }
  1099. }
  1100. static sRGBToLinear( image ) {
  1101. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1102. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1103. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1104. const canvas = createElementNS( 'canvas' );
  1105. canvas.width = image.width;
  1106. canvas.height = image.height;
  1107. const context = canvas.getContext( '2d' );
  1108. context.drawImage( image, 0, 0, image.width, image.height );
  1109. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1110. const data = imageData.data;
  1111. for ( let i = 0; i < data.length; i ++ ) {
  1112. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1113. }
  1114. context.putImageData( imageData, 0, 0 );
  1115. return canvas;
  1116. } else if ( image.data ) {
  1117. const data = image.data.slice( 0 );
  1118. for ( let i = 0; i < data.length; i ++ ) {
  1119. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1120. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1121. } else {
  1122. // assuming float
  1123. data[ i ] = SRGBToLinear( data[ i ] );
  1124. }
  1125. }
  1126. return {
  1127. data: data,
  1128. width: image.width,
  1129. height: image.height
  1130. };
  1131. } else {
  1132. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1133. return image;
  1134. }
  1135. }
  1136. }
  1137. let _sourceId = 0;
  1138. class Source {
  1139. constructor( data = null ) {
  1140. this.isSource = true;
  1141. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1142. this.uuid = generateUUID();
  1143. this.data = data;
  1144. this.dataReady = true;
  1145. this.version = 0;
  1146. }
  1147. set needsUpdate( value ) {
  1148. if ( value === true ) this.version ++;
  1149. }
  1150. toJSON( meta ) {
  1151. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1152. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1153. return meta.images[ this.uuid ];
  1154. }
  1155. const output = {
  1156. uuid: this.uuid,
  1157. url: ''
  1158. };
  1159. const data = this.data;
  1160. if ( data !== null ) {
  1161. let url;
  1162. if ( Array.isArray( data ) ) {
  1163. // cube texture
  1164. url = [];
  1165. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1166. if ( data[ i ].isDataTexture ) {
  1167. url.push( serializeImage( data[ i ].image ) );
  1168. } else {
  1169. url.push( serializeImage( data[ i ] ) );
  1170. }
  1171. }
  1172. } else {
  1173. // texture
  1174. url = serializeImage( data );
  1175. }
  1176. output.url = url;
  1177. }
  1178. if ( ! isRootObject ) {
  1179. meta.images[ this.uuid ] = output;
  1180. }
  1181. return output;
  1182. }
  1183. }
  1184. function serializeImage( image ) {
  1185. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1186. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1187. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1188. // default images
  1189. return ImageUtils.getDataURL( image );
  1190. } else {
  1191. if ( image.data ) {
  1192. // images of DataTexture
  1193. return {
  1194. data: Array.from( image.data ),
  1195. width: image.width,
  1196. height: image.height,
  1197. type: image.data.constructor.name
  1198. };
  1199. } else {
  1200. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1201. return {};
  1202. }
  1203. }
  1204. }
  1205. let _textureId = 0;
  1206. class Texture extends EventDispatcher {
  1207. 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 ) {
  1208. super();
  1209. this.isTexture = true;
  1210. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1211. this.uuid = generateUUID();
  1212. this.name = '';
  1213. this.source = new Source( image );
  1214. this.mipmaps = [];
  1215. this.mapping = mapping;
  1216. this.channel = 0;
  1217. this.wrapS = wrapS;
  1218. this.wrapT = wrapT;
  1219. this.magFilter = magFilter;
  1220. this.minFilter = minFilter;
  1221. this.anisotropy = anisotropy;
  1222. this.format = format;
  1223. this.internalFormat = null;
  1224. this.type = type;
  1225. this.offset = new Vector2( 0, 0 );
  1226. this.repeat = new Vector2( 1, 1 );
  1227. this.center = new Vector2( 0, 0 );
  1228. this.rotation = 0;
  1229. this.matrixAutoUpdate = true;
  1230. this.matrix = new Matrix3();
  1231. this.generateMipmaps = true;
  1232. this.premultiplyAlpha = false;
  1233. this.flipY = true;
  1234. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1235. this.colorSpace = colorSpace;
  1236. this.userData = {};
  1237. this.version = 0;
  1238. this.onUpdate = null;
  1239. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1240. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1241. }
  1242. get image() {
  1243. return this.source.data;
  1244. }
  1245. set image( value = null ) {
  1246. this.source.data = value;
  1247. }
  1248. updateMatrix() {
  1249. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1250. }
  1251. clone() {
  1252. return new this.constructor().copy( this );
  1253. }
  1254. copy( source ) {
  1255. this.name = source.name;
  1256. this.source = source.source;
  1257. this.mipmaps = source.mipmaps.slice( 0 );
  1258. this.mapping = source.mapping;
  1259. this.channel = source.channel;
  1260. this.wrapS = source.wrapS;
  1261. this.wrapT = source.wrapT;
  1262. this.magFilter = source.magFilter;
  1263. this.minFilter = source.minFilter;
  1264. this.anisotropy = source.anisotropy;
  1265. this.format = source.format;
  1266. this.internalFormat = source.internalFormat;
  1267. this.type = source.type;
  1268. this.offset.copy( source.offset );
  1269. this.repeat.copy( source.repeat );
  1270. this.center.copy( source.center );
  1271. this.rotation = source.rotation;
  1272. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1273. this.matrix.copy( source.matrix );
  1274. this.generateMipmaps = source.generateMipmaps;
  1275. this.premultiplyAlpha = source.premultiplyAlpha;
  1276. this.flipY = source.flipY;
  1277. this.unpackAlignment = source.unpackAlignment;
  1278. this.colorSpace = source.colorSpace;
  1279. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1280. this.needsUpdate = true;
  1281. return this;
  1282. }
  1283. toJSON( meta ) {
  1284. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1285. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1286. return meta.textures[ this.uuid ];
  1287. }
  1288. const output = {
  1289. metadata: {
  1290. version: 4.6,
  1291. type: 'Texture',
  1292. generator: 'Texture.toJSON'
  1293. },
  1294. uuid: this.uuid,
  1295. name: this.name,
  1296. image: this.source.toJSON( meta ).uuid,
  1297. mapping: this.mapping,
  1298. channel: this.channel,
  1299. repeat: [ this.repeat.x, this.repeat.y ],
  1300. offset: [ this.offset.x, this.offset.y ],
  1301. center: [ this.center.x, this.center.y ],
  1302. rotation: this.rotation,
  1303. wrap: [ this.wrapS, this.wrapT ],
  1304. format: this.format,
  1305. internalFormat: this.internalFormat,
  1306. type: this.type,
  1307. colorSpace: this.colorSpace,
  1308. minFilter: this.minFilter,
  1309. magFilter: this.magFilter,
  1310. anisotropy: this.anisotropy,
  1311. flipY: this.flipY,
  1312. generateMipmaps: this.generateMipmaps,
  1313. premultiplyAlpha: this.premultiplyAlpha,
  1314. unpackAlignment: this.unpackAlignment
  1315. };
  1316. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1317. if ( ! isRootObject ) {
  1318. meta.textures[ this.uuid ] = output;
  1319. }
  1320. return output;
  1321. }
  1322. dispose() {
  1323. this.dispatchEvent( { type: 'dispose' } );
  1324. }
  1325. transformUv( uv ) {
  1326. if ( this.mapping !== UVMapping ) return uv;
  1327. uv.applyMatrix3( this.matrix );
  1328. if ( uv.x < 0 || uv.x > 1 ) {
  1329. switch ( this.wrapS ) {
  1330. case RepeatWrapping:
  1331. uv.x = uv.x - Math.floor( uv.x );
  1332. break;
  1333. case ClampToEdgeWrapping:
  1334. uv.x = uv.x < 0 ? 0 : 1;
  1335. break;
  1336. case MirroredRepeatWrapping:
  1337. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1338. uv.x = Math.ceil( uv.x ) - uv.x;
  1339. } else {
  1340. uv.x = uv.x - Math.floor( uv.x );
  1341. }
  1342. break;
  1343. }
  1344. }
  1345. if ( uv.y < 0 || uv.y > 1 ) {
  1346. switch ( this.wrapT ) {
  1347. case RepeatWrapping:
  1348. uv.y = uv.y - Math.floor( uv.y );
  1349. break;
  1350. case ClampToEdgeWrapping:
  1351. uv.y = uv.y < 0 ? 0 : 1;
  1352. break;
  1353. case MirroredRepeatWrapping:
  1354. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1355. uv.y = Math.ceil( uv.y ) - uv.y;
  1356. } else {
  1357. uv.y = uv.y - Math.floor( uv.y );
  1358. }
  1359. break;
  1360. }
  1361. }
  1362. if ( this.flipY ) {
  1363. uv.y = 1 - uv.y;
  1364. }
  1365. return uv;
  1366. }
  1367. set needsUpdate( value ) {
  1368. if ( value === true ) {
  1369. this.version ++;
  1370. this.source.needsUpdate = true;
  1371. }
  1372. }
  1373. set needsPMREMUpdate( value ) {
  1374. if ( value === true ) {
  1375. this.pmremVersion ++;
  1376. }
  1377. }
  1378. }
  1379. Texture.DEFAULT_IMAGE = null;
  1380. Texture.DEFAULT_MAPPING = UVMapping;
  1381. Texture.DEFAULT_ANISOTROPY = 1;
  1382. class Vector4 {
  1383. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1384. Vector4.prototype.isVector4 = true;
  1385. this.x = x;
  1386. this.y = y;
  1387. this.z = z;
  1388. this.w = w;
  1389. }
  1390. get width() {
  1391. return this.z;
  1392. }
  1393. set width( value ) {
  1394. this.z = value;
  1395. }
  1396. get height() {
  1397. return this.w;
  1398. }
  1399. set height( value ) {
  1400. this.w = value;
  1401. }
  1402. set( x, y, z, w ) {
  1403. this.x = x;
  1404. this.y = y;
  1405. this.z = z;
  1406. this.w = w;
  1407. return this;
  1408. }
  1409. setScalar( scalar ) {
  1410. this.x = scalar;
  1411. this.y = scalar;
  1412. this.z = scalar;
  1413. this.w = scalar;
  1414. return this;
  1415. }
  1416. setX( x ) {
  1417. this.x = x;
  1418. return this;
  1419. }
  1420. setY( y ) {
  1421. this.y = y;
  1422. return this;
  1423. }
  1424. setZ( z ) {
  1425. this.z = z;
  1426. return this;
  1427. }
  1428. setW( w ) {
  1429. this.w = w;
  1430. return this;
  1431. }
  1432. setComponent( index, value ) {
  1433. switch ( index ) {
  1434. case 0: this.x = value; break;
  1435. case 1: this.y = value; break;
  1436. case 2: this.z = value; break;
  1437. case 3: this.w = value; break;
  1438. default: throw new Error( 'index is out of range: ' + index );
  1439. }
  1440. return this;
  1441. }
  1442. getComponent( index ) {
  1443. switch ( index ) {
  1444. case 0: return this.x;
  1445. case 1: return this.y;
  1446. case 2: return this.z;
  1447. case 3: return this.w;
  1448. default: throw new Error( 'index is out of range: ' + index );
  1449. }
  1450. }
  1451. clone() {
  1452. return new this.constructor( this.x, this.y, this.z, this.w );
  1453. }
  1454. copy( v ) {
  1455. this.x = v.x;
  1456. this.y = v.y;
  1457. this.z = v.z;
  1458. this.w = ( v.w !== undefined ) ? v.w : 1;
  1459. return this;
  1460. }
  1461. add( v ) {
  1462. this.x += v.x;
  1463. this.y += v.y;
  1464. this.z += v.z;
  1465. this.w += v.w;
  1466. return this;
  1467. }
  1468. addScalar( s ) {
  1469. this.x += s;
  1470. this.y += s;
  1471. this.z += s;
  1472. this.w += s;
  1473. return this;
  1474. }
  1475. addVectors( a, b ) {
  1476. this.x = a.x + b.x;
  1477. this.y = a.y + b.y;
  1478. this.z = a.z + b.z;
  1479. this.w = a.w + b.w;
  1480. return this;
  1481. }
  1482. addScaledVector( v, s ) {
  1483. this.x += v.x * s;
  1484. this.y += v.y * s;
  1485. this.z += v.z * s;
  1486. this.w += v.w * s;
  1487. return this;
  1488. }
  1489. sub( v ) {
  1490. this.x -= v.x;
  1491. this.y -= v.y;
  1492. this.z -= v.z;
  1493. this.w -= v.w;
  1494. return this;
  1495. }
  1496. subScalar( s ) {
  1497. this.x -= s;
  1498. this.y -= s;
  1499. this.z -= s;
  1500. this.w -= s;
  1501. return this;
  1502. }
  1503. subVectors( a, b ) {
  1504. this.x = a.x - b.x;
  1505. this.y = a.y - b.y;
  1506. this.z = a.z - b.z;
  1507. this.w = a.w - b.w;
  1508. return this;
  1509. }
  1510. multiply( v ) {
  1511. this.x *= v.x;
  1512. this.y *= v.y;
  1513. this.z *= v.z;
  1514. this.w *= v.w;
  1515. return this;
  1516. }
  1517. multiplyScalar( scalar ) {
  1518. this.x *= scalar;
  1519. this.y *= scalar;
  1520. this.z *= scalar;
  1521. this.w *= scalar;
  1522. return this;
  1523. }
  1524. applyMatrix4( m ) {
  1525. const x = this.x, y = this.y, z = this.z, w = this.w;
  1526. const e = m.elements;
  1527. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1528. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1529. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1530. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1531. return this;
  1532. }
  1533. divideScalar( scalar ) {
  1534. return this.multiplyScalar( 1 / scalar );
  1535. }
  1536. setAxisAngleFromQuaternion( q ) {
  1537. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1538. // q is assumed to be normalized
  1539. this.w = 2 * Math.acos( q.w );
  1540. const s = Math.sqrt( 1 - q.w * q.w );
  1541. if ( s < 0.0001 ) {
  1542. this.x = 1;
  1543. this.y = 0;
  1544. this.z = 0;
  1545. } else {
  1546. this.x = q.x / s;
  1547. this.y = q.y / s;
  1548. this.z = q.z / s;
  1549. }
  1550. return this;
  1551. }
  1552. setAxisAngleFromRotationMatrix( m ) {
  1553. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1554. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1555. let angle, x, y, z; // variables for result
  1556. const epsilon = 0.01, // margin to allow for rounding errors
  1557. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1558. te = m.elements,
  1559. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1560. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1561. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1562. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1563. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1564. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1565. // singularity found
  1566. // first check for identity matrix which must have +1 for all terms
  1567. // in leading diagonal and zero in other terms
  1568. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1569. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1570. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1571. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1572. // this singularity is identity matrix so angle = 0
  1573. this.set( 1, 0, 0, 0 );
  1574. return this; // zero angle, arbitrary axis
  1575. }
  1576. // otherwise this singularity is angle = 180
  1577. angle = Math.PI;
  1578. const xx = ( m11 + 1 ) / 2;
  1579. const yy = ( m22 + 1 ) / 2;
  1580. const zz = ( m33 + 1 ) / 2;
  1581. const xy = ( m12 + m21 ) / 4;
  1582. const xz = ( m13 + m31 ) / 4;
  1583. const yz = ( m23 + m32 ) / 4;
  1584. if ( ( xx > yy ) && ( xx > zz ) ) {
  1585. // m11 is the largest diagonal term
  1586. if ( xx < epsilon ) {
  1587. x = 0;
  1588. y = 0.707106781;
  1589. z = 0.707106781;
  1590. } else {
  1591. x = Math.sqrt( xx );
  1592. y = xy / x;
  1593. z = xz / x;
  1594. }
  1595. } else if ( yy > zz ) {
  1596. // m22 is the largest diagonal term
  1597. if ( yy < epsilon ) {
  1598. x = 0.707106781;
  1599. y = 0;
  1600. z = 0.707106781;
  1601. } else {
  1602. y = Math.sqrt( yy );
  1603. x = xy / y;
  1604. z = yz / y;
  1605. }
  1606. } else {
  1607. // m33 is the largest diagonal term so base result on this
  1608. if ( zz < epsilon ) {
  1609. x = 0.707106781;
  1610. y = 0.707106781;
  1611. z = 0;
  1612. } else {
  1613. z = Math.sqrt( zz );
  1614. x = xz / z;
  1615. y = yz / z;
  1616. }
  1617. }
  1618. this.set( x, y, z, angle );
  1619. return this; // return 180 deg rotation
  1620. }
  1621. // as we have reached here there are no singularities so we can handle normally
  1622. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1623. ( m13 - m31 ) * ( m13 - m31 ) +
  1624. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1625. if ( Math.abs( s ) < 0.001 ) s = 1;
  1626. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1627. // caught by singularity test above, but I've left it in just in case
  1628. this.x = ( m32 - m23 ) / s;
  1629. this.y = ( m13 - m31 ) / s;
  1630. this.z = ( m21 - m12 ) / s;
  1631. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1632. return this;
  1633. }
  1634. setFromMatrixPosition( m ) {
  1635. const e = m.elements;
  1636. this.x = e[ 12 ];
  1637. this.y = e[ 13 ];
  1638. this.z = e[ 14 ];
  1639. this.w = e[ 15 ];
  1640. return this;
  1641. }
  1642. min( v ) {
  1643. this.x = Math.min( this.x, v.x );
  1644. this.y = Math.min( this.y, v.y );
  1645. this.z = Math.min( this.z, v.z );
  1646. this.w = Math.min( this.w, v.w );
  1647. return this;
  1648. }
  1649. max( v ) {
  1650. this.x = Math.max( this.x, v.x );
  1651. this.y = Math.max( this.y, v.y );
  1652. this.z = Math.max( this.z, v.z );
  1653. this.w = Math.max( this.w, v.w );
  1654. return this;
  1655. }
  1656. clamp( min, max ) {
  1657. // assumes min < max, componentwise
  1658. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1659. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1660. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1661. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1662. return this;
  1663. }
  1664. clampScalar( minVal, maxVal ) {
  1665. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1666. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1667. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1668. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1669. return this;
  1670. }
  1671. clampLength( min, max ) {
  1672. const length = this.length();
  1673. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1674. }
  1675. floor() {
  1676. this.x = Math.floor( this.x );
  1677. this.y = Math.floor( this.y );
  1678. this.z = Math.floor( this.z );
  1679. this.w = Math.floor( this.w );
  1680. return this;
  1681. }
  1682. ceil() {
  1683. this.x = Math.ceil( this.x );
  1684. this.y = Math.ceil( this.y );
  1685. this.z = Math.ceil( this.z );
  1686. this.w = Math.ceil( this.w );
  1687. return this;
  1688. }
  1689. round() {
  1690. this.x = Math.round( this.x );
  1691. this.y = Math.round( this.y );
  1692. this.z = Math.round( this.z );
  1693. this.w = Math.round( this.w );
  1694. return this;
  1695. }
  1696. roundToZero() {
  1697. this.x = Math.trunc( this.x );
  1698. this.y = Math.trunc( this.y );
  1699. this.z = Math.trunc( this.z );
  1700. this.w = Math.trunc( this.w );
  1701. return this;
  1702. }
  1703. negate() {
  1704. this.x = - this.x;
  1705. this.y = - this.y;
  1706. this.z = - this.z;
  1707. this.w = - this.w;
  1708. return this;
  1709. }
  1710. dot( v ) {
  1711. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1712. }
  1713. lengthSq() {
  1714. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1715. }
  1716. length() {
  1717. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1718. }
  1719. manhattanLength() {
  1720. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1721. }
  1722. normalize() {
  1723. return this.divideScalar( this.length() || 1 );
  1724. }
  1725. setLength( length ) {
  1726. return this.normalize().multiplyScalar( length );
  1727. }
  1728. lerp( v, alpha ) {
  1729. this.x += ( v.x - this.x ) * alpha;
  1730. this.y += ( v.y - this.y ) * alpha;
  1731. this.z += ( v.z - this.z ) * alpha;
  1732. this.w += ( v.w - this.w ) * alpha;
  1733. return this;
  1734. }
  1735. lerpVectors( v1, v2, alpha ) {
  1736. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1737. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1738. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1739. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1740. return this;
  1741. }
  1742. equals( v ) {
  1743. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1744. }
  1745. fromArray( array, offset = 0 ) {
  1746. this.x = array[ offset ];
  1747. this.y = array[ offset + 1 ];
  1748. this.z = array[ offset + 2 ];
  1749. this.w = array[ offset + 3 ];
  1750. return this;
  1751. }
  1752. toArray( array = [], offset = 0 ) {
  1753. array[ offset ] = this.x;
  1754. array[ offset + 1 ] = this.y;
  1755. array[ offset + 2 ] = this.z;
  1756. array[ offset + 3 ] = this.w;
  1757. return array;
  1758. }
  1759. fromBufferAttribute( attribute, index ) {
  1760. this.x = attribute.getX( index );
  1761. this.y = attribute.getY( index );
  1762. this.z = attribute.getZ( index );
  1763. this.w = attribute.getW( index );
  1764. return this;
  1765. }
  1766. random() {
  1767. this.x = Math.random();
  1768. this.y = Math.random();
  1769. this.z = Math.random();
  1770. this.w = Math.random();
  1771. return this;
  1772. }
  1773. *[ Symbol.iterator ]() {
  1774. yield this.x;
  1775. yield this.y;
  1776. yield this.z;
  1777. yield this.w;
  1778. }
  1779. }
  1780. /*
  1781. In options, we can specify:
  1782. * Texture parameters for an auto-generated target texture
  1783. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1784. */
  1785. class RenderTarget extends EventDispatcher {
  1786. constructor( width = 1, height = 1, options = {} ) {
  1787. super();
  1788. this.isRenderTarget = true;
  1789. this.width = width;
  1790. this.height = height;
  1791. this.depth = 1;
  1792. this.scissor = new Vector4( 0, 0, width, height );
  1793. this.scissorTest = false;
  1794. this.viewport = new Vector4( 0, 0, width, height );
  1795. const image = { width: width, height: height, depth: 1 };
  1796. options = Object.assign( {
  1797. generateMipmaps: false,
  1798. internalFormat: null,
  1799. minFilter: LinearFilter,
  1800. depthBuffer: true,
  1801. stencilBuffer: false,
  1802. resolveDepthBuffer: true,
  1803. resolveStencilBuffer: true,
  1804. depthTexture: null,
  1805. samples: 0,
  1806. count: 1
  1807. }, options );
  1808. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1809. texture.flipY = false;
  1810. texture.generateMipmaps = options.generateMipmaps;
  1811. texture.internalFormat = options.internalFormat;
  1812. this.textures = [];
  1813. const count = options.count;
  1814. for ( let i = 0; i < count; i ++ ) {
  1815. this.textures[ i ] = texture.clone();
  1816. this.textures[ i ].isRenderTargetTexture = true;
  1817. }
  1818. this.depthBuffer = options.depthBuffer;
  1819. this.stencilBuffer = options.stencilBuffer;
  1820. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1821. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1822. this.depthTexture = options.depthTexture;
  1823. this.samples = options.samples;
  1824. }
  1825. get texture() {
  1826. return this.textures[ 0 ];
  1827. }
  1828. set texture( value ) {
  1829. this.textures[ 0 ] = value;
  1830. }
  1831. setSize( width, height, depth = 1 ) {
  1832. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1833. this.width = width;
  1834. this.height = height;
  1835. this.depth = depth;
  1836. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1837. this.textures[ i ].image.width = width;
  1838. this.textures[ i ].image.height = height;
  1839. this.textures[ i ].image.depth = depth;
  1840. }
  1841. this.dispose();
  1842. }
  1843. this.viewport.set( 0, 0, width, height );
  1844. this.scissor.set( 0, 0, width, height );
  1845. }
  1846. clone() {
  1847. return new this.constructor().copy( this );
  1848. }
  1849. copy( source ) {
  1850. this.width = source.width;
  1851. this.height = source.height;
  1852. this.depth = source.depth;
  1853. this.scissor.copy( source.scissor );
  1854. this.scissorTest = source.scissorTest;
  1855. this.viewport.copy( source.viewport );
  1856. this.textures.length = 0;
  1857. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1858. this.textures[ i ] = source.textures[ i ].clone();
  1859. this.textures[ i ].isRenderTargetTexture = true;
  1860. }
  1861. // ensure image object is not shared, see #20328
  1862. const image = Object.assign( {}, source.texture.image );
  1863. this.texture.source = new Source( image );
  1864. this.depthBuffer = source.depthBuffer;
  1865. this.stencilBuffer = source.stencilBuffer;
  1866. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1867. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1868. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1869. this.samples = source.samples;
  1870. return this;
  1871. }
  1872. dispose() {
  1873. this.dispatchEvent( { type: 'dispose' } );
  1874. }
  1875. }
  1876. class WebGLRenderTarget extends RenderTarget {
  1877. constructor( width = 1, height = 1, options = {} ) {
  1878. super( width, height, options );
  1879. this.isWebGLRenderTarget = true;
  1880. }
  1881. }
  1882. class DataArrayTexture extends Texture {
  1883. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1884. super( null );
  1885. this.isDataArrayTexture = true;
  1886. this.image = { data, width, height, depth };
  1887. this.magFilter = NearestFilter;
  1888. this.minFilter = NearestFilter;
  1889. this.wrapR = ClampToEdgeWrapping;
  1890. this.generateMipmaps = false;
  1891. this.flipY = false;
  1892. this.unpackAlignment = 1;
  1893. this.layerUpdates = new Set();
  1894. }
  1895. addLayerUpdate( layerIndex ) {
  1896. this.layerUpdates.add( layerIndex );
  1897. }
  1898. clearLayerUpdates() {
  1899. this.layerUpdates.clear();
  1900. }
  1901. }
  1902. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1903. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1904. super( width, height, options );
  1905. this.isWebGLArrayRenderTarget = true;
  1906. this.depth = depth;
  1907. this.texture = new DataArrayTexture( null, width, height, depth );
  1908. this.texture.isRenderTargetTexture = true;
  1909. }
  1910. }
  1911. class Data3DTexture extends Texture {
  1912. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1913. // We're going to add .setXXX() methods for setting properties later.
  1914. // Users can still set in DataTexture3D directly.
  1915. //
  1916. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1917. // texture.anisotropy = 16;
  1918. //
  1919. // See #14839
  1920. super( null );
  1921. this.isData3DTexture = true;
  1922. this.image = { data, width, height, depth };
  1923. this.magFilter = NearestFilter;
  1924. this.minFilter = NearestFilter;
  1925. this.wrapR = ClampToEdgeWrapping;
  1926. this.generateMipmaps = false;
  1927. this.flipY = false;
  1928. this.unpackAlignment = 1;
  1929. }
  1930. }
  1931. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1932. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1933. super( width, height, options );
  1934. this.isWebGL3DRenderTarget = true;
  1935. this.depth = depth;
  1936. this.texture = new Data3DTexture( null, width, height, depth );
  1937. this.texture.isRenderTargetTexture = true;
  1938. }
  1939. }
  1940. class Quaternion {
  1941. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1942. this.isQuaternion = true;
  1943. this._x = x;
  1944. this._y = y;
  1945. this._z = z;
  1946. this._w = w;
  1947. }
  1948. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1949. // fuzz-free, array-based Quaternion SLERP operation
  1950. let x0 = src0[ srcOffset0 + 0 ],
  1951. y0 = src0[ srcOffset0 + 1 ],
  1952. z0 = src0[ srcOffset0 + 2 ],
  1953. w0 = src0[ srcOffset0 + 3 ];
  1954. const x1 = src1[ srcOffset1 + 0 ],
  1955. y1 = src1[ srcOffset1 + 1 ],
  1956. z1 = src1[ srcOffset1 + 2 ],
  1957. w1 = src1[ srcOffset1 + 3 ];
  1958. if ( t === 0 ) {
  1959. dst[ dstOffset + 0 ] = x0;
  1960. dst[ dstOffset + 1 ] = y0;
  1961. dst[ dstOffset + 2 ] = z0;
  1962. dst[ dstOffset + 3 ] = w0;
  1963. return;
  1964. }
  1965. if ( t === 1 ) {
  1966. dst[ dstOffset + 0 ] = x1;
  1967. dst[ dstOffset + 1 ] = y1;
  1968. dst[ dstOffset + 2 ] = z1;
  1969. dst[ dstOffset + 3 ] = w1;
  1970. return;
  1971. }
  1972. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1973. let s = 1 - t;
  1974. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1975. dir = ( cos >= 0 ? 1 : - 1 ),
  1976. sqrSin = 1 - cos * cos;
  1977. // Skip the Slerp for tiny steps to avoid numeric problems:
  1978. if ( sqrSin > Number.EPSILON ) {
  1979. const sin = Math.sqrt( sqrSin ),
  1980. len = Math.atan2( sin, cos * dir );
  1981. s = Math.sin( s * len ) / sin;
  1982. t = Math.sin( t * len ) / sin;
  1983. }
  1984. const tDir = t * dir;
  1985. x0 = x0 * s + x1 * tDir;
  1986. y0 = y0 * s + y1 * tDir;
  1987. z0 = z0 * s + z1 * tDir;
  1988. w0 = w0 * s + w1 * tDir;
  1989. // Normalize in case we just did a lerp:
  1990. if ( s === 1 - t ) {
  1991. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1992. x0 *= f;
  1993. y0 *= f;
  1994. z0 *= f;
  1995. w0 *= f;
  1996. }
  1997. }
  1998. dst[ dstOffset ] = x0;
  1999. dst[ dstOffset + 1 ] = y0;
  2000. dst[ dstOffset + 2 ] = z0;
  2001. dst[ dstOffset + 3 ] = w0;
  2002. }
  2003. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2004. const x0 = src0[ srcOffset0 ];
  2005. const y0 = src0[ srcOffset0 + 1 ];
  2006. const z0 = src0[ srcOffset0 + 2 ];
  2007. const w0 = src0[ srcOffset0 + 3 ];
  2008. const x1 = src1[ srcOffset1 ];
  2009. const y1 = src1[ srcOffset1 + 1 ];
  2010. const z1 = src1[ srcOffset1 + 2 ];
  2011. const w1 = src1[ srcOffset1 + 3 ];
  2012. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2013. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2014. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2015. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2016. return dst;
  2017. }
  2018. get x() {
  2019. return this._x;
  2020. }
  2021. set x( value ) {
  2022. this._x = value;
  2023. this._onChangeCallback();
  2024. }
  2025. get y() {
  2026. return this._y;
  2027. }
  2028. set y( value ) {
  2029. this._y = value;
  2030. this._onChangeCallback();
  2031. }
  2032. get z() {
  2033. return this._z;
  2034. }
  2035. set z( value ) {
  2036. this._z = value;
  2037. this._onChangeCallback();
  2038. }
  2039. get w() {
  2040. return this._w;
  2041. }
  2042. set w( value ) {
  2043. this._w = value;
  2044. this._onChangeCallback();
  2045. }
  2046. set( x, y, z, w ) {
  2047. this._x = x;
  2048. this._y = y;
  2049. this._z = z;
  2050. this._w = w;
  2051. this._onChangeCallback();
  2052. return this;
  2053. }
  2054. clone() {
  2055. return new this.constructor( this._x, this._y, this._z, this._w );
  2056. }
  2057. copy( quaternion ) {
  2058. this._x = quaternion.x;
  2059. this._y = quaternion.y;
  2060. this._z = quaternion.z;
  2061. this._w = quaternion.w;
  2062. this._onChangeCallback();
  2063. return this;
  2064. }
  2065. setFromEuler( euler, update = true ) {
  2066. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2067. // http://www.mathworks.com/matlabcentral/fileexchange/
  2068. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2069. // content/SpinCalc.m
  2070. const cos = Math.cos;
  2071. const sin = Math.sin;
  2072. const c1 = cos( x / 2 );
  2073. const c2 = cos( y / 2 );
  2074. const c3 = cos( z / 2 );
  2075. const s1 = sin( x / 2 );
  2076. const s2 = sin( y / 2 );
  2077. const s3 = sin( z / 2 );
  2078. switch ( order ) {
  2079. case 'XYZ':
  2080. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2081. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2082. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2083. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2084. break;
  2085. case 'YXZ':
  2086. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2087. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2088. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2089. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2090. break;
  2091. case 'ZXY':
  2092. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2093. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2094. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2095. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2096. break;
  2097. case 'ZYX':
  2098. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2099. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2100. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2101. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2102. break;
  2103. case 'YZX':
  2104. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2105. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2106. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2107. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2108. break;
  2109. case 'XZY':
  2110. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2111. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2112. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2113. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2114. break;
  2115. default:
  2116. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2117. }
  2118. if ( update === true ) this._onChangeCallback();
  2119. return this;
  2120. }
  2121. setFromAxisAngle( axis, angle ) {
  2122. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2123. // assumes axis is normalized
  2124. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2125. this._x = axis.x * s;
  2126. this._y = axis.y * s;
  2127. this._z = axis.z * s;
  2128. this._w = Math.cos( halfAngle );
  2129. this._onChangeCallback();
  2130. return this;
  2131. }
  2132. setFromRotationMatrix( m ) {
  2133. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2134. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2135. const te = m.elements,
  2136. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2137. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2138. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2139. trace = m11 + m22 + m33;
  2140. if ( trace > 0 ) {
  2141. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2142. this._w = 0.25 / s;
  2143. this._x = ( m32 - m23 ) * s;
  2144. this._y = ( m13 - m31 ) * s;
  2145. this._z = ( m21 - m12 ) * s;
  2146. } else if ( m11 > m22 && m11 > m33 ) {
  2147. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2148. this._w = ( m32 - m23 ) / s;
  2149. this._x = 0.25 * s;
  2150. this._y = ( m12 + m21 ) / s;
  2151. this._z = ( m13 + m31 ) / s;
  2152. } else if ( m22 > m33 ) {
  2153. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2154. this._w = ( m13 - m31 ) / s;
  2155. this._x = ( m12 + m21 ) / s;
  2156. this._y = 0.25 * s;
  2157. this._z = ( m23 + m32 ) / s;
  2158. } else {
  2159. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2160. this._w = ( m21 - m12 ) / s;
  2161. this._x = ( m13 + m31 ) / s;
  2162. this._y = ( m23 + m32 ) / s;
  2163. this._z = 0.25 * s;
  2164. }
  2165. this._onChangeCallback();
  2166. return this;
  2167. }
  2168. setFromUnitVectors( vFrom, vTo ) {
  2169. // assumes direction vectors vFrom and vTo are normalized
  2170. let r = vFrom.dot( vTo ) + 1;
  2171. if ( r < Number.EPSILON ) {
  2172. // vFrom and vTo point in opposite directions
  2173. r = 0;
  2174. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2175. this._x = - vFrom.y;
  2176. this._y = vFrom.x;
  2177. this._z = 0;
  2178. this._w = r;
  2179. } else {
  2180. this._x = 0;
  2181. this._y = - vFrom.z;
  2182. this._z = vFrom.y;
  2183. this._w = r;
  2184. }
  2185. } else {
  2186. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2187. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2188. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2189. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2190. this._w = r;
  2191. }
  2192. return this.normalize();
  2193. }
  2194. angleTo( q ) {
  2195. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2196. }
  2197. rotateTowards( q, step ) {
  2198. const angle = this.angleTo( q );
  2199. if ( angle === 0 ) return this;
  2200. const t = Math.min( 1, step / angle );
  2201. this.slerp( q, t );
  2202. return this;
  2203. }
  2204. identity() {
  2205. return this.set( 0, 0, 0, 1 );
  2206. }
  2207. invert() {
  2208. // quaternion is assumed to have unit length
  2209. return this.conjugate();
  2210. }
  2211. conjugate() {
  2212. this._x *= - 1;
  2213. this._y *= - 1;
  2214. this._z *= - 1;
  2215. this._onChangeCallback();
  2216. return this;
  2217. }
  2218. dot( v ) {
  2219. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2220. }
  2221. lengthSq() {
  2222. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2223. }
  2224. length() {
  2225. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2226. }
  2227. normalize() {
  2228. let l = this.length();
  2229. if ( l === 0 ) {
  2230. this._x = 0;
  2231. this._y = 0;
  2232. this._z = 0;
  2233. this._w = 1;
  2234. } else {
  2235. l = 1 / l;
  2236. this._x = this._x * l;
  2237. this._y = this._y * l;
  2238. this._z = this._z * l;
  2239. this._w = this._w * l;
  2240. }
  2241. this._onChangeCallback();
  2242. return this;
  2243. }
  2244. multiply( q ) {
  2245. return this.multiplyQuaternions( this, q );
  2246. }
  2247. premultiply( q ) {
  2248. return this.multiplyQuaternions( q, this );
  2249. }
  2250. multiplyQuaternions( a, b ) {
  2251. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2252. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2253. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2254. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2255. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2256. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2257. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2258. this._onChangeCallback();
  2259. return this;
  2260. }
  2261. slerp( qb, t ) {
  2262. if ( t === 0 ) return this;
  2263. if ( t === 1 ) return this.copy( qb );
  2264. const x = this._x, y = this._y, z = this._z, w = this._w;
  2265. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2266. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2267. if ( cosHalfTheta < 0 ) {
  2268. this._w = - qb._w;
  2269. this._x = - qb._x;
  2270. this._y = - qb._y;
  2271. this._z = - qb._z;
  2272. cosHalfTheta = - cosHalfTheta;
  2273. } else {
  2274. this.copy( qb );
  2275. }
  2276. if ( cosHalfTheta >= 1.0 ) {
  2277. this._w = w;
  2278. this._x = x;
  2279. this._y = y;
  2280. this._z = z;
  2281. return this;
  2282. }
  2283. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2284. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2285. const s = 1 - t;
  2286. this._w = s * w + t * this._w;
  2287. this._x = s * x + t * this._x;
  2288. this._y = s * y + t * this._y;
  2289. this._z = s * z + t * this._z;
  2290. this.normalize(); // normalize calls _onChangeCallback()
  2291. return this;
  2292. }
  2293. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2294. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2295. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2296. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2297. this._w = ( w * ratioA + this._w * ratioB );
  2298. this._x = ( x * ratioA + this._x * ratioB );
  2299. this._y = ( y * ratioA + this._y * ratioB );
  2300. this._z = ( z * ratioA + this._z * ratioB );
  2301. this._onChangeCallback();
  2302. return this;
  2303. }
  2304. slerpQuaternions( qa, qb, t ) {
  2305. return this.copy( qa ).slerp( qb, t );
  2306. }
  2307. random() {
  2308. // sets this quaternion to a uniform random unit quaternnion
  2309. // Ken Shoemake
  2310. // Uniform random rotations
  2311. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2312. const theta1 = 2 * Math.PI * Math.random();
  2313. const theta2 = 2 * Math.PI * Math.random();
  2314. const x0 = Math.random();
  2315. const r1 = Math.sqrt( 1 - x0 );
  2316. const r2 = Math.sqrt( x0 );
  2317. return this.set(
  2318. r1 * Math.sin( theta1 ),
  2319. r1 * Math.cos( theta1 ),
  2320. r2 * Math.sin( theta2 ),
  2321. r2 * Math.cos( theta2 ),
  2322. );
  2323. }
  2324. equals( quaternion ) {
  2325. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2326. }
  2327. fromArray( array, offset = 0 ) {
  2328. this._x = array[ offset ];
  2329. this._y = array[ offset + 1 ];
  2330. this._z = array[ offset + 2 ];
  2331. this._w = array[ offset + 3 ];
  2332. this._onChangeCallback();
  2333. return this;
  2334. }
  2335. toArray( array = [], offset = 0 ) {
  2336. array[ offset ] = this._x;
  2337. array[ offset + 1 ] = this._y;
  2338. array[ offset + 2 ] = this._z;
  2339. array[ offset + 3 ] = this._w;
  2340. return array;
  2341. }
  2342. fromBufferAttribute( attribute, index ) {
  2343. this._x = attribute.getX( index );
  2344. this._y = attribute.getY( index );
  2345. this._z = attribute.getZ( index );
  2346. this._w = attribute.getW( index );
  2347. this._onChangeCallback();
  2348. return this;
  2349. }
  2350. toJSON() {
  2351. return this.toArray();
  2352. }
  2353. _onChange( callback ) {
  2354. this._onChangeCallback = callback;
  2355. return this;
  2356. }
  2357. _onChangeCallback() {}
  2358. *[ Symbol.iterator ]() {
  2359. yield this._x;
  2360. yield this._y;
  2361. yield this._z;
  2362. yield this._w;
  2363. }
  2364. }
  2365. class Vector3 {
  2366. constructor( x = 0, y = 0, z = 0 ) {
  2367. Vector3.prototype.isVector3 = true;
  2368. this.x = x;
  2369. this.y = y;
  2370. this.z = z;
  2371. }
  2372. set( x, y, z ) {
  2373. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2374. this.x = x;
  2375. this.y = y;
  2376. this.z = z;
  2377. return this;
  2378. }
  2379. setScalar( scalar ) {
  2380. this.x = scalar;
  2381. this.y = scalar;
  2382. this.z = scalar;
  2383. return this;
  2384. }
  2385. setX( x ) {
  2386. this.x = x;
  2387. return this;
  2388. }
  2389. setY( y ) {
  2390. this.y = y;
  2391. return this;
  2392. }
  2393. setZ( z ) {
  2394. this.z = z;
  2395. return this;
  2396. }
  2397. setComponent( index, value ) {
  2398. switch ( index ) {
  2399. case 0: this.x = value; break;
  2400. case 1: this.y = value; break;
  2401. case 2: this.z = value; break;
  2402. default: throw new Error( 'index is out of range: ' + index );
  2403. }
  2404. return this;
  2405. }
  2406. getComponent( index ) {
  2407. switch ( index ) {
  2408. case 0: return this.x;
  2409. case 1: return this.y;
  2410. case 2: return this.z;
  2411. default: throw new Error( 'index is out of range: ' + index );
  2412. }
  2413. }
  2414. clone() {
  2415. return new this.constructor( this.x, this.y, this.z );
  2416. }
  2417. copy( v ) {
  2418. this.x = v.x;
  2419. this.y = v.y;
  2420. this.z = v.z;
  2421. return this;
  2422. }
  2423. add( v ) {
  2424. this.x += v.x;
  2425. this.y += v.y;
  2426. this.z += v.z;
  2427. return this;
  2428. }
  2429. addScalar( s ) {
  2430. this.x += s;
  2431. this.y += s;
  2432. this.z += s;
  2433. return this;
  2434. }
  2435. addVectors( a, b ) {
  2436. this.x = a.x + b.x;
  2437. this.y = a.y + b.y;
  2438. this.z = a.z + b.z;
  2439. return this;
  2440. }
  2441. addScaledVector( v, s ) {
  2442. this.x += v.x * s;
  2443. this.y += v.y * s;
  2444. this.z += v.z * s;
  2445. return this;
  2446. }
  2447. sub( v ) {
  2448. this.x -= v.x;
  2449. this.y -= v.y;
  2450. this.z -= v.z;
  2451. return this;
  2452. }
  2453. subScalar( s ) {
  2454. this.x -= s;
  2455. this.y -= s;
  2456. this.z -= s;
  2457. return this;
  2458. }
  2459. subVectors( a, b ) {
  2460. this.x = a.x - b.x;
  2461. this.y = a.y - b.y;
  2462. this.z = a.z - b.z;
  2463. return this;
  2464. }
  2465. multiply( v ) {
  2466. this.x *= v.x;
  2467. this.y *= v.y;
  2468. this.z *= v.z;
  2469. return this;
  2470. }
  2471. multiplyScalar( scalar ) {
  2472. this.x *= scalar;
  2473. this.y *= scalar;
  2474. this.z *= scalar;
  2475. return this;
  2476. }
  2477. multiplyVectors( a, b ) {
  2478. this.x = a.x * b.x;
  2479. this.y = a.y * b.y;
  2480. this.z = a.z * b.z;
  2481. return this;
  2482. }
  2483. applyEuler( euler ) {
  2484. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2485. }
  2486. applyAxisAngle( axis, angle ) {
  2487. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2488. }
  2489. applyMatrix3( m ) {
  2490. const x = this.x, y = this.y, z = this.z;
  2491. const e = m.elements;
  2492. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2493. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2494. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2495. return this;
  2496. }
  2497. applyNormalMatrix( m ) {
  2498. return this.applyMatrix3( m ).normalize();
  2499. }
  2500. applyMatrix4( m ) {
  2501. const x = this.x, y = this.y, z = this.z;
  2502. const e = m.elements;
  2503. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2504. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2505. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2506. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2507. return this;
  2508. }
  2509. applyQuaternion( q ) {
  2510. // quaternion q is assumed to have unit length
  2511. const vx = this.x, vy = this.y, vz = this.z;
  2512. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2513. // t = 2 * cross( q.xyz, v );
  2514. const tx = 2 * ( qy * vz - qz * vy );
  2515. const ty = 2 * ( qz * vx - qx * vz );
  2516. const tz = 2 * ( qx * vy - qy * vx );
  2517. // v + q.w * t + cross( q.xyz, t );
  2518. this.x = vx + qw * tx + qy * tz - qz * ty;
  2519. this.y = vy + qw * ty + qz * tx - qx * tz;
  2520. this.z = vz + qw * tz + qx * ty - qy * tx;
  2521. return this;
  2522. }
  2523. project( camera ) {
  2524. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2525. }
  2526. unproject( camera ) {
  2527. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2528. }
  2529. transformDirection( m ) {
  2530. // input: THREE.Matrix4 affine matrix
  2531. // vector interpreted as a direction
  2532. const x = this.x, y = this.y, z = this.z;
  2533. const e = m.elements;
  2534. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2535. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2536. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2537. return this.normalize();
  2538. }
  2539. divide( v ) {
  2540. this.x /= v.x;
  2541. this.y /= v.y;
  2542. this.z /= v.z;
  2543. return this;
  2544. }
  2545. divideScalar( scalar ) {
  2546. return this.multiplyScalar( 1 / scalar );
  2547. }
  2548. min( v ) {
  2549. this.x = Math.min( this.x, v.x );
  2550. this.y = Math.min( this.y, v.y );
  2551. this.z = Math.min( this.z, v.z );
  2552. return this;
  2553. }
  2554. max( v ) {
  2555. this.x = Math.max( this.x, v.x );
  2556. this.y = Math.max( this.y, v.y );
  2557. this.z = Math.max( this.z, v.z );
  2558. return this;
  2559. }
  2560. clamp( min, max ) {
  2561. // assumes min < max, componentwise
  2562. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2563. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2564. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2565. return this;
  2566. }
  2567. clampScalar( minVal, maxVal ) {
  2568. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2569. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2570. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2571. return this;
  2572. }
  2573. clampLength( min, max ) {
  2574. const length = this.length();
  2575. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2576. }
  2577. floor() {
  2578. this.x = Math.floor( this.x );
  2579. this.y = Math.floor( this.y );
  2580. this.z = Math.floor( this.z );
  2581. return this;
  2582. }
  2583. ceil() {
  2584. this.x = Math.ceil( this.x );
  2585. this.y = Math.ceil( this.y );
  2586. this.z = Math.ceil( this.z );
  2587. return this;
  2588. }
  2589. round() {
  2590. this.x = Math.round( this.x );
  2591. this.y = Math.round( this.y );
  2592. this.z = Math.round( this.z );
  2593. return this;
  2594. }
  2595. roundToZero() {
  2596. this.x = Math.trunc( this.x );
  2597. this.y = Math.trunc( this.y );
  2598. this.z = Math.trunc( this.z );
  2599. return this;
  2600. }
  2601. negate() {
  2602. this.x = - this.x;
  2603. this.y = - this.y;
  2604. this.z = - this.z;
  2605. return this;
  2606. }
  2607. dot( v ) {
  2608. return this.x * v.x + this.y * v.y + this.z * v.z;
  2609. }
  2610. // TODO lengthSquared?
  2611. lengthSq() {
  2612. return this.x * this.x + this.y * this.y + this.z * this.z;
  2613. }
  2614. length() {
  2615. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2616. }
  2617. manhattanLength() {
  2618. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2619. }
  2620. normalize() {
  2621. return this.divideScalar( this.length() || 1 );
  2622. }
  2623. setLength( length ) {
  2624. return this.normalize().multiplyScalar( length );
  2625. }
  2626. lerp( v, alpha ) {
  2627. this.x += ( v.x - this.x ) * alpha;
  2628. this.y += ( v.y - this.y ) * alpha;
  2629. this.z += ( v.z - this.z ) * alpha;
  2630. return this;
  2631. }
  2632. lerpVectors( v1, v2, alpha ) {
  2633. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2634. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2635. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2636. return this;
  2637. }
  2638. cross( v ) {
  2639. return this.crossVectors( this, v );
  2640. }
  2641. crossVectors( a, b ) {
  2642. const ax = a.x, ay = a.y, az = a.z;
  2643. const bx = b.x, by = b.y, bz = b.z;
  2644. this.x = ay * bz - az * by;
  2645. this.y = az * bx - ax * bz;
  2646. this.z = ax * by - ay * bx;
  2647. return this;
  2648. }
  2649. projectOnVector( v ) {
  2650. const denominator = v.lengthSq();
  2651. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2652. const scalar = v.dot( this ) / denominator;
  2653. return this.copy( v ).multiplyScalar( scalar );
  2654. }
  2655. projectOnPlane( planeNormal ) {
  2656. _vector$c.copy( this ).projectOnVector( planeNormal );
  2657. return this.sub( _vector$c );
  2658. }
  2659. reflect( normal ) {
  2660. // reflect incident vector off plane orthogonal to normal
  2661. // normal is assumed to have unit length
  2662. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2663. }
  2664. angleTo( v ) {
  2665. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2666. if ( denominator === 0 ) return Math.PI / 2;
  2667. const theta = this.dot( v ) / denominator;
  2668. // clamp, to handle numerical problems
  2669. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2670. }
  2671. distanceTo( v ) {
  2672. return Math.sqrt( this.distanceToSquared( v ) );
  2673. }
  2674. distanceToSquared( v ) {
  2675. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2676. return dx * dx + dy * dy + dz * dz;
  2677. }
  2678. manhattanDistanceTo( v ) {
  2679. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2680. }
  2681. setFromSpherical( s ) {
  2682. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2683. }
  2684. setFromSphericalCoords( radius, phi, theta ) {
  2685. const sinPhiRadius = Math.sin( phi ) * radius;
  2686. this.x = sinPhiRadius * Math.sin( theta );
  2687. this.y = Math.cos( phi ) * radius;
  2688. this.z = sinPhiRadius * Math.cos( theta );
  2689. return this;
  2690. }
  2691. setFromCylindrical( c ) {
  2692. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2693. }
  2694. setFromCylindricalCoords( radius, theta, y ) {
  2695. this.x = radius * Math.sin( theta );
  2696. this.y = y;
  2697. this.z = radius * Math.cos( theta );
  2698. return this;
  2699. }
  2700. setFromMatrixPosition( m ) {
  2701. const e = m.elements;
  2702. this.x = e[ 12 ];
  2703. this.y = e[ 13 ];
  2704. this.z = e[ 14 ];
  2705. return this;
  2706. }
  2707. setFromMatrixScale( m ) {
  2708. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2709. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2710. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2711. this.x = sx;
  2712. this.y = sy;
  2713. this.z = sz;
  2714. return this;
  2715. }
  2716. setFromMatrixColumn( m, index ) {
  2717. return this.fromArray( m.elements, index * 4 );
  2718. }
  2719. setFromMatrix3Column( m, index ) {
  2720. return this.fromArray( m.elements, index * 3 );
  2721. }
  2722. setFromEuler( e ) {
  2723. this.x = e._x;
  2724. this.y = e._y;
  2725. this.z = e._z;
  2726. return this;
  2727. }
  2728. setFromColor( c ) {
  2729. this.x = c.r;
  2730. this.y = c.g;
  2731. this.z = c.b;
  2732. return this;
  2733. }
  2734. equals( v ) {
  2735. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2736. }
  2737. fromArray( array, offset = 0 ) {
  2738. this.x = array[ offset ];
  2739. this.y = array[ offset + 1 ];
  2740. this.z = array[ offset + 2 ];
  2741. return this;
  2742. }
  2743. toArray( array = [], offset = 0 ) {
  2744. array[ offset ] = this.x;
  2745. array[ offset + 1 ] = this.y;
  2746. array[ offset + 2 ] = this.z;
  2747. return array;
  2748. }
  2749. fromBufferAttribute( attribute, index ) {
  2750. this.x = attribute.getX( index );
  2751. this.y = attribute.getY( index );
  2752. this.z = attribute.getZ( index );
  2753. return this;
  2754. }
  2755. random() {
  2756. this.x = Math.random();
  2757. this.y = Math.random();
  2758. this.z = Math.random();
  2759. return this;
  2760. }
  2761. randomDirection() {
  2762. // https://mathworld.wolfram.com/SpherePointPicking.html
  2763. const theta = Math.random() * Math.PI * 2;
  2764. const u = Math.random() * 2 - 1;
  2765. const c = Math.sqrt( 1 - u * u );
  2766. this.x = c * Math.cos( theta );
  2767. this.y = u;
  2768. this.z = c * Math.sin( theta );
  2769. return this;
  2770. }
  2771. *[ Symbol.iterator ]() {
  2772. yield this.x;
  2773. yield this.y;
  2774. yield this.z;
  2775. }
  2776. }
  2777. const _vector$c = /*@__PURE__*/ new Vector3();
  2778. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2779. class Box3 {
  2780. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2781. this.isBox3 = true;
  2782. this.min = min;
  2783. this.max = max;
  2784. }
  2785. set( min, max ) {
  2786. this.min.copy( min );
  2787. this.max.copy( max );
  2788. return this;
  2789. }
  2790. setFromArray( array ) {
  2791. this.makeEmpty();
  2792. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2793. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2794. }
  2795. return this;
  2796. }
  2797. setFromBufferAttribute( attribute ) {
  2798. this.makeEmpty();
  2799. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2800. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2801. }
  2802. return this;
  2803. }
  2804. setFromPoints( points ) {
  2805. this.makeEmpty();
  2806. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2807. this.expandByPoint( points[ i ] );
  2808. }
  2809. return this;
  2810. }
  2811. setFromCenterAndSize( center, size ) {
  2812. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2813. this.min.copy( center ).sub( halfSize );
  2814. this.max.copy( center ).add( halfSize );
  2815. return this;
  2816. }
  2817. setFromObject( object, precise = false ) {
  2818. this.makeEmpty();
  2819. return this.expandByObject( object, precise );
  2820. }
  2821. clone() {
  2822. return new this.constructor().copy( this );
  2823. }
  2824. copy( box ) {
  2825. this.min.copy( box.min );
  2826. this.max.copy( box.max );
  2827. return this;
  2828. }
  2829. makeEmpty() {
  2830. this.min.x = this.min.y = this.min.z = + Infinity;
  2831. this.max.x = this.max.y = this.max.z = - Infinity;
  2832. return this;
  2833. }
  2834. isEmpty() {
  2835. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2836. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2837. }
  2838. getCenter( target ) {
  2839. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2840. }
  2841. getSize( target ) {
  2842. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2843. }
  2844. expandByPoint( point ) {
  2845. this.min.min( point );
  2846. this.max.max( point );
  2847. return this;
  2848. }
  2849. expandByVector( vector ) {
  2850. this.min.sub( vector );
  2851. this.max.add( vector );
  2852. return this;
  2853. }
  2854. expandByScalar( scalar ) {
  2855. this.min.addScalar( - scalar );
  2856. this.max.addScalar( scalar );
  2857. return this;
  2858. }
  2859. expandByObject( object, precise = false ) {
  2860. // Computes the world-axis-aligned bounding box of an object (including its children),
  2861. // accounting for both the object's, and children's, world transforms
  2862. object.updateWorldMatrix( false, false );
  2863. const geometry = object.geometry;
  2864. if ( geometry !== undefined ) {
  2865. const positionAttribute = geometry.getAttribute( 'position' );
  2866. // precise AABB computation based on vertex data requires at least a position attribute.
  2867. // instancing isn't supported so far and uses the normal (conservative) code path.
  2868. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2869. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2870. if ( object.isMesh === true ) {
  2871. object.getVertexPosition( i, _vector$b );
  2872. } else {
  2873. _vector$b.fromBufferAttribute( positionAttribute, i );
  2874. }
  2875. _vector$b.applyMatrix4( object.matrixWorld );
  2876. this.expandByPoint( _vector$b );
  2877. }
  2878. } else {
  2879. if ( object.boundingBox !== undefined ) {
  2880. // object-level bounding box
  2881. if ( object.boundingBox === null ) {
  2882. object.computeBoundingBox();
  2883. }
  2884. _box$4.copy( object.boundingBox );
  2885. } else {
  2886. // geometry-level bounding box
  2887. if ( geometry.boundingBox === null ) {
  2888. geometry.computeBoundingBox();
  2889. }
  2890. _box$4.copy( geometry.boundingBox );
  2891. }
  2892. _box$4.applyMatrix4( object.matrixWorld );
  2893. this.union( _box$4 );
  2894. }
  2895. }
  2896. const children = object.children;
  2897. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2898. this.expandByObject( children[ i ], precise );
  2899. }
  2900. return this;
  2901. }
  2902. containsPoint( point ) {
  2903. return point.x < this.min.x || point.x > this.max.x ||
  2904. point.y < this.min.y || point.y > this.max.y ||
  2905. point.z < this.min.z || point.z > this.max.z ? false : true;
  2906. }
  2907. containsBox( box ) {
  2908. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2909. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2910. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2911. }
  2912. getParameter( point, target ) {
  2913. // This can potentially have a divide by zero if the box
  2914. // has a size dimension of 0.
  2915. return target.set(
  2916. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2917. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2918. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2919. );
  2920. }
  2921. intersectsBox( box ) {
  2922. // using 6 splitting planes to rule out intersections.
  2923. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2924. box.max.y < this.min.y || box.min.y > this.max.y ||
  2925. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2926. }
  2927. intersectsSphere( sphere ) {
  2928. // Find the point on the AABB closest to the sphere center.
  2929. this.clampPoint( sphere.center, _vector$b );
  2930. // If that point is inside the sphere, the AABB and sphere intersect.
  2931. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2932. }
  2933. intersectsPlane( plane ) {
  2934. // We compute the minimum and maximum dot product values. If those values
  2935. // are on the same side (back or front) of the plane, then there is no intersection.
  2936. let min, max;
  2937. if ( plane.normal.x > 0 ) {
  2938. min = plane.normal.x * this.min.x;
  2939. max = plane.normal.x * this.max.x;
  2940. } else {
  2941. min = plane.normal.x * this.max.x;
  2942. max = plane.normal.x * this.min.x;
  2943. }
  2944. if ( plane.normal.y > 0 ) {
  2945. min += plane.normal.y * this.min.y;
  2946. max += plane.normal.y * this.max.y;
  2947. } else {
  2948. min += plane.normal.y * this.max.y;
  2949. max += plane.normal.y * this.min.y;
  2950. }
  2951. if ( plane.normal.z > 0 ) {
  2952. min += plane.normal.z * this.min.z;
  2953. max += plane.normal.z * this.max.z;
  2954. } else {
  2955. min += plane.normal.z * this.max.z;
  2956. max += plane.normal.z * this.min.z;
  2957. }
  2958. return ( min <= - plane.constant && max >= - plane.constant );
  2959. }
  2960. intersectsTriangle( triangle ) {
  2961. if ( this.isEmpty() ) {
  2962. return false;
  2963. }
  2964. // compute box center and extents
  2965. this.getCenter( _center );
  2966. _extents.subVectors( this.max, _center );
  2967. // translate triangle to aabb origin
  2968. _v0$2.subVectors( triangle.a, _center );
  2969. _v1$7.subVectors( triangle.b, _center );
  2970. _v2$4.subVectors( triangle.c, _center );
  2971. // compute edge vectors for triangle
  2972. _f0.subVectors( _v1$7, _v0$2 );
  2973. _f1.subVectors( _v2$4, _v1$7 );
  2974. _f2.subVectors( _v0$2, _v2$4 );
  2975. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2976. // 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
  2977. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2978. let axes = [
  2979. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2980. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2981. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2982. ];
  2983. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2984. return false;
  2985. }
  2986. // test 3 face normals from the aabb
  2987. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2988. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2989. return false;
  2990. }
  2991. // finally testing the face normal of the triangle
  2992. // use already existing triangle edge vectors here
  2993. _triangleNormal.crossVectors( _f0, _f1 );
  2994. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2995. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2996. }
  2997. clampPoint( point, target ) {
  2998. return target.copy( point ).clamp( this.min, this.max );
  2999. }
  3000. distanceToPoint( point ) {
  3001. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3002. }
  3003. getBoundingSphere( target ) {
  3004. if ( this.isEmpty() ) {
  3005. target.makeEmpty();
  3006. } else {
  3007. this.getCenter( target.center );
  3008. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3009. }
  3010. return target;
  3011. }
  3012. intersect( box ) {
  3013. this.min.max( box.min );
  3014. this.max.min( box.max );
  3015. // 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.
  3016. if ( this.isEmpty() ) this.makeEmpty();
  3017. return this;
  3018. }
  3019. union( box ) {
  3020. this.min.min( box.min );
  3021. this.max.max( box.max );
  3022. return this;
  3023. }
  3024. applyMatrix4( matrix ) {
  3025. // transform of empty box is an empty box.
  3026. if ( this.isEmpty() ) return this;
  3027. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3028. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3029. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3030. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3031. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3032. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3033. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3034. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3035. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3036. this.setFromPoints( _points );
  3037. return this;
  3038. }
  3039. translate( offset ) {
  3040. this.min.add( offset );
  3041. this.max.add( offset );
  3042. return this;
  3043. }
  3044. equals( box ) {
  3045. return box.min.equals( this.min ) && box.max.equals( this.max );
  3046. }
  3047. }
  3048. const _points = [
  3049. /*@__PURE__*/ new Vector3(),
  3050. /*@__PURE__*/ new Vector3(),
  3051. /*@__PURE__*/ new Vector3(),
  3052. /*@__PURE__*/ new Vector3(),
  3053. /*@__PURE__*/ new Vector3(),
  3054. /*@__PURE__*/ new Vector3(),
  3055. /*@__PURE__*/ new Vector3(),
  3056. /*@__PURE__*/ new Vector3()
  3057. ];
  3058. const _vector$b = /*@__PURE__*/ new Vector3();
  3059. const _box$4 = /*@__PURE__*/ new Box3();
  3060. // triangle centered vertices
  3061. const _v0$2 = /*@__PURE__*/ new Vector3();
  3062. const _v1$7 = /*@__PURE__*/ new Vector3();
  3063. const _v2$4 = /*@__PURE__*/ new Vector3();
  3064. // triangle edge vectors
  3065. const _f0 = /*@__PURE__*/ new Vector3();
  3066. const _f1 = /*@__PURE__*/ new Vector3();
  3067. const _f2 = /*@__PURE__*/ new Vector3();
  3068. const _center = /*@__PURE__*/ new Vector3();
  3069. const _extents = /*@__PURE__*/ new Vector3();
  3070. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3071. const _testAxis = /*@__PURE__*/ new Vector3();
  3072. function satForAxes( axes, v0, v1, v2, extents ) {
  3073. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3074. _testAxis.fromArray( axes, i );
  3075. // project the aabb onto the separating axis
  3076. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3077. // project all 3 vertices of the triangle onto the separating axis
  3078. const p0 = v0.dot( _testAxis );
  3079. const p1 = v1.dot( _testAxis );
  3080. const p2 = v2.dot( _testAxis );
  3081. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3082. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3083. // points of the projected triangle are outside the projected half-length of the aabb
  3084. // the axis is separating and we can exit
  3085. return false;
  3086. }
  3087. }
  3088. return true;
  3089. }
  3090. const _box$3 = /*@__PURE__*/ new Box3();
  3091. const _v1$6 = /*@__PURE__*/ new Vector3();
  3092. const _v2$3 = /*@__PURE__*/ new Vector3();
  3093. class Sphere {
  3094. constructor( center = new Vector3(), radius = - 1 ) {
  3095. this.isSphere = true;
  3096. this.center = center;
  3097. this.radius = radius;
  3098. }
  3099. set( center, radius ) {
  3100. this.center.copy( center );
  3101. this.radius = radius;
  3102. return this;
  3103. }
  3104. setFromPoints( points, optionalCenter ) {
  3105. const center = this.center;
  3106. if ( optionalCenter !== undefined ) {
  3107. center.copy( optionalCenter );
  3108. } else {
  3109. _box$3.setFromPoints( points ).getCenter( center );
  3110. }
  3111. let maxRadiusSq = 0;
  3112. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3113. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3114. }
  3115. this.radius = Math.sqrt( maxRadiusSq );
  3116. return this;
  3117. }
  3118. copy( sphere ) {
  3119. this.center.copy( sphere.center );
  3120. this.radius = sphere.radius;
  3121. return this;
  3122. }
  3123. isEmpty() {
  3124. return ( this.radius < 0 );
  3125. }
  3126. makeEmpty() {
  3127. this.center.set( 0, 0, 0 );
  3128. this.radius = - 1;
  3129. return this;
  3130. }
  3131. containsPoint( point ) {
  3132. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3133. }
  3134. distanceToPoint( point ) {
  3135. return ( point.distanceTo( this.center ) - this.radius );
  3136. }
  3137. intersectsSphere( sphere ) {
  3138. const radiusSum = this.radius + sphere.radius;
  3139. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3140. }
  3141. intersectsBox( box ) {
  3142. return box.intersectsSphere( this );
  3143. }
  3144. intersectsPlane( plane ) {
  3145. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3146. }
  3147. clampPoint( point, target ) {
  3148. const deltaLengthSq = this.center.distanceToSquared( point );
  3149. target.copy( point );
  3150. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3151. target.sub( this.center ).normalize();
  3152. target.multiplyScalar( this.radius ).add( this.center );
  3153. }
  3154. return target;
  3155. }
  3156. getBoundingBox( target ) {
  3157. if ( this.isEmpty() ) {
  3158. // Empty sphere produces empty bounding box
  3159. target.makeEmpty();
  3160. return target;
  3161. }
  3162. target.set( this.center, this.center );
  3163. target.expandByScalar( this.radius );
  3164. return target;
  3165. }
  3166. applyMatrix4( matrix ) {
  3167. this.center.applyMatrix4( matrix );
  3168. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3169. return this;
  3170. }
  3171. translate( offset ) {
  3172. this.center.add( offset );
  3173. return this;
  3174. }
  3175. expandByPoint( point ) {
  3176. if ( this.isEmpty() ) {
  3177. this.center.copy( point );
  3178. this.radius = 0;
  3179. return this;
  3180. }
  3181. _v1$6.subVectors( point, this.center );
  3182. const lengthSq = _v1$6.lengthSq();
  3183. if ( lengthSq > ( this.radius * this.radius ) ) {
  3184. // calculate the minimal sphere
  3185. const length = Math.sqrt( lengthSq );
  3186. const delta = ( length - this.radius ) * 0.5;
  3187. this.center.addScaledVector( _v1$6, delta / length );
  3188. this.radius += delta;
  3189. }
  3190. return this;
  3191. }
  3192. union( sphere ) {
  3193. if ( sphere.isEmpty() ) {
  3194. return this;
  3195. }
  3196. if ( this.isEmpty() ) {
  3197. this.copy( sphere );
  3198. return this;
  3199. }
  3200. if ( this.center.equals( sphere.center ) === true ) {
  3201. this.radius = Math.max( this.radius, sphere.radius );
  3202. } else {
  3203. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3204. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3205. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3206. }
  3207. return this;
  3208. }
  3209. equals( sphere ) {
  3210. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3211. }
  3212. clone() {
  3213. return new this.constructor().copy( this );
  3214. }
  3215. }
  3216. const _vector$a = /*@__PURE__*/ new Vector3();
  3217. const _segCenter = /*@__PURE__*/ new Vector3();
  3218. const _segDir = /*@__PURE__*/ new Vector3();
  3219. const _diff = /*@__PURE__*/ new Vector3();
  3220. const _edge1 = /*@__PURE__*/ new Vector3();
  3221. const _edge2 = /*@__PURE__*/ new Vector3();
  3222. const _normal$2 = /*@__PURE__*/ new Vector3();
  3223. class Ray {
  3224. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3225. this.origin = origin;
  3226. this.direction = direction;
  3227. }
  3228. set( origin, direction ) {
  3229. this.origin.copy( origin );
  3230. this.direction.copy( direction );
  3231. return this;
  3232. }
  3233. copy( ray ) {
  3234. this.origin.copy( ray.origin );
  3235. this.direction.copy( ray.direction );
  3236. return this;
  3237. }
  3238. at( t, target ) {
  3239. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3240. }
  3241. lookAt( v ) {
  3242. this.direction.copy( v ).sub( this.origin ).normalize();
  3243. return this;
  3244. }
  3245. recast( t ) {
  3246. this.origin.copy( this.at( t, _vector$a ) );
  3247. return this;
  3248. }
  3249. closestPointToPoint( point, target ) {
  3250. target.subVectors( point, this.origin );
  3251. const directionDistance = target.dot( this.direction );
  3252. if ( directionDistance < 0 ) {
  3253. return target.copy( this.origin );
  3254. }
  3255. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3256. }
  3257. distanceToPoint( point ) {
  3258. return Math.sqrt( this.distanceSqToPoint( point ) );
  3259. }
  3260. distanceSqToPoint( point ) {
  3261. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3262. // point behind the ray
  3263. if ( directionDistance < 0 ) {
  3264. return this.origin.distanceToSquared( point );
  3265. }
  3266. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3267. return _vector$a.distanceToSquared( point );
  3268. }
  3269. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3270. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3271. // It returns the min distance between the ray and the segment
  3272. // defined by v0 and v1
  3273. // It can also set two optional targets :
  3274. // - The closest point on the ray
  3275. // - The closest point on the segment
  3276. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3277. _segDir.copy( v1 ).sub( v0 ).normalize();
  3278. _diff.copy( this.origin ).sub( _segCenter );
  3279. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3280. const a01 = - this.direction.dot( _segDir );
  3281. const b0 = _diff.dot( this.direction );
  3282. const b1 = - _diff.dot( _segDir );
  3283. const c = _diff.lengthSq();
  3284. const det = Math.abs( 1 - a01 * a01 );
  3285. let s0, s1, sqrDist, extDet;
  3286. if ( det > 0 ) {
  3287. // The ray and segment are not parallel.
  3288. s0 = a01 * b1 - b0;
  3289. s1 = a01 * b0 - b1;
  3290. extDet = segExtent * det;
  3291. if ( s0 >= 0 ) {
  3292. if ( s1 >= - extDet ) {
  3293. if ( s1 <= extDet ) {
  3294. // region 0
  3295. // Minimum at interior points of ray and segment.
  3296. const invDet = 1 / det;
  3297. s0 *= invDet;
  3298. s1 *= invDet;
  3299. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3300. } else {
  3301. // region 1
  3302. s1 = segExtent;
  3303. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3304. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3305. }
  3306. } else {
  3307. // region 5
  3308. s1 = - segExtent;
  3309. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3310. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3311. }
  3312. } else {
  3313. if ( s1 <= - extDet ) {
  3314. // region 4
  3315. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3316. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3317. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3318. } else if ( s1 <= extDet ) {
  3319. // region 3
  3320. s0 = 0;
  3321. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3322. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3323. } else {
  3324. // region 2
  3325. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3326. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3327. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3328. }
  3329. }
  3330. } else {
  3331. // Ray and segment are parallel.
  3332. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3333. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3334. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3335. }
  3336. if ( optionalPointOnRay ) {
  3337. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3338. }
  3339. if ( optionalPointOnSegment ) {
  3340. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3341. }
  3342. return sqrDist;
  3343. }
  3344. intersectSphere( sphere, target ) {
  3345. _vector$a.subVectors( sphere.center, this.origin );
  3346. const tca = _vector$a.dot( this.direction );
  3347. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3348. const radius2 = sphere.radius * sphere.radius;
  3349. if ( d2 > radius2 ) return null;
  3350. const thc = Math.sqrt( radius2 - d2 );
  3351. // t0 = first intersect point - entrance on front of sphere
  3352. const t0 = tca - thc;
  3353. // t1 = second intersect point - exit point on back of sphere
  3354. const t1 = tca + thc;
  3355. // test to see if t1 is behind the ray - if so, return null
  3356. if ( t1 < 0 ) return null;
  3357. // test to see if t0 is behind the ray:
  3358. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3359. // in order to always return an intersect point that is in front of the ray.
  3360. if ( t0 < 0 ) return this.at( t1, target );
  3361. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3362. return this.at( t0, target );
  3363. }
  3364. intersectsSphere( sphere ) {
  3365. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3366. }
  3367. distanceToPlane( plane ) {
  3368. const denominator = plane.normal.dot( this.direction );
  3369. if ( denominator === 0 ) {
  3370. // line is coplanar, return origin
  3371. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3372. return 0;
  3373. }
  3374. // Null is preferable to undefined since undefined means.... it is undefined
  3375. return null;
  3376. }
  3377. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3378. // Return if the ray never intersects the plane
  3379. return t >= 0 ? t : null;
  3380. }
  3381. intersectPlane( plane, target ) {
  3382. const t = this.distanceToPlane( plane );
  3383. if ( t === null ) {
  3384. return null;
  3385. }
  3386. return this.at( t, target );
  3387. }
  3388. intersectsPlane( plane ) {
  3389. // check if the ray lies on the plane first
  3390. const distToPoint = plane.distanceToPoint( this.origin );
  3391. if ( distToPoint === 0 ) {
  3392. return true;
  3393. }
  3394. const denominator = plane.normal.dot( this.direction );
  3395. if ( denominator * distToPoint < 0 ) {
  3396. return true;
  3397. }
  3398. // ray origin is behind the plane (and is pointing behind it)
  3399. return false;
  3400. }
  3401. intersectBox( box, target ) {
  3402. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3403. const invdirx = 1 / this.direction.x,
  3404. invdiry = 1 / this.direction.y,
  3405. invdirz = 1 / this.direction.z;
  3406. const origin = this.origin;
  3407. if ( invdirx >= 0 ) {
  3408. tmin = ( box.min.x - origin.x ) * invdirx;
  3409. tmax = ( box.max.x - origin.x ) * invdirx;
  3410. } else {
  3411. tmin = ( box.max.x - origin.x ) * invdirx;
  3412. tmax = ( box.min.x - origin.x ) * invdirx;
  3413. }
  3414. if ( invdiry >= 0 ) {
  3415. tymin = ( box.min.y - origin.y ) * invdiry;
  3416. tymax = ( box.max.y - origin.y ) * invdiry;
  3417. } else {
  3418. tymin = ( box.max.y - origin.y ) * invdiry;
  3419. tymax = ( box.min.y - origin.y ) * invdiry;
  3420. }
  3421. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3422. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3423. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3424. if ( invdirz >= 0 ) {
  3425. tzmin = ( box.min.z - origin.z ) * invdirz;
  3426. tzmax = ( box.max.z - origin.z ) * invdirz;
  3427. } else {
  3428. tzmin = ( box.max.z - origin.z ) * invdirz;
  3429. tzmax = ( box.min.z - origin.z ) * invdirz;
  3430. }
  3431. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3432. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3433. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3434. //return point closest to the ray (positive side)
  3435. if ( tmax < 0 ) return null;
  3436. return this.at( tmin >= 0 ? tmin : tmax, target );
  3437. }
  3438. intersectsBox( box ) {
  3439. return this.intersectBox( box, _vector$a ) !== null;
  3440. }
  3441. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3442. // Compute the offset origin, edges, and normal.
  3443. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3444. _edge1.subVectors( b, a );
  3445. _edge2.subVectors( c, a );
  3446. _normal$2.crossVectors( _edge1, _edge2 );
  3447. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3448. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3449. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3450. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3451. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3452. let DdN = this.direction.dot( _normal$2 );
  3453. let sign;
  3454. if ( DdN > 0 ) {
  3455. if ( backfaceCulling ) return null;
  3456. sign = 1;
  3457. } else if ( DdN < 0 ) {
  3458. sign = - 1;
  3459. DdN = - DdN;
  3460. } else {
  3461. return null;
  3462. }
  3463. _diff.subVectors( this.origin, a );
  3464. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3465. // b1 < 0, no intersection
  3466. if ( DdQxE2 < 0 ) {
  3467. return null;
  3468. }
  3469. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3470. // b2 < 0, no intersection
  3471. if ( DdE1xQ < 0 ) {
  3472. return null;
  3473. }
  3474. // b1+b2 > 1, no intersection
  3475. if ( DdQxE2 + DdE1xQ > DdN ) {
  3476. return null;
  3477. }
  3478. // Line intersects triangle, check if ray does.
  3479. const QdN = - sign * _diff.dot( _normal$2 );
  3480. // t < 0, no intersection
  3481. if ( QdN < 0 ) {
  3482. return null;
  3483. }
  3484. // Ray intersects triangle.
  3485. return this.at( QdN / DdN, target );
  3486. }
  3487. applyMatrix4( matrix4 ) {
  3488. this.origin.applyMatrix4( matrix4 );
  3489. this.direction.transformDirection( matrix4 );
  3490. return this;
  3491. }
  3492. equals( ray ) {
  3493. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3494. }
  3495. clone() {
  3496. return new this.constructor().copy( this );
  3497. }
  3498. }
  3499. class Matrix4 {
  3500. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3501. Matrix4.prototype.isMatrix4 = true;
  3502. this.elements = [
  3503. 1, 0, 0, 0,
  3504. 0, 1, 0, 0,
  3505. 0, 0, 1, 0,
  3506. 0, 0, 0, 1
  3507. ];
  3508. if ( n11 !== undefined ) {
  3509. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3510. }
  3511. }
  3512. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3513. const te = this.elements;
  3514. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3515. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3516. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3517. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3518. return this;
  3519. }
  3520. identity() {
  3521. this.set(
  3522. 1, 0, 0, 0,
  3523. 0, 1, 0, 0,
  3524. 0, 0, 1, 0,
  3525. 0, 0, 0, 1
  3526. );
  3527. return this;
  3528. }
  3529. clone() {
  3530. return new Matrix4().fromArray( this.elements );
  3531. }
  3532. copy( m ) {
  3533. const te = this.elements;
  3534. const me = m.elements;
  3535. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3536. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3537. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3538. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3539. return this;
  3540. }
  3541. copyPosition( m ) {
  3542. const te = this.elements, me = m.elements;
  3543. te[ 12 ] = me[ 12 ];
  3544. te[ 13 ] = me[ 13 ];
  3545. te[ 14 ] = me[ 14 ];
  3546. return this;
  3547. }
  3548. setFromMatrix3( m ) {
  3549. const me = m.elements;
  3550. this.set(
  3551. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3552. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3553. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3554. 0, 0, 0, 1
  3555. );
  3556. return this;
  3557. }
  3558. extractBasis( xAxis, yAxis, zAxis ) {
  3559. xAxis.setFromMatrixColumn( this, 0 );
  3560. yAxis.setFromMatrixColumn( this, 1 );
  3561. zAxis.setFromMatrixColumn( this, 2 );
  3562. return this;
  3563. }
  3564. makeBasis( xAxis, yAxis, zAxis ) {
  3565. this.set(
  3566. xAxis.x, yAxis.x, zAxis.x, 0,
  3567. xAxis.y, yAxis.y, zAxis.y, 0,
  3568. xAxis.z, yAxis.z, zAxis.z, 0,
  3569. 0, 0, 0, 1
  3570. );
  3571. return this;
  3572. }
  3573. extractRotation( m ) {
  3574. // this method does not support reflection matrices
  3575. const te = this.elements;
  3576. const me = m.elements;
  3577. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3578. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3579. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3580. te[ 0 ] = me[ 0 ] * scaleX;
  3581. te[ 1 ] = me[ 1 ] * scaleX;
  3582. te[ 2 ] = me[ 2 ] * scaleX;
  3583. te[ 3 ] = 0;
  3584. te[ 4 ] = me[ 4 ] * scaleY;
  3585. te[ 5 ] = me[ 5 ] * scaleY;
  3586. te[ 6 ] = me[ 6 ] * scaleY;
  3587. te[ 7 ] = 0;
  3588. te[ 8 ] = me[ 8 ] * scaleZ;
  3589. te[ 9 ] = me[ 9 ] * scaleZ;
  3590. te[ 10 ] = me[ 10 ] * scaleZ;
  3591. te[ 11 ] = 0;
  3592. te[ 12 ] = 0;
  3593. te[ 13 ] = 0;
  3594. te[ 14 ] = 0;
  3595. te[ 15 ] = 1;
  3596. return this;
  3597. }
  3598. makeRotationFromEuler( euler ) {
  3599. const te = this.elements;
  3600. const x = euler.x, y = euler.y, z = euler.z;
  3601. const a = Math.cos( x ), b = Math.sin( x );
  3602. const c = Math.cos( y ), d = Math.sin( y );
  3603. const e = Math.cos( z ), f = Math.sin( z );
  3604. if ( euler.order === 'XYZ' ) {
  3605. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3606. te[ 0 ] = c * e;
  3607. te[ 4 ] = - c * f;
  3608. te[ 8 ] = d;
  3609. te[ 1 ] = af + be * d;
  3610. te[ 5 ] = ae - bf * d;
  3611. te[ 9 ] = - b * c;
  3612. te[ 2 ] = bf - ae * d;
  3613. te[ 6 ] = be + af * d;
  3614. te[ 10 ] = a * c;
  3615. } else if ( euler.order === 'YXZ' ) {
  3616. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3617. te[ 0 ] = ce + df * b;
  3618. te[ 4 ] = de * b - cf;
  3619. te[ 8 ] = a * d;
  3620. te[ 1 ] = a * f;
  3621. te[ 5 ] = a * e;
  3622. te[ 9 ] = - b;
  3623. te[ 2 ] = cf * b - de;
  3624. te[ 6 ] = df + ce * b;
  3625. te[ 10 ] = a * c;
  3626. } else if ( euler.order === 'ZXY' ) {
  3627. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3628. te[ 0 ] = ce - df * b;
  3629. te[ 4 ] = - a * f;
  3630. te[ 8 ] = de + cf * b;
  3631. te[ 1 ] = cf + de * b;
  3632. te[ 5 ] = a * e;
  3633. te[ 9 ] = df - ce * b;
  3634. te[ 2 ] = - a * d;
  3635. te[ 6 ] = b;
  3636. te[ 10 ] = a * c;
  3637. } else if ( euler.order === 'ZYX' ) {
  3638. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3639. te[ 0 ] = c * e;
  3640. te[ 4 ] = be * d - af;
  3641. te[ 8 ] = ae * d + bf;
  3642. te[ 1 ] = c * f;
  3643. te[ 5 ] = bf * d + ae;
  3644. te[ 9 ] = af * d - be;
  3645. te[ 2 ] = - d;
  3646. te[ 6 ] = b * c;
  3647. te[ 10 ] = a * c;
  3648. } else if ( euler.order === 'YZX' ) {
  3649. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3650. te[ 0 ] = c * e;
  3651. te[ 4 ] = bd - ac * f;
  3652. te[ 8 ] = bc * f + ad;
  3653. te[ 1 ] = f;
  3654. te[ 5 ] = a * e;
  3655. te[ 9 ] = - b * e;
  3656. te[ 2 ] = - d * e;
  3657. te[ 6 ] = ad * f + bc;
  3658. te[ 10 ] = ac - bd * f;
  3659. } else if ( euler.order === 'XZY' ) {
  3660. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3661. te[ 0 ] = c * e;
  3662. te[ 4 ] = - f;
  3663. te[ 8 ] = d * e;
  3664. te[ 1 ] = ac * f + bd;
  3665. te[ 5 ] = a * e;
  3666. te[ 9 ] = ad * f - bc;
  3667. te[ 2 ] = bc * f - ad;
  3668. te[ 6 ] = b * e;
  3669. te[ 10 ] = bd * f + ac;
  3670. }
  3671. // bottom row
  3672. te[ 3 ] = 0;
  3673. te[ 7 ] = 0;
  3674. te[ 11 ] = 0;
  3675. // last column
  3676. te[ 12 ] = 0;
  3677. te[ 13 ] = 0;
  3678. te[ 14 ] = 0;
  3679. te[ 15 ] = 1;
  3680. return this;
  3681. }
  3682. makeRotationFromQuaternion( q ) {
  3683. return this.compose( _zero, q, _one );
  3684. }
  3685. lookAt( eye, target, up ) {
  3686. const te = this.elements;
  3687. _z.subVectors( eye, target );
  3688. if ( _z.lengthSq() === 0 ) {
  3689. // eye and target are in the same position
  3690. _z.z = 1;
  3691. }
  3692. _z.normalize();
  3693. _x.crossVectors( up, _z );
  3694. if ( _x.lengthSq() === 0 ) {
  3695. // up and z are parallel
  3696. if ( Math.abs( up.z ) === 1 ) {
  3697. _z.x += 0.0001;
  3698. } else {
  3699. _z.z += 0.0001;
  3700. }
  3701. _z.normalize();
  3702. _x.crossVectors( up, _z );
  3703. }
  3704. _x.normalize();
  3705. _y.crossVectors( _z, _x );
  3706. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3707. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3708. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3709. return this;
  3710. }
  3711. multiply( m ) {
  3712. return this.multiplyMatrices( this, m );
  3713. }
  3714. premultiply( m ) {
  3715. return this.multiplyMatrices( m, this );
  3716. }
  3717. multiplyMatrices( a, b ) {
  3718. const ae = a.elements;
  3719. const be = b.elements;
  3720. const te = this.elements;
  3721. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3722. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3723. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3724. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3725. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3726. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3727. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3728. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3729. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3730. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3731. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3732. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3733. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3734. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3735. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3736. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3737. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3738. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3739. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3740. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3741. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3742. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3743. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3744. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3745. return this;
  3746. }
  3747. multiplyScalar( s ) {
  3748. const te = this.elements;
  3749. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3750. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3751. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3752. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3753. return this;
  3754. }
  3755. determinant() {
  3756. const te = this.elements;
  3757. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3758. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3759. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3760. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3761. //TODO: make this more efficient
  3762. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3763. return (
  3764. n41 * (
  3765. + n14 * n23 * n32
  3766. - n13 * n24 * n32
  3767. - n14 * n22 * n33
  3768. + n12 * n24 * n33
  3769. + n13 * n22 * n34
  3770. - n12 * n23 * n34
  3771. ) +
  3772. n42 * (
  3773. + n11 * n23 * n34
  3774. - n11 * n24 * n33
  3775. + n14 * n21 * n33
  3776. - n13 * n21 * n34
  3777. + n13 * n24 * n31
  3778. - n14 * n23 * n31
  3779. ) +
  3780. n43 * (
  3781. + n11 * n24 * n32
  3782. - n11 * n22 * n34
  3783. - n14 * n21 * n32
  3784. + n12 * n21 * n34
  3785. + n14 * n22 * n31
  3786. - n12 * n24 * n31
  3787. ) +
  3788. n44 * (
  3789. - n13 * n22 * n31
  3790. - n11 * n23 * n32
  3791. + n11 * n22 * n33
  3792. + n13 * n21 * n32
  3793. - n12 * n21 * n33
  3794. + n12 * n23 * n31
  3795. )
  3796. );
  3797. }
  3798. transpose() {
  3799. const te = this.elements;
  3800. let tmp;
  3801. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3802. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3803. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3804. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3805. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3806. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3807. return this;
  3808. }
  3809. setPosition( x, y, z ) {
  3810. const te = this.elements;
  3811. if ( x.isVector3 ) {
  3812. te[ 12 ] = x.x;
  3813. te[ 13 ] = x.y;
  3814. te[ 14 ] = x.z;
  3815. } else {
  3816. te[ 12 ] = x;
  3817. te[ 13 ] = y;
  3818. te[ 14 ] = z;
  3819. }
  3820. return this;
  3821. }
  3822. invert() {
  3823. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3824. const te = this.elements,
  3825. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3826. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3827. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3828. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3829. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3830. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3831. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3832. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3833. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3834. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3835. const detInv = 1 / det;
  3836. te[ 0 ] = t11 * detInv;
  3837. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3838. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3839. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3840. te[ 4 ] = t12 * detInv;
  3841. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3842. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3843. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3844. te[ 8 ] = t13 * detInv;
  3845. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3846. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3847. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3848. te[ 12 ] = t14 * detInv;
  3849. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3850. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3851. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3852. return this;
  3853. }
  3854. scale( v ) {
  3855. const te = this.elements;
  3856. const x = v.x, y = v.y, z = v.z;
  3857. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3858. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3859. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3860. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3861. return this;
  3862. }
  3863. getMaxScaleOnAxis() {
  3864. const te = this.elements;
  3865. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3866. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3867. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3868. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3869. }
  3870. makeTranslation( x, y, z ) {
  3871. if ( x.isVector3 ) {
  3872. this.set(
  3873. 1, 0, 0, x.x,
  3874. 0, 1, 0, x.y,
  3875. 0, 0, 1, x.z,
  3876. 0, 0, 0, 1
  3877. );
  3878. } else {
  3879. this.set(
  3880. 1, 0, 0, x,
  3881. 0, 1, 0, y,
  3882. 0, 0, 1, z,
  3883. 0, 0, 0, 1
  3884. );
  3885. }
  3886. return this;
  3887. }
  3888. makeRotationX( theta ) {
  3889. const c = Math.cos( theta ), s = Math.sin( theta );
  3890. this.set(
  3891. 1, 0, 0, 0,
  3892. 0, c, - s, 0,
  3893. 0, s, c, 0,
  3894. 0, 0, 0, 1
  3895. );
  3896. return this;
  3897. }
  3898. makeRotationY( theta ) {
  3899. const c = Math.cos( theta ), s = Math.sin( theta );
  3900. this.set(
  3901. c, 0, s, 0,
  3902. 0, 1, 0, 0,
  3903. - s, 0, c, 0,
  3904. 0, 0, 0, 1
  3905. );
  3906. return this;
  3907. }
  3908. makeRotationZ( theta ) {
  3909. const c = Math.cos( theta ), s = Math.sin( theta );
  3910. this.set(
  3911. c, - s, 0, 0,
  3912. s, c, 0, 0,
  3913. 0, 0, 1, 0,
  3914. 0, 0, 0, 1
  3915. );
  3916. return this;
  3917. }
  3918. makeRotationAxis( axis, angle ) {
  3919. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3920. const c = Math.cos( angle );
  3921. const s = Math.sin( angle );
  3922. const t = 1 - c;
  3923. const x = axis.x, y = axis.y, z = axis.z;
  3924. const tx = t * x, ty = t * y;
  3925. this.set(
  3926. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3927. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3928. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3929. 0, 0, 0, 1
  3930. );
  3931. return this;
  3932. }
  3933. makeScale( x, y, z ) {
  3934. this.set(
  3935. x, 0, 0, 0,
  3936. 0, y, 0, 0,
  3937. 0, 0, z, 0,
  3938. 0, 0, 0, 1
  3939. );
  3940. return this;
  3941. }
  3942. makeShear( xy, xz, yx, yz, zx, zy ) {
  3943. this.set(
  3944. 1, yx, zx, 0,
  3945. xy, 1, zy, 0,
  3946. xz, yz, 1, 0,
  3947. 0, 0, 0, 1
  3948. );
  3949. return this;
  3950. }
  3951. compose( position, quaternion, scale ) {
  3952. const te = this.elements;
  3953. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3954. const x2 = x + x, y2 = y + y, z2 = z + z;
  3955. const xx = x * x2, xy = x * y2, xz = x * z2;
  3956. const yy = y * y2, yz = y * z2, zz = z * z2;
  3957. const wx = w * x2, wy = w * y2, wz = w * z2;
  3958. const sx = scale.x, sy = scale.y, sz = scale.z;
  3959. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3960. te[ 1 ] = ( xy + wz ) * sx;
  3961. te[ 2 ] = ( xz - wy ) * sx;
  3962. te[ 3 ] = 0;
  3963. te[ 4 ] = ( xy - wz ) * sy;
  3964. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3965. te[ 6 ] = ( yz + wx ) * sy;
  3966. te[ 7 ] = 0;
  3967. te[ 8 ] = ( xz + wy ) * sz;
  3968. te[ 9 ] = ( yz - wx ) * sz;
  3969. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3970. te[ 11 ] = 0;
  3971. te[ 12 ] = position.x;
  3972. te[ 13 ] = position.y;
  3973. te[ 14 ] = position.z;
  3974. te[ 15 ] = 1;
  3975. return this;
  3976. }
  3977. decompose( position, quaternion, scale ) {
  3978. const te = this.elements;
  3979. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3980. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3981. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3982. // if determine is negative, we need to invert one scale
  3983. const det = this.determinant();
  3984. if ( det < 0 ) sx = - sx;
  3985. position.x = te[ 12 ];
  3986. position.y = te[ 13 ];
  3987. position.z = te[ 14 ];
  3988. // scale the rotation part
  3989. _m1$2.copy( this );
  3990. const invSX = 1 / sx;
  3991. const invSY = 1 / sy;
  3992. const invSZ = 1 / sz;
  3993. _m1$2.elements[ 0 ] *= invSX;
  3994. _m1$2.elements[ 1 ] *= invSX;
  3995. _m1$2.elements[ 2 ] *= invSX;
  3996. _m1$2.elements[ 4 ] *= invSY;
  3997. _m1$2.elements[ 5 ] *= invSY;
  3998. _m1$2.elements[ 6 ] *= invSY;
  3999. _m1$2.elements[ 8 ] *= invSZ;
  4000. _m1$2.elements[ 9 ] *= invSZ;
  4001. _m1$2.elements[ 10 ] *= invSZ;
  4002. quaternion.setFromRotationMatrix( _m1$2 );
  4003. scale.x = sx;
  4004. scale.y = sy;
  4005. scale.z = sz;
  4006. return this;
  4007. }
  4008. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4009. const te = this.elements;
  4010. const x = 2 * near / ( right - left );
  4011. const y = 2 * near / ( top - bottom );
  4012. const a = ( right + left ) / ( right - left );
  4013. const b = ( top + bottom ) / ( top - bottom );
  4014. let c, d;
  4015. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4016. c = - ( far + near ) / ( far - near );
  4017. d = ( - 2 * far * near ) / ( far - near );
  4018. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4019. c = - far / ( far - near );
  4020. d = ( - far * near ) / ( far - near );
  4021. } else {
  4022. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4023. }
  4024. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4025. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4026. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4027. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4028. return this;
  4029. }
  4030. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4031. const te = this.elements;
  4032. const w = 1.0 / ( right - left );
  4033. const h = 1.0 / ( top - bottom );
  4034. const p = 1.0 / ( far - near );
  4035. const x = ( right + left ) * w;
  4036. const y = ( top + bottom ) * h;
  4037. let z, zInv;
  4038. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4039. z = ( far + near ) * p;
  4040. zInv = - 2 * p;
  4041. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4042. z = near * p;
  4043. zInv = - 1 * p;
  4044. } else {
  4045. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4046. }
  4047. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4048. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4049. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4050. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4051. return this;
  4052. }
  4053. equals( matrix ) {
  4054. const te = this.elements;
  4055. const me = matrix.elements;
  4056. for ( let i = 0; i < 16; i ++ ) {
  4057. if ( te[ i ] !== me[ i ] ) return false;
  4058. }
  4059. return true;
  4060. }
  4061. fromArray( array, offset = 0 ) {
  4062. for ( let i = 0; i < 16; i ++ ) {
  4063. this.elements[ i ] = array[ i + offset ];
  4064. }
  4065. return this;
  4066. }
  4067. toArray( array = [], offset = 0 ) {
  4068. const te = this.elements;
  4069. array[ offset ] = te[ 0 ];
  4070. array[ offset + 1 ] = te[ 1 ];
  4071. array[ offset + 2 ] = te[ 2 ];
  4072. array[ offset + 3 ] = te[ 3 ];
  4073. array[ offset + 4 ] = te[ 4 ];
  4074. array[ offset + 5 ] = te[ 5 ];
  4075. array[ offset + 6 ] = te[ 6 ];
  4076. array[ offset + 7 ] = te[ 7 ];
  4077. array[ offset + 8 ] = te[ 8 ];
  4078. array[ offset + 9 ] = te[ 9 ];
  4079. array[ offset + 10 ] = te[ 10 ];
  4080. array[ offset + 11 ] = te[ 11 ];
  4081. array[ offset + 12 ] = te[ 12 ];
  4082. array[ offset + 13 ] = te[ 13 ];
  4083. array[ offset + 14 ] = te[ 14 ];
  4084. array[ offset + 15 ] = te[ 15 ];
  4085. return array;
  4086. }
  4087. }
  4088. const _v1$5 = /*@__PURE__*/ new Vector3();
  4089. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4090. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4091. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4092. const _x = /*@__PURE__*/ new Vector3();
  4093. const _y = /*@__PURE__*/ new Vector3();
  4094. const _z = /*@__PURE__*/ new Vector3();
  4095. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4096. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4097. class Euler {
  4098. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4099. this.isEuler = true;
  4100. this._x = x;
  4101. this._y = y;
  4102. this._z = z;
  4103. this._order = order;
  4104. }
  4105. get x() {
  4106. return this._x;
  4107. }
  4108. set x( value ) {
  4109. this._x = value;
  4110. this._onChangeCallback();
  4111. }
  4112. get y() {
  4113. return this._y;
  4114. }
  4115. set y( value ) {
  4116. this._y = value;
  4117. this._onChangeCallback();
  4118. }
  4119. get z() {
  4120. return this._z;
  4121. }
  4122. set z( value ) {
  4123. this._z = value;
  4124. this._onChangeCallback();
  4125. }
  4126. get order() {
  4127. return this._order;
  4128. }
  4129. set order( value ) {
  4130. this._order = value;
  4131. this._onChangeCallback();
  4132. }
  4133. set( x, y, z, order = this._order ) {
  4134. this._x = x;
  4135. this._y = y;
  4136. this._z = z;
  4137. this._order = order;
  4138. this._onChangeCallback();
  4139. return this;
  4140. }
  4141. clone() {
  4142. return new this.constructor( this._x, this._y, this._z, this._order );
  4143. }
  4144. copy( euler ) {
  4145. this._x = euler._x;
  4146. this._y = euler._y;
  4147. this._z = euler._z;
  4148. this._order = euler._order;
  4149. this._onChangeCallback();
  4150. return this;
  4151. }
  4152. setFromRotationMatrix( m, order = this._order, update = true ) {
  4153. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4154. const te = m.elements;
  4155. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4156. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4157. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4158. switch ( order ) {
  4159. case 'XYZ':
  4160. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4161. if ( Math.abs( m13 ) < 0.9999999 ) {
  4162. this._x = Math.atan2( - m23, m33 );
  4163. this._z = Math.atan2( - m12, m11 );
  4164. } else {
  4165. this._x = Math.atan2( m32, m22 );
  4166. this._z = 0;
  4167. }
  4168. break;
  4169. case 'YXZ':
  4170. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4171. if ( Math.abs( m23 ) < 0.9999999 ) {
  4172. this._y = Math.atan2( m13, m33 );
  4173. this._z = Math.atan2( m21, m22 );
  4174. } else {
  4175. this._y = Math.atan2( - m31, m11 );
  4176. this._z = 0;
  4177. }
  4178. break;
  4179. case 'ZXY':
  4180. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4181. if ( Math.abs( m32 ) < 0.9999999 ) {
  4182. this._y = Math.atan2( - m31, m33 );
  4183. this._z = Math.atan2( - m12, m22 );
  4184. } else {
  4185. this._y = 0;
  4186. this._z = Math.atan2( m21, m11 );
  4187. }
  4188. break;
  4189. case 'ZYX':
  4190. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4191. if ( Math.abs( m31 ) < 0.9999999 ) {
  4192. this._x = Math.atan2( m32, m33 );
  4193. this._z = Math.atan2( m21, m11 );
  4194. } else {
  4195. this._x = 0;
  4196. this._z = Math.atan2( - m12, m22 );
  4197. }
  4198. break;
  4199. case 'YZX':
  4200. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4201. if ( Math.abs( m21 ) < 0.9999999 ) {
  4202. this._x = Math.atan2( - m23, m22 );
  4203. this._y = Math.atan2( - m31, m11 );
  4204. } else {
  4205. this._x = 0;
  4206. this._y = Math.atan2( m13, m33 );
  4207. }
  4208. break;
  4209. case 'XZY':
  4210. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4211. if ( Math.abs( m12 ) < 0.9999999 ) {
  4212. this._x = Math.atan2( m32, m22 );
  4213. this._y = Math.atan2( m13, m11 );
  4214. } else {
  4215. this._x = Math.atan2( - m23, m33 );
  4216. this._y = 0;
  4217. }
  4218. break;
  4219. default:
  4220. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4221. }
  4222. this._order = order;
  4223. if ( update === true ) this._onChangeCallback();
  4224. return this;
  4225. }
  4226. setFromQuaternion( q, order, update ) {
  4227. _matrix$2.makeRotationFromQuaternion( q );
  4228. return this.setFromRotationMatrix( _matrix$2, order, update );
  4229. }
  4230. setFromVector3( v, order = this._order ) {
  4231. return this.set( v.x, v.y, v.z, order );
  4232. }
  4233. reorder( newOrder ) {
  4234. // WARNING: this discards revolution information -bhouston
  4235. _quaternion$3.setFromEuler( this );
  4236. return this.setFromQuaternion( _quaternion$3, newOrder );
  4237. }
  4238. equals( euler ) {
  4239. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4240. }
  4241. fromArray( array ) {
  4242. this._x = array[ 0 ];
  4243. this._y = array[ 1 ];
  4244. this._z = array[ 2 ];
  4245. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4246. this._onChangeCallback();
  4247. return this;
  4248. }
  4249. toArray( array = [], offset = 0 ) {
  4250. array[ offset ] = this._x;
  4251. array[ offset + 1 ] = this._y;
  4252. array[ offset + 2 ] = this._z;
  4253. array[ offset + 3 ] = this._order;
  4254. return array;
  4255. }
  4256. _onChange( callback ) {
  4257. this._onChangeCallback = callback;
  4258. return this;
  4259. }
  4260. _onChangeCallback() {}
  4261. *[ Symbol.iterator ]() {
  4262. yield this._x;
  4263. yield this._y;
  4264. yield this._z;
  4265. yield this._order;
  4266. }
  4267. }
  4268. Euler.DEFAULT_ORDER = 'XYZ';
  4269. class Layers {
  4270. constructor() {
  4271. this.mask = 1 | 0;
  4272. }
  4273. set( channel ) {
  4274. this.mask = ( 1 << channel | 0 ) >>> 0;
  4275. }
  4276. enable( channel ) {
  4277. this.mask |= 1 << channel | 0;
  4278. }
  4279. enableAll() {
  4280. this.mask = 0xffffffff | 0;
  4281. }
  4282. toggle( channel ) {
  4283. this.mask ^= 1 << channel | 0;
  4284. }
  4285. disable( channel ) {
  4286. this.mask &= ~ ( 1 << channel | 0 );
  4287. }
  4288. disableAll() {
  4289. this.mask = 0;
  4290. }
  4291. test( layers ) {
  4292. return ( this.mask & layers.mask ) !== 0;
  4293. }
  4294. isEnabled( channel ) {
  4295. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4296. }
  4297. }
  4298. let _object3DId = 0;
  4299. const _v1$4 = /*@__PURE__*/ new Vector3();
  4300. const _q1 = /*@__PURE__*/ new Quaternion();
  4301. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4302. const _target$1 = /*@__PURE__*/ new Vector3();
  4303. const _position$3 = /*@__PURE__*/ new Vector3();
  4304. const _scale$2 = /*@__PURE__*/ new Vector3();
  4305. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4306. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4307. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4308. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4309. const _addedEvent = { type: 'added' };
  4310. const _removedEvent = { type: 'removed' };
  4311. const _childaddedEvent = { type: 'childadded', child: null };
  4312. const _childremovedEvent = { type: 'childremoved', child: null };
  4313. class Object3D extends EventDispatcher {
  4314. constructor() {
  4315. super();
  4316. this.isObject3D = true;
  4317. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4318. this.uuid = generateUUID();
  4319. this.name = '';
  4320. this.type = 'Object3D';
  4321. this.parent = null;
  4322. this.children = [];
  4323. this.up = Object3D.DEFAULT_UP.clone();
  4324. const position = new Vector3();
  4325. const rotation = new Euler();
  4326. const quaternion = new Quaternion();
  4327. const scale = new Vector3( 1, 1, 1 );
  4328. function onRotationChange() {
  4329. quaternion.setFromEuler( rotation, false );
  4330. }
  4331. function onQuaternionChange() {
  4332. rotation.setFromQuaternion( quaternion, undefined, false );
  4333. }
  4334. rotation._onChange( onRotationChange );
  4335. quaternion._onChange( onQuaternionChange );
  4336. Object.defineProperties( this, {
  4337. position: {
  4338. configurable: true,
  4339. enumerable: true,
  4340. value: position
  4341. },
  4342. rotation: {
  4343. configurable: true,
  4344. enumerable: true,
  4345. value: rotation
  4346. },
  4347. quaternion: {
  4348. configurable: true,
  4349. enumerable: true,
  4350. value: quaternion
  4351. },
  4352. scale: {
  4353. configurable: true,
  4354. enumerable: true,
  4355. value: scale
  4356. },
  4357. modelViewMatrix: {
  4358. value: new Matrix4()
  4359. },
  4360. normalMatrix: {
  4361. value: new Matrix3()
  4362. }
  4363. } );
  4364. this.matrix = new Matrix4();
  4365. this.matrixWorld = new Matrix4();
  4366. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4367. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4368. this.matrixWorldNeedsUpdate = false;
  4369. this.layers = new Layers();
  4370. this.visible = true;
  4371. this.castShadow = false;
  4372. this.receiveShadow = false;
  4373. this.frustumCulled = true;
  4374. this.renderOrder = 0;
  4375. this.animations = [];
  4376. this.userData = {};
  4377. }
  4378. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4379. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4380. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4381. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4382. applyMatrix4( matrix ) {
  4383. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4384. this.matrix.premultiply( matrix );
  4385. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4386. }
  4387. applyQuaternion( q ) {
  4388. this.quaternion.premultiply( q );
  4389. return this;
  4390. }
  4391. setRotationFromAxisAngle( axis, angle ) {
  4392. // assumes axis is normalized
  4393. this.quaternion.setFromAxisAngle( axis, angle );
  4394. }
  4395. setRotationFromEuler( euler ) {
  4396. this.quaternion.setFromEuler( euler, true );
  4397. }
  4398. setRotationFromMatrix( m ) {
  4399. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4400. this.quaternion.setFromRotationMatrix( m );
  4401. }
  4402. setRotationFromQuaternion( q ) {
  4403. // assumes q is normalized
  4404. this.quaternion.copy( q );
  4405. }
  4406. rotateOnAxis( axis, angle ) {
  4407. // rotate object on axis in object space
  4408. // axis is assumed to be normalized
  4409. _q1.setFromAxisAngle( axis, angle );
  4410. this.quaternion.multiply( _q1 );
  4411. return this;
  4412. }
  4413. rotateOnWorldAxis( axis, angle ) {
  4414. // rotate object on axis in world space
  4415. // axis is assumed to be normalized
  4416. // method assumes no rotated parent
  4417. _q1.setFromAxisAngle( axis, angle );
  4418. this.quaternion.premultiply( _q1 );
  4419. return this;
  4420. }
  4421. rotateX( angle ) {
  4422. return this.rotateOnAxis( _xAxis, angle );
  4423. }
  4424. rotateY( angle ) {
  4425. return this.rotateOnAxis( _yAxis, angle );
  4426. }
  4427. rotateZ( angle ) {
  4428. return this.rotateOnAxis( _zAxis, angle );
  4429. }
  4430. translateOnAxis( axis, distance ) {
  4431. // translate object by distance along axis in object space
  4432. // axis is assumed to be normalized
  4433. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4434. this.position.add( _v1$4.multiplyScalar( distance ) );
  4435. return this;
  4436. }
  4437. translateX( distance ) {
  4438. return this.translateOnAxis( _xAxis, distance );
  4439. }
  4440. translateY( distance ) {
  4441. return this.translateOnAxis( _yAxis, distance );
  4442. }
  4443. translateZ( distance ) {
  4444. return this.translateOnAxis( _zAxis, distance );
  4445. }
  4446. localToWorld( vector ) {
  4447. this.updateWorldMatrix( true, false );
  4448. return vector.applyMatrix4( this.matrixWorld );
  4449. }
  4450. worldToLocal( vector ) {
  4451. this.updateWorldMatrix( true, false );
  4452. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4453. }
  4454. lookAt( x, y, z ) {
  4455. // This method does not support objects having non-uniformly-scaled parent(s)
  4456. if ( x.isVector3 ) {
  4457. _target$1.copy( x );
  4458. } else {
  4459. _target$1.set( x, y, z );
  4460. }
  4461. const parent = this.parent;
  4462. this.updateWorldMatrix( true, false );
  4463. _position$3.setFromMatrixPosition( this.matrixWorld );
  4464. if ( this.isCamera || this.isLight ) {
  4465. _m1$1.lookAt( _position$3, _target$1, this.up );
  4466. } else {
  4467. _m1$1.lookAt( _target$1, _position$3, this.up );
  4468. }
  4469. this.quaternion.setFromRotationMatrix( _m1$1 );
  4470. if ( parent ) {
  4471. _m1$1.extractRotation( parent.matrixWorld );
  4472. _q1.setFromRotationMatrix( _m1$1 );
  4473. this.quaternion.premultiply( _q1.invert() );
  4474. }
  4475. }
  4476. add( object ) {
  4477. if ( arguments.length > 1 ) {
  4478. for ( let i = 0; i < arguments.length; i ++ ) {
  4479. this.add( arguments[ i ] );
  4480. }
  4481. return this;
  4482. }
  4483. if ( object === this ) {
  4484. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4485. return this;
  4486. }
  4487. if ( object && object.isObject3D ) {
  4488. object.removeFromParent();
  4489. object.parent = this;
  4490. this.children.push( object );
  4491. object.dispatchEvent( _addedEvent );
  4492. _childaddedEvent.child = object;
  4493. this.dispatchEvent( _childaddedEvent );
  4494. _childaddedEvent.child = null;
  4495. } else {
  4496. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4497. }
  4498. return this;
  4499. }
  4500. remove( object ) {
  4501. if ( arguments.length > 1 ) {
  4502. for ( let i = 0; i < arguments.length; i ++ ) {
  4503. this.remove( arguments[ i ] );
  4504. }
  4505. return this;
  4506. }
  4507. const index = this.children.indexOf( object );
  4508. if ( index !== - 1 ) {
  4509. object.parent = null;
  4510. this.children.splice( index, 1 );
  4511. object.dispatchEvent( _removedEvent );
  4512. _childremovedEvent.child = object;
  4513. this.dispatchEvent( _childremovedEvent );
  4514. _childremovedEvent.child = null;
  4515. }
  4516. return this;
  4517. }
  4518. removeFromParent() {
  4519. const parent = this.parent;
  4520. if ( parent !== null ) {
  4521. parent.remove( this );
  4522. }
  4523. return this;
  4524. }
  4525. clear() {
  4526. return this.remove( ... this.children );
  4527. }
  4528. attach( object ) {
  4529. // adds object as a child of this, while maintaining the object's world transform
  4530. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4531. this.updateWorldMatrix( true, false );
  4532. _m1$1.copy( this.matrixWorld ).invert();
  4533. if ( object.parent !== null ) {
  4534. object.parent.updateWorldMatrix( true, false );
  4535. _m1$1.multiply( object.parent.matrixWorld );
  4536. }
  4537. object.applyMatrix4( _m1$1 );
  4538. object.removeFromParent();
  4539. object.parent = this;
  4540. this.children.push( object );
  4541. object.updateWorldMatrix( false, true );
  4542. object.dispatchEvent( _addedEvent );
  4543. _childaddedEvent.child = object;
  4544. this.dispatchEvent( _childaddedEvent );
  4545. _childaddedEvent.child = null;
  4546. return this;
  4547. }
  4548. getObjectById( id ) {
  4549. return this.getObjectByProperty( 'id', id );
  4550. }
  4551. getObjectByName( name ) {
  4552. return this.getObjectByProperty( 'name', name );
  4553. }
  4554. getObjectByProperty( name, value ) {
  4555. if ( this[ name ] === value ) return this;
  4556. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4557. const child = this.children[ i ];
  4558. const object = child.getObjectByProperty( name, value );
  4559. if ( object !== undefined ) {
  4560. return object;
  4561. }
  4562. }
  4563. return undefined;
  4564. }
  4565. getObjectsByProperty( name, value, result = [] ) {
  4566. if ( this[ name ] === value ) result.push( this );
  4567. const children = this.children;
  4568. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4569. children[ i ].getObjectsByProperty( name, value, result );
  4570. }
  4571. return result;
  4572. }
  4573. getWorldPosition( target ) {
  4574. this.updateWorldMatrix( true, false );
  4575. return target.setFromMatrixPosition( this.matrixWorld );
  4576. }
  4577. getWorldQuaternion( target ) {
  4578. this.updateWorldMatrix( true, false );
  4579. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4580. return target;
  4581. }
  4582. getWorldScale( target ) {
  4583. this.updateWorldMatrix( true, false );
  4584. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4585. return target;
  4586. }
  4587. getWorldDirection( target ) {
  4588. this.updateWorldMatrix( true, false );
  4589. const e = this.matrixWorld.elements;
  4590. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4591. }
  4592. raycast( /* raycaster, intersects */ ) {}
  4593. traverse( callback ) {
  4594. callback( this );
  4595. const children = this.children;
  4596. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4597. children[ i ].traverse( callback );
  4598. }
  4599. }
  4600. traverseVisible( callback ) {
  4601. if ( this.visible === false ) return;
  4602. callback( this );
  4603. const children = this.children;
  4604. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4605. children[ i ].traverseVisible( callback );
  4606. }
  4607. }
  4608. traverseAncestors( callback ) {
  4609. const parent = this.parent;
  4610. if ( parent !== null ) {
  4611. callback( parent );
  4612. parent.traverseAncestors( callback );
  4613. }
  4614. }
  4615. updateMatrix() {
  4616. this.matrix.compose( this.position, this.quaternion, this.scale );
  4617. this.matrixWorldNeedsUpdate = true;
  4618. }
  4619. updateMatrixWorld( force ) {
  4620. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4621. if ( this.matrixWorldNeedsUpdate || force ) {
  4622. if ( this.matrixWorldAutoUpdate === true ) {
  4623. if ( this.parent === null ) {
  4624. this.matrixWorld.copy( this.matrix );
  4625. } else {
  4626. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4627. }
  4628. }
  4629. this.matrixWorldNeedsUpdate = false;
  4630. force = true;
  4631. }
  4632. // make sure descendants are updated if required
  4633. const children = this.children;
  4634. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4635. const child = children[ i ];
  4636. child.updateMatrixWorld( force );
  4637. }
  4638. }
  4639. updateWorldMatrix( updateParents, updateChildren ) {
  4640. const parent = this.parent;
  4641. if ( updateParents === true && parent !== null ) {
  4642. parent.updateWorldMatrix( true, false );
  4643. }
  4644. if ( this.matrixAutoUpdate ) this.updateMatrix();
  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. // make sure descendants are updated
  4653. if ( updateChildren === true ) {
  4654. const children = this.children;
  4655. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4656. const child = children[ i ];
  4657. child.updateWorldMatrix( false, true );
  4658. }
  4659. }
  4660. }
  4661. toJSON( meta ) {
  4662. // meta is a string when called from JSON.stringify
  4663. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4664. const output = {};
  4665. // meta is a hash used to collect geometries, materials.
  4666. // not providing it implies that this is the root object
  4667. // being serialized.
  4668. if ( isRootObject ) {
  4669. // initialize meta obj
  4670. meta = {
  4671. geometries: {},
  4672. materials: {},
  4673. textures: {},
  4674. images: {},
  4675. shapes: {},
  4676. skeletons: {},
  4677. animations: {},
  4678. nodes: {}
  4679. };
  4680. output.metadata = {
  4681. version: 4.6,
  4682. type: 'Object',
  4683. generator: 'Object3D.toJSON'
  4684. };
  4685. }
  4686. // standard Object3D serialization
  4687. const object = {};
  4688. object.uuid = this.uuid;
  4689. object.type = this.type;
  4690. if ( this.name !== '' ) object.name = this.name;
  4691. if ( this.castShadow === true ) object.castShadow = true;
  4692. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4693. if ( this.visible === false ) object.visible = false;
  4694. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4695. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4696. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4697. object.layers = this.layers.mask;
  4698. object.matrix = this.matrix.toArray();
  4699. object.up = this.up.toArray();
  4700. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4701. // object specific properties
  4702. if ( this.isInstancedMesh ) {
  4703. object.type = 'InstancedMesh';
  4704. object.count = this.count;
  4705. object.instanceMatrix = this.instanceMatrix.toJSON();
  4706. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4707. }
  4708. if ( this.isBatchedMesh ) {
  4709. object.type = 'BatchedMesh';
  4710. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4711. object.sortObjects = this.sortObjects;
  4712. object.drawRanges = this._drawRanges;
  4713. object.reservedRanges = this._reservedRanges;
  4714. object.visibility = this._visibility;
  4715. object.active = this._active;
  4716. object.bounds = this._bounds.map( bound => ( {
  4717. boxInitialized: bound.boxInitialized,
  4718. boxMin: bound.box.min.toArray(),
  4719. boxMax: bound.box.max.toArray(),
  4720. sphereInitialized: bound.sphereInitialized,
  4721. sphereRadius: bound.sphere.radius,
  4722. sphereCenter: bound.sphere.center.toArray()
  4723. } ) );
  4724. object.maxInstanceCount = this._maxInstanceCount;
  4725. object.maxVertexCount = this._maxVertexCount;
  4726. object.maxIndexCount = this._maxIndexCount;
  4727. object.geometryInitialized = this._geometryInitialized;
  4728. object.geometryCount = this._geometryCount;
  4729. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4730. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4731. if ( this.boundingSphere !== null ) {
  4732. object.boundingSphere = {
  4733. center: object.boundingSphere.center.toArray(),
  4734. radius: object.boundingSphere.radius
  4735. };
  4736. }
  4737. if ( this.boundingBox !== null ) {
  4738. object.boundingBox = {
  4739. min: object.boundingBox.min.toArray(),
  4740. max: object.boundingBox.max.toArray()
  4741. };
  4742. }
  4743. }
  4744. //
  4745. function serialize( library, element ) {
  4746. if ( library[ element.uuid ] === undefined ) {
  4747. library[ element.uuid ] = element.toJSON( meta );
  4748. }
  4749. return element.uuid;
  4750. }
  4751. if ( this.isScene ) {
  4752. if ( this.background ) {
  4753. if ( this.background.isColor ) {
  4754. object.background = this.background.toJSON();
  4755. } else if ( this.background.isTexture ) {
  4756. object.background = this.background.toJSON( meta ).uuid;
  4757. }
  4758. }
  4759. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4760. object.environment = this.environment.toJSON( meta ).uuid;
  4761. }
  4762. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4763. object.geometry = serialize( meta.geometries, this.geometry );
  4764. const parameters = this.geometry.parameters;
  4765. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4766. const shapes = parameters.shapes;
  4767. if ( Array.isArray( shapes ) ) {
  4768. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4769. const shape = shapes[ i ];
  4770. serialize( meta.shapes, shape );
  4771. }
  4772. } else {
  4773. serialize( meta.shapes, shapes );
  4774. }
  4775. }
  4776. }
  4777. if ( this.isSkinnedMesh ) {
  4778. object.bindMode = this.bindMode;
  4779. object.bindMatrix = this.bindMatrix.toArray();
  4780. if ( this.skeleton !== undefined ) {
  4781. serialize( meta.skeletons, this.skeleton );
  4782. object.skeleton = this.skeleton.uuid;
  4783. }
  4784. }
  4785. if ( this.material !== undefined ) {
  4786. if ( Array.isArray( this.material ) ) {
  4787. const uuids = [];
  4788. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4789. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4790. }
  4791. object.material = uuids;
  4792. } else {
  4793. object.material = serialize( meta.materials, this.material );
  4794. }
  4795. }
  4796. //
  4797. if ( this.children.length > 0 ) {
  4798. object.children = [];
  4799. for ( let i = 0; i < this.children.length; i ++ ) {
  4800. object.children.push( this.children[ i ].toJSON( meta ).object );
  4801. }
  4802. }
  4803. //
  4804. if ( this.animations.length > 0 ) {
  4805. object.animations = [];
  4806. for ( let i = 0; i < this.animations.length; i ++ ) {
  4807. const animation = this.animations[ i ];
  4808. object.animations.push( serialize( meta.animations, animation ) );
  4809. }
  4810. }
  4811. if ( isRootObject ) {
  4812. const geometries = extractFromCache( meta.geometries );
  4813. const materials = extractFromCache( meta.materials );
  4814. const textures = extractFromCache( meta.textures );
  4815. const images = extractFromCache( meta.images );
  4816. const shapes = extractFromCache( meta.shapes );
  4817. const skeletons = extractFromCache( meta.skeletons );
  4818. const animations = extractFromCache( meta.animations );
  4819. const nodes = extractFromCache( meta.nodes );
  4820. if ( geometries.length > 0 ) output.geometries = geometries;
  4821. if ( materials.length > 0 ) output.materials = materials;
  4822. if ( textures.length > 0 ) output.textures = textures;
  4823. if ( images.length > 0 ) output.images = images;
  4824. if ( shapes.length > 0 ) output.shapes = shapes;
  4825. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4826. if ( animations.length > 0 ) output.animations = animations;
  4827. if ( nodes.length > 0 ) output.nodes = nodes;
  4828. }
  4829. output.object = object;
  4830. return output;
  4831. // extract data from the cache hash
  4832. // remove metadata on each item
  4833. // and return as array
  4834. function extractFromCache( cache ) {
  4835. const values = [];
  4836. for ( const key in cache ) {
  4837. const data = cache[ key ];
  4838. delete data.metadata;
  4839. values.push( data );
  4840. }
  4841. return values;
  4842. }
  4843. }
  4844. clone( recursive ) {
  4845. return new this.constructor().copy( this, recursive );
  4846. }
  4847. copy( source, recursive = true ) {
  4848. this.name = source.name;
  4849. this.up.copy( source.up );
  4850. this.position.copy( source.position );
  4851. this.rotation.order = source.rotation.order;
  4852. this.quaternion.copy( source.quaternion );
  4853. this.scale.copy( source.scale );
  4854. this.matrix.copy( source.matrix );
  4855. this.matrixWorld.copy( source.matrixWorld );
  4856. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4857. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4858. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4859. this.layers.mask = source.layers.mask;
  4860. this.visible = source.visible;
  4861. this.castShadow = source.castShadow;
  4862. this.receiveShadow = source.receiveShadow;
  4863. this.frustumCulled = source.frustumCulled;
  4864. this.renderOrder = source.renderOrder;
  4865. this.animations = source.animations.slice();
  4866. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4867. if ( recursive === true ) {
  4868. for ( let i = 0; i < source.children.length; i ++ ) {
  4869. const child = source.children[ i ];
  4870. this.add( child.clone() );
  4871. }
  4872. }
  4873. return this;
  4874. }
  4875. }
  4876. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4877. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4878. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4879. const _v0$1 = /*@__PURE__*/ new Vector3();
  4880. const _v1$3 = /*@__PURE__*/ new Vector3();
  4881. const _v2$2 = /*@__PURE__*/ new Vector3();
  4882. const _v3$2 = /*@__PURE__*/ new Vector3();
  4883. const _vab = /*@__PURE__*/ new Vector3();
  4884. const _vac = /*@__PURE__*/ new Vector3();
  4885. const _vbc = /*@__PURE__*/ new Vector3();
  4886. const _vap = /*@__PURE__*/ new Vector3();
  4887. const _vbp = /*@__PURE__*/ new Vector3();
  4888. const _vcp = /*@__PURE__*/ new Vector3();
  4889. class Triangle {
  4890. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4891. this.a = a;
  4892. this.b = b;
  4893. this.c = c;
  4894. }
  4895. static getNormal( a, b, c, target ) {
  4896. target.subVectors( c, b );
  4897. _v0$1.subVectors( a, b );
  4898. target.cross( _v0$1 );
  4899. const targetLengthSq = target.lengthSq();
  4900. if ( targetLengthSq > 0 ) {
  4901. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4902. }
  4903. return target.set( 0, 0, 0 );
  4904. }
  4905. // static/instance method to calculate barycentric coordinates
  4906. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4907. static getBarycoord( point, a, b, c, target ) {
  4908. _v0$1.subVectors( c, a );
  4909. _v1$3.subVectors( b, a );
  4910. _v2$2.subVectors( point, a );
  4911. const dot00 = _v0$1.dot( _v0$1 );
  4912. const dot01 = _v0$1.dot( _v1$3 );
  4913. const dot02 = _v0$1.dot( _v2$2 );
  4914. const dot11 = _v1$3.dot( _v1$3 );
  4915. const dot12 = _v1$3.dot( _v2$2 );
  4916. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4917. // collinear or singular triangle
  4918. if ( denom === 0 ) {
  4919. target.set( 0, 0, 0 );
  4920. return null;
  4921. }
  4922. const invDenom = 1 / denom;
  4923. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4924. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4925. // barycentric coordinates must always sum to 1
  4926. return target.set( 1 - u - v, v, u );
  4927. }
  4928. static containsPoint( point, a, b, c ) {
  4929. // if the triangle is degenerate then we can't contain a point
  4930. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4931. return false;
  4932. }
  4933. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4934. }
  4935. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4936. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4937. target.x = 0;
  4938. target.y = 0;
  4939. if ( 'z' in target ) target.z = 0;
  4940. if ( 'w' in target ) target.w = 0;
  4941. return null;
  4942. }
  4943. target.setScalar( 0 );
  4944. target.addScaledVector( v1, _v3$2.x );
  4945. target.addScaledVector( v2, _v3$2.y );
  4946. target.addScaledVector( v3, _v3$2.z );
  4947. return target;
  4948. }
  4949. static isFrontFacing( a, b, c, direction ) {
  4950. _v0$1.subVectors( c, b );
  4951. _v1$3.subVectors( a, b );
  4952. // strictly front facing
  4953. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4954. }
  4955. set( a, b, c ) {
  4956. this.a.copy( a );
  4957. this.b.copy( b );
  4958. this.c.copy( c );
  4959. return this;
  4960. }
  4961. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4962. this.a.copy( points[ i0 ] );
  4963. this.b.copy( points[ i1 ] );
  4964. this.c.copy( points[ i2 ] );
  4965. return this;
  4966. }
  4967. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4968. this.a.fromBufferAttribute( attribute, i0 );
  4969. this.b.fromBufferAttribute( attribute, i1 );
  4970. this.c.fromBufferAttribute( attribute, i2 );
  4971. return this;
  4972. }
  4973. clone() {
  4974. return new this.constructor().copy( this );
  4975. }
  4976. copy( triangle ) {
  4977. this.a.copy( triangle.a );
  4978. this.b.copy( triangle.b );
  4979. this.c.copy( triangle.c );
  4980. return this;
  4981. }
  4982. getArea() {
  4983. _v0$1.subVectors( this.c, this.b );
  4984. _v1$3.subVectors( this.a, this.b );
  4985. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4986. }
  4987. getMidpoint( target ) {
  4988. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4989. }
  4990. getNormal( target ) {
  4991. return Triangle.getNormal( this.a, this.b, this.c, target );
  4992. }
  4993. getPlane( target ) {
  4994. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4995. }
  4996. getBarycoord( point, target ) {
  4997. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4998. }
  4999. getInterpolation( point, v1, v2, v3, target ) {
  5000. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5001. }
  5002. containsPoint( point ) {
  5003. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5004. }
  5005. isFrontFacing( direction ) {
  5006. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5007. }
  5008. intersectsBox( box ) {
  5009. return box.intersectsTriangle( this );
  5010. }
  5011. closestPointToPoint( p, target ) {
  5012. const a = this.a, b = this.b, c = this.c;
  5013. let v, w;
  5014. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5015. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5016. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5017. // basically, we're distinguishing which of the voronoi regions of the triangle
  5018. // the point lies in with the minimum amount of redundant computation.
  5019. _vab.subVectors( b, a );
  5020. _vac.subVectors( c, a );
  5021. _vap.subVectors( p, a );
  5022. const d1 = _vab.dot( _vap );
  5023. const d2 = _vac.dot( _vap );
  5024. if ( d1 <= 0 && d2 <= 0 ) {
  5025. // vertex region of A; barycentric coords (1, 0, 0)
  5026. return target.copy( a );
  5027. }
  5028. _vbp.subVectors( p, b );
  5029. const d3 = _vab.dot( _vbp );
  5030. const d4 = _vac.dot( _vbp );
  5031. if ( d3 >= 0 && d4 <= d3 ) {
  5032. // vertex region of B; barycentric coords (0, 1, 0)
  5033. return target.copy( b );
  5034. }
  5035. const vc = d1 * d4 - d3 * d2;
  5036. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5037. v = d1 / ( d1 - d3 );
  5038. // edge region of AB; barycentric coords (1-v, v, 0)
  5039. return target.copy( a ).addScaledVector( _vab, v );
  5040. }
  5041. _vcp.subVectors( p, c );
  5042. const d5 = _vab.dot( _vcp );
  5043. const d6 = _vac.dot( _vcp );
  5044. if ( d6 >= 0 && d5 <= d6 ) {
  5045. // vertex region of C; barycentric coords (0, 0, 1)
  5046. return target.copy( c );
  5047. }
  5048. const vb = d5 * d2 - d1 * d6;
  5049. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5050. w = d2 / ( d2 - d6 );
  5051. // edge region of AC; barycentric coords (1-w, 0, w)
  5052. return target.copy( a ).addScaledVector( _vac, w );
  5053. }
  5054. const va = d3 * d6 - d5 * d4;
  5055. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5056. _vbc.subVectors( c, b );
  5057. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5058. // edge region of BC; barycentric coords (0, 1-w, w)
  5059. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5060. }
  5061. // face region
  5062. const denom = 1 / ( va + vb + vc );
  5063. // u = va * denom
  5064. v = vb * denom;
  5065. w = vc * denom;
  5066. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5067. }
  5068. equals( triangle ) {
  5069. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5070. }
  5071. }
  5072. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5073. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5074. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5075. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5076. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5077. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5078. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5079. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5080. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5081. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5082. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5083. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5084. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5085. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5086. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5087. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5088. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5089. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5090. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5091. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5092. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5093. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5094. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5095. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5096. const _hslA = { h: 0, s: 0, l: 0 };
  5097. const _hslB = { h: 0, s: 0, l: 0 };
  5098. function hue2rgb( p, q, t ) {
  5099. if ( t < 0 ) t += 1;
  5100. if ( t > 1 ) t -= 1;
  5101. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5102. if ( t < 1 / 2 ) return q;
  5103. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5104. return p;
  5105. }
  5106. class Color {
  5107. constructor( r, g, b ) {
  5108. this.isColor = true;
  5109. this.r = 1;
  5110. this.g = 1;
  5111. this.b = 1;
  5112. return this.set( r, g, b );
  5113. }
  5114. set( r, g, b ) {
  5115. if ( g === undefined && b === undefined ) {
  5116. // r is THREE.Color, hex or string
  5117. const value = r;
  5118. if ( value && value.isColor ) {
  5119. this.copy( value );
  5120. } else if ( typeof value === 'number' ) {
  5121. this.setHex( value );
  5122. } else if ( typeof value === 'string' ) {
  5123. this.setStyle( value );
  5124. }
  5125. } else {
  5126. this.setRGB( r, g, b );
  5127. }
  5128. return this;
  5129. }
  5130. setScalar( scalar ) {
  5131. this.r = scalar;
  5132. this.g = scalar;
  5133. this.b = scalar;
  5134. return this;
  5135. }
  5136. setHex( hex, colorSpace = SRGBColorSpace ) {
  5137. hex = Math.floor( hex );
  5138. this.r = ( hex >> 16 & 255 ) / 255;
  5139. this.g = ( hex >> 8 & 255 ) / 255;
  5140. this.b = ( hex & 255 ) / 255;
  5141. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5142. return this;
  5143. }
  5144. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5145. this.r = r;
  5146. this.g = g;
  5147. this.b = b;
  5148. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5149. return this;
  5150. }
  5151. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5152. // h,s,l ranges are in 0.0 - 1.0
  5153. h = euclideanModulo( h, 1 );
  5154. s = clamp$1( s, 0, 1 );
  5155. l = clamp$1( l, 0, 1 );
  5156. if ( s === 0 ) {
  5157. this.r = this.g = this.b = l;
  5158. } else {
  5159. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5160. const q = ( 2 * l ) - p;
  5161. this.r = hue2rgb( q, p, h + 1 / 3 );
  5162. this.g = hue2rgb( q, p, h );
  5163. this.b = hue2rgb( q, p, h - 1 / 3 );
  5164. }
  5165. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5166. return this;
  5167. }
  5168. setStyle( style, colorSpace = SRGBColorSpace ) {
  5169. function handleAlpha( string ) {
  5170. if ( string === undefined ) return;
  5171. if ( parseFloat( string ) < 1 ) {
  5172. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5173. }
  5174. }
  5175. let m;
  5176. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5177. // rgb / hsl
  5178. let color;
  5179. const name = m[ 1 ];
  5180. const components = m[ 2 ];
  5181. switch ( name ) {
  5182. case 'rgb':
  5183. case 'rgba':
  5184. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5185. // rgb(255,0,0) rgba(255,0,0,0.5)
  5186. handleAlpha( color[ 4 ] );
  5187. return this.setRGB(
  5188. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5189. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5190. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5191. colorSpace
  5192. );
  5193. }
  5194. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5195. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5196. handleAlpha( color[ 4 ] );
  5197. return this.setRGB(
  5198. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5199. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5200. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5201. colorSpace
  5202. );
  5203. }
  5204. break;
  5205. case 'hsl':
  5206. case 'hsla':
  5207. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5208. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5209. handleAlpha( color[ 4 ] );
  5210. return this.setHSL(
  5211. parseFloat( color[ 1 ] ) / 360,
  5212. parseFloat( color[ 2 ] ) / 100,
  5213. parseFloat( color[ 3 ] ) / 100,
  5214. colorSpace
  5215. );
  5216. }
  5217. break;
  5218. default:
  5219. console.warn( 'THREE.Color: Unknown color model ' + style );
  5220. }
  5221. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5222. // hex color
  5223. const hex = m[ 1 ];
  5224. const size = hex.length;
  5225. if ( size === 3 ) {
  5226. // #ff0
  5227. return this.setRGB(
  5228. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5229. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5230. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5231. colorSpace
  5232. );
  5233. } else if ( size === 6 ) {
  5234. // #ff0000
  5235. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5236. } else {
  5237. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5238. }
  5239. } else if ( style && style.length > 0 ) {
  5240. return this.setColorName( style, colorSpace );
  5241. }
  5242. return this;
  5243. }
  5244. setColorName( style, colorSpace = SRGBColorSpace ) {
  5245. // color keywords
  5246. const hex = _colorKeywords[ style.toLowerCase() ];
  5247. if ( hex !== undefined ) {
  5248. // red
  5249. this.setHex( hex, colorSpace );
  5250. } else {
  5251. // unknown color
  5252. console.warn( 'THREE.Color: Unknown color ' + style );
  5253. }
  5254. return this;
  5255. }
  5256. clone() {
  5257. return new this.constructor( this.r, this.g, this.b );
  5258. }
  5259. copy( color ) {
  5260. this.r = color.r;
  5261. this.g = color.g;
  5262. this.b = color.b;
  5263. return this;
  5264. }
  5265. copySRGBToLinear( color ) {
  5266. this.r = SRGBToLinear( color.r );
  5267. this.g = SRGBToLinear( color.g );
  5268. this.b = SRGBToLinear( color.b );
  5269. return this;
  5270. }
  5271. copyLinearToSRGB( color ) {
  5272. this.r = LinearToSRGB( color.r );
  5273. this.g = LinearToSRGB( color.g );
  5274. this.b = LinearToSRGB( color.b );
  5275. return this;
  5276. }
  5277. convertSRGBToLinear() {
  5278. this.copySRGBToLinear( this );
  5279. return this;
  5280. }
  5281. convertLinearToSRGB() {
  5282. this.copyLinearToSRGB( this );
  5283. return this;
  5284. }
  5285. getHex( colorSpace = SRGBColorSpace ) {
  5286. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5287. 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 ) );
  5288. }
  5289. getHexString( colorSpace = SRGBColorSpace ) {
  5290. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5291. }
  5292. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5293. // h,s,l ranges are in 0.0 - 1.0
  5294. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5295. const r = _color.r, g = _color.g, b = _color.b;
  5296. const max = Math.max( r, g, b );
  5297. const min = Math.min( r, g, b );
  5298. let hue, saturation;
  5299. const lightness = ( min + max ) / 2.0;
  5300. if ( min === max ) {
  5301. hue = 0;
  5302. saturation = 0;
  5303. } else {
  5304. const delta = max - min;
  5305. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5306. switch ( max ) {
  5307. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5308. case g: hue = ( b - r ) / delta + 2; break;
  5309. case b: hue = ( r - g ) / delta + 4; break;
  5310. }
  5311. hue /= 6;
  5312. }
  5313. target.h = hue;
  5314. target.s = saturation;
  5315. target.l = lightness;
  5316. return target;
  5317. }
  5318. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5319. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5320. target.r = _color.r;
  5321. target.g = _color.g;
  5322. target.b = _color.b;
  5323. return target;
  5324. }
  5325. getStyle( colorSpace = SRGBColorSpace ) {
  5326. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5327. const r = _color.r, g = _color.g, b = _color.b;
  5328. if ( colorSpace !== SRGBColorSpace ) {
  5329. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5330. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5331. }
  5332. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5333. }
  5334. offsetHSL( h, s, l ) {
  5335. this.getHSL( _hslA );
  5336. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5337. }
  5338. add( color ) {
  5339. this.r += color.r;
  5340. this.g += color.g;
  5341. this.b += color.b;
  5342. return this;
  5343. }
  5344. addColors( color1, color2 ) {
  5345. this.r = color1.r + color2.r;
  5346. this.g = color1.g + color2.g;
  5347. this.b = color1.b + color2.b;
  5348. return this;
  5349. }
  5350. addScalar( s ) {
  5351. this.r += s;
  5352. this.g += s;
  5353. this.b += s;
  5354. return this;
  5355. }
  5356. sub( color ) {
  5357. this.r = Math.max( 0, this.r - color.r );
  5358. this.g = Math.max( 0, this.g - color.g );
  5359. this.b = Math.max( 0, this.b - color.b );
  5360. return this;
  5361. }
  5362. multiply( color ) {
  5363. this.r *= color.r;
  5364. this.g *= color.g;
  5365. this.b *= color.b;
  5366. return this;
  5367. }
  5368. multiplyScalar( s ) {
  5369. this.r *= s;
  5370. this.g *= s;
  5371. this.b *= s;
  5372. return this;
  5373. }
  5374. lerp( color, alpha ) {
  5375. this.r += ( color.r - this.r ) * alpha;
  5376. this.g += ( color.g - this.g ) * alpha;
  5377. this.b += ( color.b - this.b ) * alpha;
  5378. return this;
  5379. }
  5380. lerpColors( color1, color2, alpha ) {
  5381. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5382. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5383. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5384. return this;
  5385. }
  5386. lerpHSL( color, alpha ) {
  5387. this.getHSL( _hslA );
  5388. color.getHSL( _hslB );
  5389. const h = lerp( _hslA.h, _hslB.h, alpha );
  5390. const s = lerp( _hslA.s, _hslB.s, alpha );
  5391. const l = lerp( _hslA.l, _hslB.l, alpha );
  5392. this.setHSL( h, s, l );
  5393. return this;
  5394. }
  5395. setFromVector3( v ) {
  5396. this.r = v.x;
  5397. this.g = v.y;
  5398. this.b = v.z;
  5399. return this;
  5400. }
  5401. applyMatrix3( m ) {
  5402. const r = this.r, g = this.g, b = this.b;
  5403. const e = m.elements;
  5404. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5405. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5406. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5407. return this;
  5408. }
  5409. equals( c ) {
  5410. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5411. }
  5412. fromArray( array, offset = 0 ) {
  5413. this.r = array[ offset ];
  5414. this.g = array[ offset + 1 ];
  5415. this.b = array[ offset + 2 ];
  5416. return this;
  5417. }
  5418. toArray( array = [], offset = 0 ) {
  5419. array[ offset ] = this.r;
  5420. array[ offset + 1 ] = this.g;
  5421. array[ offset + 2 ] = this.b;
  5422. return array;
  5423. }
  5424. fromBufferAttribute( attribute, index ) {
  5425. this.r = attribute.getX( index );
  5426. this.g = attribute.getY( index );
  5427. this.b = attribute.getZ( index );
  5428. return this;
  5429. }
  5430. toJSON() {
  5431. return this.getHex();
  5432. }
  5433. *[ Symbol.iterator ]() {
  5434. yield this.r;
  5435. yield this.g;
  5436. yield this.b;
  5437. }
  5438. }
  5439. const _color = /*@__PURE__*/ new Color();
  5440. Color.NAMES = _colorKeywords;
  5441. let _materialId = 0;
  5442. class Material extends EventDispatcher {
  5443. constructor() {
  5444. super();
  5445. this.isMaterial = true;
  5446. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5447. this.uuid = generateUUID();
  5448. this.name = '';
  5449. this.type = 'Material';
  5450. this.blending = NormalBlending;
  5451. this.side = FrontSide;
  5452. this.vertexColors = false;
  5453. this.opacity = 1;
  5454. this.transparent = false;
  5455. this.alphaHash = false;
  5456. this.blendSrc = SrcAlphaFactor;
  5457. this.blendDst = OneMinusSrcAlphaFactor;
  5458. this.blendEquation = AddEquation;
  5459. this.blendSrcAlpha = null;
  5460. this.blendDstAlpha = null;
  5461. this.blendEquationAlpha = null;
  5462. this.blendColor = new Color( 0, 0, 0 );
  5463. this.blendAlpha = 0;
  5464. this.depthFunc = LessEqualDepth;
  5465. this.depthTest = true;
  5466. this.depthWrite = true;
  5467. this.stencilWriteMask = 0xff;
  5468. this.stencilFunc = AlwaysStencilFunc;
  5469. this.stencilRef = 0;
  5470. this.stencilFuncMask = 0xff;
  5471. this.stencilFail = KeepStencilOp;
  5472. this.stencilZFail = KeepStencilOp;
  5473. this.stencilZPass = KeepStencilOp;
  5474. this.stencilWrite = false;
  5475. this.clippingPlanes = null;
  5476. this.clipIntersection = false;
  5477. this.clipShadows = false;
  5478. this.shadowSide = null;
  5479. this.colorWrite = true;
  5480. this.precision = null; // override the renderer's default precision for this material
  5481. this.polygonOffset = false;
  5482. this.polygonOffsetFactor = 0;
  5483. this.polygonOffsetUnits = 0;
  5484. this.dithering = false;
  5485. this.alphaToCoverage = false;
  5486. this.premultipliedAlpha = false;
  5487. this.forceSinglePass = false;
  5488. this.visible = true;
  5489. this.toneMapped = true;
  5490. this.userData = {};
  5491. this.version = 0;
  5492. this._alphaTest = 0;
  5493. }
  5494. get alphaTest() {
  5495. return this._alphaTest;
  5496. }
  5497. set alphaTest( value ) {
  5498. if ( this._alphaTest > 0 !== value > 0 ) {
  5499. this.version ++;
  5500. }
  5501. this._alphaTest = value;
  5502. }
  5503. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5504. customProgramCacheKey() {
  5505. return this.onBeforeCompile.toString();
  5506. }
  5507. setValues( values ) {
  5508. if ( values === undefined ) return;
  5509. for ( const key in values ) {
  5510. const newValue = values[ key ];
  5511. if ( newValue === undefined ) {
  5512. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5513. continue;
  5514. }
  5515. const currentValue = this[ key ];
  5516. if ( currentValue === undefined ) {
  5517. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5518. continue;
  5519. }
  5520. if ( currentValue && currentValue.isColor ) {
  5521. currentValue.set( newValue );
  5522. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5523. currentValue.copy( newValue );
  5524. } else {
  5525. this[ key ] = newValue;
  5526. }
  5527. }
  5528. }
  5529. toJSON( meta ) {
  5530. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5531. if ( isRootObject ) {
  5532. meta = {
  5533. textures: {},
  5534. images: {}
  5535. };
  5536. }
  5537. const data = {
  5538. metadata: {
  5539. version: 4.6,
  5540. type: 'Material',
  5541. generator: 'Material.toJSON'
  5542. }
  5543. };
  5544. // standard Material serialization
  5545. data.uuid = this.uuid;
  5546. data.type = this.type;
  5547. if ( this.name !== '' ) data.name = this.name;
  5548. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5549. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5550. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5551. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5552. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5553. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5554. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5555. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5556. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5557. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5558. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5559. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5560. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5561. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5562. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5563. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5564. }
  5565. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5566. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5567. }
  5568. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5569. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5570. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5571. }
  5572. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5573. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5574. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5575. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5576. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5577. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5578. }
  5579. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5580. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5581. }
  5582. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5583. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5584. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5585. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5586. }
  5587. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5588. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5589. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5590. if ( this.lightMap && this.lightMap.isTexture ) {
  5591. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5592. data.lightMapIntensity = this.lightMapIntensity;
  5593. }
  5594. if ( this.aoMap && this.aoMap.isTexture ) {
  5595. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5596. data.aoMapIntensity = this.aoMapIntensity;
  5597. }
  5598. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5599. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5600. data.bumpScale = this.bumpScale;
  5601. }
  5602. if ( this.normalMap && this.normalMap.isTexture ) {
  5603. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5604. data.normalMapType = this.normalMapType;
  5605. data.normalScale = this.normalScale.toArray();
  5606. }
  5607. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5608. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5609. data.displacementScale = this.displacementScale;
  5610. data.displacementBias = this.displacementBias;
  5611. }
  5612. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5613. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5614. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5615. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5616. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5617. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5618. if ( this.envMap && this.envMap.isTexture ) {
  5619. data.envMap = this.envMap.toJSON( meta ).uuid;
  5620. if ( this.combine !== undefined ) data.combine = this.combine;
  5621. }
  5622. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5623. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5624. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5625. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5626. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5627. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5628. }
  5629. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5630. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5631. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5632. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5633. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5634. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5635. if ( this.size !== undefined ) data.size = this.size;
  5636. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5637. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5638. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5639. if ( this.side !== FrontSide ) data.side = this.side;
  5640. if ( this.vertexColors === true ) data.vertexColors = true;
  5641. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5642. if ( this.transparent === true ) data.transparent = true;
  5643. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5644. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5645. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5646. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5647. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5648. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5649. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5650. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5651. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5652. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5653. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5654. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5655. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5656. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5657. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5658. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5659. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5660. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5661. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5662. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5663. // rotation (SpriteMaterial)
  5664. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5665. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5666. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5667. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5668. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5669. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5670. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5671. if ( this.scale !== undefined ) data.scale = this.scale;
  5672. if ( this.dithering === true ) data.dithering = true;
  5673. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5674. if ( this.alphaHash === true ) data.alphaHash = true;
  5675. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5676. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5677. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5678. if ( this.wireframe === true ) data.wireframe = true;
  5679. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5680. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5681. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5682. if ( this.flatShading === true ) data.flatShading = true;
  5683. if ( this.visible === false ) data.visible = false;
  5684. if ( this.toneMapped === false ) data.toneMapped = false;
  5685. if ( this.fog === false ) data.fog = false;
  5686. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5687. // TODO: Copied from Object3D.toJSON
  5688. function extractFromCache( cache ) {
  5689. const values = [];
  5690. for ( const key in cache ) {
  5691. const data = cache[ key ];
  5692. delete data.metadata;
  5693. values.push( data );
  5694. }
  5695. return values;
  5696. }
  5697. if ( isRootObject ) {
  5698. const textures = extractFromCache( meta.textures );
  5699. const images = extractFromCache( meta.images );
  5700. if ( textures.length > 0 ) data.textures = textures;
  5701. if ( images.length > 0 ) data.images = images;
  5702. }
  5703. return data;
  5704. }
  5705. clone() {
  5706. return new this.constructor().copy( this );
  5707. }
  5708. copy( source ) {
  5709. this.name = source.name;
  5710. this.blending = source.blending;
  5711. this.side = source.side;
  5712. this.vertexColors = source.vertexColors;
  5713. this.opacity = source.opacity;
  5714. this.transparent = source.transparent;
  5715. this.blendSrc = source.blendSrc;
  5716. this.blendDst = source.blendDst;
  5717. this.blendEquation = source.blendEquation;
  5718. this.blendSrcAlpha = source.blendSrcAlpha;
  5719. this.blendDstAlpha = source.blendDstAlpha;
  5720. this.blendEquationAlpha = source.blendEquationAlpha;
  5721. this.blendColor.copy( source.blendColor );
  5722. this.blendAlpha = source.blendAlpha;
  5723. this.depthFunc = source.depthFunc;
  5724. this.depthTest = source.depthTest;
  5725. this.depthWrite = source.depthWrite;
  5726. this.stencilWriteMask = source.stencilWriteMask;
  5727. this.stencilFunc = source.stencilFunc;
  5728. this.stencilRef = source.stencilRef;
  5729. this.stencilFuncMask = source.stencilFuncMask;
  5730. this.stencilFail = source.stencilFail;
  5731. this.stencilZFail = source.stencilZFail;
  5732. this.stencilZPass = source.stencilZPass;
  5733. this.stencilWrite = source.stencilWrite;
  5734. const srcPlanes = source.clippingPlanes;
  5735. let dstPlanes = null;
  5736. if ( srcPlanes !== null ) {
  5737. const n = srcPlanes.length;
  5738. dstPlanes = new Array( n );
  5739. for ( let i = 0; i !== n; ++ i ) {
  5740. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5741. }
  5742. }
  5743. this.clippingPlanes = dstPlanes;
  5744. this.clipIntersection = source.clipIntersection;
  5745. this.clipShadows = source.clipShadows;
  5746. this.shadowSide = source.shadowSide;
  5747. this.colorWrite = source.colorWrite;
  5748. this.precision = source.precision;
  5749. this.polygonOffset = source.polygonOffset;
  5750. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5751. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5752. this.dithering = source.dithering;
  5753. this.alphaTest = source.alphaTest;
  5754. this.alphaHash = source.alphaHash;
  5755. this.alphaToCoverage = source.alphaToCoverage;
  5756. this.premultipliedAlpha = source.premultipliedAlpha;
  5757. this.forceSinglePass = source.forceSinglePass;
  5758. this.visible = source.visible;
  5759. this.toneMapped = source.toneMapped;
  5760. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5761. return this;
  5762. }
  5763. dispose() {
  5764. this.dispatchEvent( { type: 'dispose' } );
  5765. }
  5766. set needsUpdate( value ) {
  5767. if ( value === true ) this.version ++;
  5768. }
  5769. onBuild( /* shaderobject, renderer */ ) {
  5770. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5771. }
  5772. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {
  5773. console.warn( 'Material: onBeforeRender() has been removed.' ); // @deprecated, r166
  5774. }
  5775. }
  5776. class MeshBasicMaterial extends Material {
  5777. constructor( parameters ) {
  5778. super();
  5779. this.isMeshBasicMaterial = true;
  5780. this.type = 'MeshBasicMaterial';
  5781. this.color = new Color( 0xffffff ); // emissive
  5782. this.map = null;
  5783. this.lightMap = null;
  5784. this.lightMapIntensity = 1.0;
  5785. this.aoMap = null;
  5786. this.aoMapIntensity = 1.0;
  5787. this.specularMap = null;
  5788. this.alphaMap = null;
  5789. this.envMap = null;
  5790. this.envMapRotation = new Euler();
  5791. this.combine = MultiplyOperation;
  5792. this.reflectivity = 1;
  5793. this.refractionRatio = 0.98;
  5794. this.wireframe = false;
  5795. this.wireframeLinewidth = 1;
  5796. this.wireframeLinecap = 'round';
  5797. this.wireframeLinejoin = 'round';
  5798. this.fog = true;
  5799. this.setValues( parameters );
  5800. }
  5801. copy( source ) {
  5802. super.copy( source );
  5803. this.color.copy( source.color );
  5804. this.map = source.map;
  5805. this.lightMap = source.lightMap;
  5806. this.lightMapIntensity = source.lightMapIntensity;
  5807. this.aoMap = source.aoMap;
  5808. this.aoMapIntensity = source.aoMapIntensity;
  5809. this.specularMap = source.specularMap;
  5810. this.alphaMap = source.alphaMap;
  5811. this.envMap = source.envMap;
  5812. this.envMapRotation.copy( source.envMapRotation );
  5813. this.combine = source.combine;
  5814. this.reflectivity = source.reflectivity;
  5815. this.refractionRatio = source.refractionRatio;
  5816. this.wireframe = source.wireframe;
  5817. this.wireframeLinewidth = source.wireframeLinewidth;
  5818. this.wireframeLinecap = source.wireframeLinecap;
  5819. this.wireframeLinejoin = source.wireframeLinejoin;
  5820. this.fog = source.fog;
  5821. return this;
  5822. }
  5823. }
  5824. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5825. const _tables = /*@__PURE__*/ _generateTables();
  5826. function _generateTables() {
  5827. // float32 to float16 helpers
  5828. const buffer = new ArrayBuffer( 4 );
  5829. const floatView = new Float32Array( buffer );
  5830. const uint32View = new Uint32Array( buffer );
  5831. const baseTable = new Uint32Array( 512 );
  5832. const shiftTable = new Uint32Array( 512 );
  5833. for ( let i = 0; i < 256; ++ i ) {
  5834. const e = i - 127;
  5835. // very small number (0, -0)
  5836. if ( e < - 27 ) {
  5837. baseTable[ i ] = 0x0000;
  5838. baseTable[ i | 0x100 ] = 0x8000;
  5839. shiftTable[ i ] = 24;
  5840. shiftTable[ i | 0x100 ] = 24;
  5841. // small number (denorm)
  5842. } else if ( e < - 14 ) {
  5843. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5844. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5845. shiftTable[ i ] = - e - 1;
  5846. shiftTable[ i | 0x100 ] = - e - 1;
  5847. // normal number
  5848. } else if ( e <= 15 ) {
  5849. baseTable[ i ] = ( e + 15 ) << 10;
  5850. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5851. shiftTable[ i ] = 13;
  5852. shiftTable[ i | 0x100 ] = 13;
  5853. // large number (Infinity, -Infinity)
  5854. } else if ( e < 128 ) {
  5855. baseTable[ i ] = 0x7c00;
  5856. baseTable[ i | 0x100 ] = 0xfc00;
  5857. shiftTable[ i ] = 24;
  5858. shiftTable[ i | 0x100 ] = 24;
  5859. // stay (NaN, Infinity, -Infinity)
  5860. } else {
  5861. baseTable[ i ] = 0x7c00;
  5862. baseTable[ i | 0x100 ] = 0xfc00;
  5863. shiftTable[ i ] = 13;
  5864. shiftTable[ i | 0x100 ] = 13;
  5865. }
  5866. }
  5867. // float16 to float32 helpers
  5868. const mantissaTable = new Uint32Array( 2048 );
  5869. const exponentTable = new Uint32Array( 64 );
  5870. const offsetTable = new Uint32Array( 64 );
  5871. for ( let i = 1; i < 1024; ++ i ) {
  5872. let m = i << 13; // zero pad mantissa bits
  5873. let e = 0; // zero exponent
  5874. // normalized
  5875. while ( ( m & 0x00800000 ) === 0 ) {
  5876. m <<= 1;
  5877. e -= 0x00800000; // decrement exponent
  5878. }
  5879. m &= ~ 0x00800000; // clear leading 1 bit
  5880. e += 0x38800000; // adjust bias
  5881. mantissaTable[ i ] = m | e;
  5882. }
  5883. for ( let i = 1024; i < 2048; ++ i ) {
  5884. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5885. }
  5886. for ( let i = 1; i < 31; ++ i ) {
  5887. exponentTable[ i ] = i << 23;
  5888. }
  5889. exponentTable[ 31 ] = 0x47800000;
  5890. exponentTable[ 32 ] = 0x80000000;
  5891. for ( let i = 33; i < 63; ++ i ) {
  5892. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5893. }
  5894. exponentTable[ 63 ] = 0xc7800000;
  5895. for ( let i = 1; i < 64; ++ i ) {
  5896. if ( i !== 32 ) {
  5897. offsetTable[ i ] = 1024;
  5898. }
  5899. }
  5900. return {
  5901. floatView: floatView,
  5902. uint32View: uint32View,
  5903. baseTable: baseTable,
  5904. shiftTable: shiftTable,
  5905. mantissaTable: mantissaTable,
  5906. exponentTable: exponentTable,
  5907. offsetTable: offsetTable
  5908. };
  5909. }
  5910. // float32 to float16
  5911. function toHalfFloat( val ) {
  5912. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5913. val = clamp$1( val, - 65504, 65504 );
  5914. _tables.floatView[ 0 ] = val;
  5915. const f = _tables.uint32View[ 0 ];
  5916. const e = ( f >> 23 ) & 0x1ff;
  5917. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5918. }
  5919. // float16 to float32
  5920. function fromHalfFloat( val ) {
  5921. const m = val >> 10;
  5922. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5923. return _tables.floatView[ 0 ];
  5924. }
  5925. const DataUtils = {
  5926. toHalfFloat: toHalfFloat,
  5927. fromHalfFloat: fromHalfFloat,
  5928. };
  5929. const _vector$9 = /*@__PURE__*/ new Vector3();
  5930. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5931. class BufferAttribute {
  5932. constructor( array, itemSize, normalized = false ) {
  5933. if ( Array.isArray( array ) ) {
  5934. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5935. }
  5936. this.isBufferAttribute = true;
  5937. this.name = '';
  5938. this.array = array;
  5939. this.itemSize = itemSize;
  5940. this.count = array !== undefined ? array.length / itemSize : 0;
  5941. this.normalized = normalized;
  5942. this.usage = StaticDrawUsage;
  5943. this._updateRange = { offset: 0, count: - 1 };
  5944. this.updateRanges = [];
  5945. this.gpuType = FloatType;
  5946. this.version = 0;
  5947. }
  5948. onUploadCallback() {}
  5949. set needsUpdate( value ) {
  5950. if ( value === true ) this.version ++;
  5951. }
  5952. get updateRange() {
  5953. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5954. return this._updateRange;
  5955. }
  5956. setUsage( value ) {
  5957. this.usage = value;
  5958. return this;
  5959. }
  5960. addUpdateRange( start, count ) {
  5961. this.updateRanges.push( { start, count } );
  5962. }
  5963. clearUpdateRanges() {
  5964. this.updateRanges.length = 0;
  5965. }
  5966. copy( source ) {
  5967. this.name = source.name;
  5968. this.array = new source.array.constructor( source.array );
  5969. this.itemSize = source.itemSize;
  5970. this.count = source.count;
  5971. this.normalized = source.normalized;
  5972. this.usage = source.usage;
  5973. this.gpuType = source.gpuType;
  5974. return this;
  5975. }
  5976. copyAt( index1, attribute, index2 ) {
  5977. index1 *= this.itemSize;
  5978. index2 *= attribute.itemSize;
  5979. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5980. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5981. }
  5982. return this;
  5983. }
  5984. copyArray( array ) {
  5985. this.array.set( array );
  5986. return this;
  5987. }
  5988. applyMatrix3( m ) {
  5989. if ( this.itemSize === 2 ) {
  5990. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5991. _vector2$1.fromBufferAttribute( this, i );
  5992. _vector2$1.applyMatrix3( m );
  5993. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5994. }
  5995. } else if ( this.itemSize === 3 ) {
  5996. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5997. _vector$9.fromBufferAttribute( this, i );
  5998. _vector$9.applyMatrix3( m );
  5999. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6000. }
  6001. }
  6002. return this;
  6003. }
  6004. applyMatrix4( m ) {
  6005. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6006. _vector$9.fromBufferAttribute( this, i );
  6007. _vector$9.applyMatrix4( m );
  6008. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6009. }
  6010. return this;
  6011. }
  6012. applyNormalMatrix( m ) {
  6013. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6014. _vector$9.fromBufferAttribute( this, i );
  6015. _vector$9.applyNormalMatrix( m );
  6016. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6017. }
  6018. return this;
  6019. }
  6020. transformDirection( m ) {
  6021. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6022. _vector$9.fromBufferAttribute( this, i );
  6023. _vector$9.transformDirection( m );
  6024. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6025. }
  6026. return this;
  6027. }
  6028. set( value, offset = 0 ) {
  6029. // Matching BufferAttribute constructor, do not normalize the array.
  6030. this.array.set( value, offset );
  6031. return this;
  6032. }
  6033. getComponent( index, component ) {
  6034. let value = this.array[ index * this.itemSize + component ];
  6035. if ( this.normalized ) value = denormalize( value, this.array );
  6036. return value;
  6037. }
  6038. setComponent( index, component, value ) {
  6039. if ( this.normalized ) value = normalize$1( value, this.array );
  6040. this.array[ index * this.itemSize + component ] = value;
  6041. return this;
  6042. }
  6043. getX( index ) {
  6044. let x = this.array[ index * this.itemSize ];
  6045. if ( this.normalized ) x = denormalize( x, this.array );
  6046. return x;
  6047. }
  6048. setX( index, x ) {
  6049. if ( this.normalized ) x = normalize$1( x, this.array );
  6050. this.array[ index * this.itemSize ] = x;
  6051. return this;
  6052. }
  6053. getY( index ) {
  6054. let y = this.array[ index * this.itemSize + 1 ];
  6055. if ( this.normalized ) y = denormalize( y, this.array );
  6056. return y;
  6057. }
  6058. setY( index, y ) {
  6059. if ( this.normalized ) y = normalize$1( y, this.array );
  6060. this.array[ index * this.itemSize + 1 ] = y;
  6061. return this;
  6062. }
  6063. getZ( index ) {
  6064. let z = this.array[ index * this.itemSize + 2 ];
  6065. if ( this.normalized ) z = denormalize( z, this.array );
  6066. return z;
  6067. }
  6068. setZ( index, z ) {
  6069. if ( this.normalized ) z = normalize$1( z, this.array );
  6070. this.array[ index * this.itemSize + 2 ] = z;
  6071. return this;
  6072. }
  6073. getW( index ) {
  6074. let w = this.array[ index * this.itemSize + 3 ];
  6075. if ( this.normalized ) w = denormalize( w, this.array );
  6076. return w;
  6077. }
  6078. setW( index, w ) {
  6079. if ( this.normalized ) w = normalize$1( w, this.array );
  6080. this.array[ index * this.itemSize + 3 ] = w;
  6081. return this;
  6082. }
  6083. setXY( index, x, y ) {
  6084. index *= this.itemSize;
  6085. if ( this.normalized ) {
  6086. x = normalize$1( x, this.array );
  6087. y = normalize$1( y, this.array );
  6088. }
  6089. this.array[ index + 0 ] = x;
  6090. this.array[ index + 1 ] = y;
  6091. return this;
  6092. }
  6093. setXYZ( index, x, y, z ) {
  6094. index *= this.itemSize;
  6095. if ( this.normalized ) {
  6096. x = normalize$1( x, this.array );
  6097. y = normalize$1( y, this.array );
  6098. z = normalize$1( z, this.array );
  6099. }
  6100. this.array[ index + 0 ] = x;
  6101. this.array[ index + 1 ] = y;
  6102. this.array[ index + 2 ] = z;
  6103. return this;
  6104. }
  6105. setXYZW( index, x, y, z, w ) {
  6106. index *= this.itemSize;
  6107. if ( this.normalized ) {
  6108. x = normalize$1( x, this.array );
  6109. y = normalize$1( y, this.array );
  6110. z = normalize$1( z, this.array );
  6111. w = normalize$1( w, this.array );
  6112. }
  6113. this.array[ index + 0 ] = x;
  6114. this.array[ index + 1 ] = y;
  6115. this.array[ index + 2 ] = z;
  6116. this.array[ index + 3 ] = w;
  6117. return this;
  6118. }
  6119. onUpload( callback ) {
  6120. this.onUploadCallback = callback;
  6121. return this;
  6122. }
  6123. clone() {
  6124. return new this.constructor( this.array, this.itemSize ).copy( this );
  6125. }
  6126. toJSON() {
  6127. const data = {
  6128. itemSize: this.itemSize,
  6129. type: this.array.constructor.name,
  6130. array: Array.from( this.array ),
  6131. normalized: this.normalized
  6132. };
  6133. if ( this.name !== '' ) data.name = this.name;
  6134. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6135. return data;
  6136. }
  6137. }
  6138. //
  6139. class Int8BufferAttribute extends BufferAttribute {
  6140. constructor( array, itemSize, normalized ) {
  6141. super( new Int8Array( array ), itemSize, normalized );
  6142. }
  6143. }
  6144. class Uint8BufferAttribute extends BufferAttribute {
  6145. constructor( array, itemSize, normalized ) {
  6146. super( new Uint8Array( array ), itemSize, normalized );
  6147. }
  6148. }
  6149. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6150. constructor( array, itemSize, normalized ) {
  6151. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6152. }
  6153. }
  6154. class Int16BufferAttribute extends BufferAttribute {
  6155. constructor( array, itemSize, normalized ) {
  6156. super( new Int16Array( array ), itemSize, normalized );
  6157. }
  6158. }
  6159. class Uint16BufferAttribute extends BufferAttribute {
  6160. constructor( array, itemSize, normalized ) {
  6161. super( new Uint16Array( array ), itemSize, normalized );
  6162. }
  6163. }
  6164. class Int32BufferAttribute extends BufferAttribute {
  6165. constructor( array, itemSize, normalized ) {
  6166. super( new Int32Array( array ), itemSize, normalized );
  6167. }
  6168. }
  6169. class Uint32BufferAttribute extends BufferAttribute {
  6170. constructor( array, itemSize, normalized ) {
  6171. super( new Uint32Array( array ), itemSize, normalized );
  6172. }
  6173. }
  6174. class Float16BufferAttribute extends BufferAttribute {
  6175. constructor( array, itemSize, normalized ) {
  6176. super( new Uint16Array( array ), itemSize, normalized );
  6177. this.isFloat16BufferAttribute = true;
  6178. }
  6179. getX( index ) {
  6180. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6181. if ( this.normalized ) x = denormalize( x, this.array );
  6182. return x;
  6183. }
  6184. setX( index, x ) {
  6185. if ( this.normalized ) x = normalize$1( x, this.array );
  6186. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6187. return this;
  6188. }
  6189. getY( index ) {
  6190. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6191. if ( this.normalized ) y = denormalize( y, this.array );
  6192. return y;
  6193. }
  6194. setY( index, y ) {
  6195. if ( this.normalized ) y = normalize$1( y, this.array );
  6196. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6197. return this;
  6198. }
  6199. getZ( index ) {
  6200. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6201. if ( this.normalized ) z = denormalize( z, this.array );
  6202. return z;
  6203. }
  6204. setZ( index, z ) {
  6205. if ( this.normalized ) z = normalize$1( z, this.array );
  6206. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6207. return this;
  6208. }
  6209. getW( index ) {
  6210. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6211. if ( this.normalized ) w = denormalize( w, this.array );
  6212. return w;
  6213. }
  6214. setW( index, w ) {
  6215. if ( this.normalized ) w = normalize$1( w, this.array );
  6216. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6217. return this;
  6218. }
  6219. setXY( index, x, y ) {
  6220. index *= this.itemSize;
  6221. if ( this.normalized ) {
  6222. x = normalize$1( x, this.array );
  6223. y = normalize$1( y, this.array );
  6224. }
  6225. this.array[ index + 0 ] = toHalfFloat( x );
  6226. this.array[ index + 1 ] = toHalfFloat( y );
  6227. return this;
  6228. }
  6229. setXYZ( index, x, y, z ) {
  6230. index *= this.itemSize;
  6231. if ( this.normalized ) {
  6232. x = normalize$1( x, this.array );
  6233. y = normalize$1( y, this.array );
  6234. z = normalize$1( z, this.array );
  6235. }
  6236. this.array[ index + 0 ] = toHalfFloat( x );
  6237. this.array[ index + 1 ] = toHalfFloat( y );
  6238. this.array[ index + 2 ] = toHalfFloat( z );
  6239. return this;
  6240. }
  6241. setXYZW( index, x, y, z, w ) {
  6242. index *= this.itemSize;
  6243. if ( this.normalized ) {
  6244. x = normalize$1( x, this.array );
  6245. y = normalize$1( y, this.array );
  6246. z = normalize$1( z, this.array );
  6247. w = normalize$1( w, this.array );
  6248. }
  6249. this.array[ index + 0 ] = toHalfFloat( x );
  6250. this.array[ index + 1 ] = toHalfFloat( y );
  6251. this.array[ index + 2 ] = toHalfFloat( z );
  6252. this.array[ index + 3 ] = toHalfFloat( w );
  6253. return this;
  6254. }
  6255. }
  6256. class Float32BufferAttribute extends BufferAttribute {
  6257. constructor( array, itemSize, normalized ) {
  6258. super( new Float32Array( array ), itemSize, normalized );
  6259. }
  6260. }
  6261. let _id$6 = 0;
  6262. const _m1 = /*@__PURE__*/ new Matrix4();
  6263. const _obj = /*@__PURE__*/ new Object3D();
  6264. const _offset = /*@__PURE__*/ new Vector3();
  6265. const _box$2 = /*@__PURE__*/ new Box3();
  6266. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6267. const _vector$8 = /*@__PURE__*/ new Vector3();
  6268. class BufferGeometry extends EventDispatcher {
  6269. constructor() {
  6270. super();
  6271. this.isBufferGeometry = true;
  6272. Object.defineProperty( this, 'id', { value: _id$6 ++ } );
  6273. this.uuid = generateUUID();
  6274. this.name = '';
  6275. this.type = 'BufferGeometry';
  6276. this.index = null;
  6277. this.attributes = {};
  6278. this.morphAttributes = {};
  6279. this.morphTargetsRelative = false;
  6280. this.groups = [];
  6281. this.boundingBox = null;
  6282. this.boundingSphere = null;
  6283. this.drawRange = { start: 0, count: Infinity };
  6284. this.userData = {};
  6285. }
  6286. getIndex() {
  6287. return this.index;
  6288. }
  6289. setIndex( index ) {
  6290. if ( Array.isArray( index ) ) {
  6291. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6292. } else {
  6293. this.index = index;
  6294. }
  6295. return this;
  6296. }
  6297. getAttribute( name ) {
  6298. return this.attributes[ name ];
  6299. }
  6300. setAttribute( name, attribute ) {
  6301. this.attributes[ name ] = attribute;
  6302. return this;
  6303. }
  6304. deleteAttribute( name ) {
  6305. delete this.attributes[ name ];
  6306. return this;
  6307. }
  6308. hasAttribute( name ) {
  6309. return this.attributes[ name ] !== undefined;
  6310. }
  6311. addGroup( start, count, materialIndex = 0 ) {
  6312. this.groups.push( {
  6313. start: start,
  6314. count: count,
  6315. materialIndex: materialIndex
  6316. } );
  6317. }
  6318. clearGroups() {
  6319. this.groups = [];
  6320. }
  6321. setDrawRange( start, count ) {
  6322. this.drawRange.start = start;
  6323. this.drawRange.count = count;
  6324. }
  6325. applyMatrix4( matrix ) {
  6326. const position = this.attributes.position;
  6327. if ( position !== undefined ) {
  6328. position.applyMatrix4( matrix );
  6329. position.needsUpdate = true;
  6330. }
  6331. const normal = this.attributes.normal;
  6332. if ( normal !== undefined ) {
  6333. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6334. normal.applyNormalMatrix( normalMatrix );
  6335. normal.needsUpdate = true;
  6336. }
  6337. const tangent = this.attributes.tangent;
  6338. if ( tangent !== undefined ) {
  6339. tangent.transformDirection( matrix );
  6340. tangent.needsUpdate = true;
  6341. }
  6342. if ( this.boundingBox !== null ) {
  6343. this.computeBoundingBox();
  6344. }
  6345. if ( this.boundingSphere !== null ) {
  6346. this.computeBoundingSphere();
  6347. }
  6348. return this;
  6349. }
  6350. applyQuaternion( q ) {
  6351. _m1.makeRotationFromQuaternion( q );
  6352. this.applyMatrix4( _m1 );
  6353. return this;
  6354. }
  6355. rotateX( angle ) {
  6356. // rotate geometry around world x-axis
  6357. _m1.makeRotationX( angle );
  6358. this.applyMatrix4( _m1 );
  6359. return this;
  6360. }
  6361. rotateY( angle ) {
  6362. // rotate geometry around world y-axis
  6363. _m1.makeRotationY( angle );
  6364. this.applyMatrix4( _m1 );
  6365. return this;
  6366. }
  6367. rotateZ( angle ) {
  6368. // rotate geometry around world z-axis
  6369. _m1.makeRotationZ( angle );
  6370. this.applyMatrix4( _m1 );
  6371. return this;
  6372. }
  6373. translate( x, y, z ) {
  6374. // translate geometry
  6375. _m1.makeTranslation( x, y, z );
  6376. this.applyMatrix4( _m1 );
  6377. return this;
  6378. }
  6379. scale( x, y, z ) {
  6380. // scale geometry
  6381. _m1.makeScale( x, y, z );
  6382. this.applyMatrix4( _m1 );
  6383. return this;
  6384. }
  6385. lookAt( vector ) {
  6386. _obj.lookAt( vector );
  6387. _obj.updateMatrix();
  6388. this.applyMatrix4( _obj.matrix );
  6389. return this;
  6390. }
  6391. center() {
  6392. this.computeBoundingBox();
  6393. this.boundingBox.getCenter( _offset ).negate();
  6394. this.translate( _offset.x, _offset.y, _offset.z );
  6395. return this;
  6396. }
  6397. setFromPoints( points ) {
  6398. const position = [];
  6399. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6400. const point = points[ i ];
  6401. position.push( point.x, point.y, point.z || 0 );
  6402. }
  6403. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6404. return this;
  6405. }
  6406. computeBoundingBox() {
  6407. if ( this.boundingBox === null ) {
  6408. this.boundingBox = new Box3();
  6409. }
  6410. const position = this.attributes.position;
  6411. const morphAttributesPosition = this.morphAttributes.position;
  6412. if ( position && position.isGLBufferAttribute ) {
  6413. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6414. this.boundingBox.set(
  6415. new Vector3( - Infinity, - Infinity, - Infinity ),
  6416. new Vector3( + Infinity, + Infinity, + Infinity )
  6417. );
  6418. return;
  6419. }
  6420. if ( position !== undefined ) {
  6421. this.boundingBox.setFromBufferAttribute( position );
  6422. // process morph attributes if present
  6423. if ( morphAttributesPosition ) {
  6424. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6425. const morphAttribute = morphAttributesPosition[ i ];
  6426. _box$2.setFromBufferAttribute( morphAttribute );
  6427. if ( this.morphTargetsRelative ) {
  6428. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6429. this.boundingBox.expandByPoint( _vector$8 );
  6430. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6431. this.boundingBox.expandByPoint( _vector$8 );
  6432. } else {
  6433. this.boundingBox.expandByPoint( _box$2.min );
  6434. this.boundingBox.expandByPoint( _box$2.max );
  6435. }
  6436. }
  6437. }
  6438. } else {
  6439. this.boundingBox.makeEmpty();
  6440. }
  6441. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6442. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6443. }
  6444. }
  6445. computeBoundingSphere() {
  6446. if ( this.boundingSphere === null ) {
  6447. this.boundingSphere = new Sphere();
  6448. }
  6449. const position = this.attributes.position;
  6450. const morphAttributesPosition = this.morphAttributes.position;
  6451. if ( position && position.isGLBufferAttribute ) {
  6452. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6453. this.boundingSphere.set( new Vector3(), Infinity );
  6454. return;
  6455. }
  6456. if ( position ) {
  6457. // first, find the center of the bounding sphere
  6458. const center = this.boundingSphere.center;
  6459. _box$2.setFromBufferAttribute( position );
  6460. // process morph attributes if present
  6461. if ( morphAttributesPosition ) {
  6462. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6463. const morphAttribute = morphAttributesPosition[ i ];
  6464. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6465. if ( this.morphTargetsRelative ) {
  6466. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6467. _box$2.expandByPoint( _vector$8 );
  6468. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6469. _box$2.expandByPoint( _vector$8 );
  6470. } else {
  6471. _box$2.expandByPoint( _boxMorphTargets.min );
  6472. _box$2.expandByPoint( _boxMorphTargets.max );
  6473. }
  6474. }
  6475. }
  6476. _box$2.getCenter( center );
  6477. // second, try to find a boundingSphere with a radius smaller than the
  6478. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6479. let maxRadiusSq = 0;
  6480. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6481. _vector$8.fromBufferAttribute( position, i );
  6482. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6483. }
  6484. // process morph attributes if present
  6485. if ( morphAttributesPosition ) {
  6486. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6487. const morphAttribute = morphAttributesPosition[ i ];
  6488. const morphTargetsRelative = this.morphTargetsRelative;
  6489. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6490. _vector$8.fromBufferAttribute( morphAttribute, j );
  6491. if ( morphTargetsRelative ) {
  6492. _offset.fromBufferAttribute( position, j );
  6493. _vector$8.add( _offset );
  6494. }
  6495. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6496. }
  6497. }
  6498. }
  6499. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6500. if ( isNaN( this.boundingSphere.radius ) ) {
  6501. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6502. }
  6503. }
  6504. }
  6505. computeTangents() {
  6506. const index = this.index;
  6507. const attributes = this.attributes;
  6508. // based on http://www.terathon.com/code/tangent.html
  6509. // (per vertex tangents)
  6510. if ( index === null ||
  6511. attributes.position === undefined ||
  6512. attributes.normal === undefined ||
  6513. attributes.uv === undefined ) {
  6514. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6515. return;
  6516. }
  6517. const positionAttribute = attributes.position;
  6518. const normalAttribute = attributes.normal;
  6519. const uvAttribute = attributes.uv;
  6520. if ( this.hasAttribute( 'tangent' ) === false ) {
  6521. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6522. }
  6523. const tangentAttribute = this.getAttribute( 'tangent' );
  6524. const tan1 = [], tan2 = [];
  6525. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6526. tan1[ i ] = new Vector3();
  6527. tan2[ i ] = new Vector3();
  6528. }
  6529. const vA = new Vector3(),
  6530. vB = new Vector3(),
  6531. vC = new Vector3(),
  6532. uvA = new Vector2(),
  6533. uvB = new Vector2(),
  6534. uvC = new Vector2(),
  6535. sdir = new Vector3(),
  6536. tdir = new Vector3();
  6537. function handleTriangle( a, b, c ) {
  6538. vA.fromBufferAttribute( positionAttribute, a );
  6539. vB.fromBufferAttribute( positionAttribute, b );
  6540. vC.fromBufferAttribute( positionAttribute, c );
  6541. uvA.fromBufferAttribute( uvAttribute, a );
  6542. uvB.fromBufferAttribute( uvAttribute, b );
  6543. uvC.fromBufferAttribute( uvAttribute, c );
  6544. vB.sub( vA );
  6545. vC.sub( vA );
  6546. uvB.sub( uvA );
  6547. uvC.sub( uvA );
  6548. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6549. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6550. if ( ! isFinite( r ) ) return;
  6551. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6552. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6553. tan1[ a ].add( sdir );
  6554. tan1[ b ].add( sdir );
  6555. tan1[ c ].add( sdir );
  6556. tan2[ a ].add( tdir );
  6557. tan2[ b ].add( tdir );
  6558. tan2[ c ].add( tdir );
  6559. }
  6560. let groups = this.groups;
  6561. if ( groups.length === 0 ) {
  6562. groups = [ {
  6563. start: 0,
  6564. count: index.count
  6565. } ];
  6566. }
  6567. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6568. const group = groups[ i ];
  6569. const start = group.start;
  6570. const count = group.count;
  6571. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6572. handleTriangle(
  6573. index.getX( j + 0 ),
  6574. index.getX( j + 1 ),
  6575. index.getX( j + 2 )
  6576. );
  6577. }
  6578. }
  6579. const tmp = new Vector3(), tmp2 = new Vector3();
  6580. const n = new Vector3(), n2 = new Vector3();
  6581. function handleVertex( v ) {
  6582. n.fromBufferAttribute( normalAttribute, v );
  6583. n2.copy( n );
  6584. const t = tan1[ v ];
  6585. // Gram-Schmidt orthogonalize
  6586. tmp.copy( t );
  6587. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6588. // Calculate handedness
  6589. tmp2.crossVectors( n2, t );
  6590. const test = tmp2.dot( tan2[ v ] );
  6591. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6592. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6593. }
  6594. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6595. const group = groups[ i ];
  6596. const start = group.start;
  6597. const count = group.count;
  6598. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6599. handleVertex( index.getX( j + 0 ) );
  6600. handleVertex( index.getX( j + 1 ) );
  6601. handleVertex( index.getX( j + 2 ) );
  6602. }
  6603. }
  6604. }
  6605. computeVertexNormals() {
  6606. const index = this.index;
  6607. const positionAttribute = this.getAttribute( 'position' );
  6608. if ( positionAttribute !== undefined ) {
  6609. let normalAttribute = this.getAttribute( 'normal' );
  6610. if ( normalAttribute === undefined ) {
  6611. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6612. this.setAttribute( 'normal', normalAttribute );
  6613. } else {
  6614. // reset existing normals to zero
  6615. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6616. normalAttribute.setXYZ( i, 0, 0, 0 );
  6617. }
  6618. }
  6619. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6620. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6621. const cb = new Vector3(), ab = new Vector3();
  6622. // indexed elements
  6623. if ( index ) {
  6624. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6625. const vA = index.getX( i + 0 );
  6626. const vB = index.getX( i + 1 );
  6627. const vC = index.getX( i + 2 );
  6628. pA.fromBufferAttribute( positionAttribute, vA );
  6629. pB.fromBufferAttribute( positionAttribute, vB );
  6630. pC.fromBufferAttribute( positionAttribute, vC );
  6631. cb.subVectors( pC, pB );
  6632. ab.subVectors( pA, pB );
  6633. cb.cross( ab );
  6634. nA.fromBufferAttribute( normalAttribute, vA );
  6635. nB.fromBufferAttribute( normalAttribute, vB );
  6636. nC.fromBufferAttribute( normalAttribute, vC );
  6637. nA.add( cb );
  6638. nB.add( cb );
  6639. nC.add( cb );
  6640. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6641. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6642. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6643. }
  6644. } else {
  6645. // non-indexed elements (unconnected triangle soup)
  6646. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6647. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6648. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6649. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6650. cb.subVectors( pC, pB );
  6651. ab.subVectors( pA, pB );
  6652. cb.cross( ab );
  6653. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6654. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6655. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6656. }
  6657. }
  6658. this.normalizeNormals();
  6659. normalAttribute.needsUpdate = true;
  6660. }
  6661. }
  6662. normalizeNormals() {
  6663. const normals = this.attributes.normal;
  6664. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6665. _vector$8.fromBufferAttribute( normals, i );
  6666. _vector$8.normalize();
  6667. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6668. }
  6669. }
  6670. toNonIndexed() {
  6671. function convertBufferAttribute( attribute, indices ) {
  6672. const array = attribute.array;
  6673. const itemSize = attribute.itemSize;
  6674. const normalized = attribute.normalized;
  6675. const array2 = new array.constructor( indices.length * itemSize );
  6676. let index = 0, index2 = 0;
  6677. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6678. if ( attribute.isInterleavedBufferAttribute ) {
  6679. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6680. } else {
  6681. index = indices[ i ] * itemSize;
  6682. }
  6683. for ( let j = 0; j < itemSize; j ++ ) {
  6684. array2[ index2 ++ ] = array[ index ++ ];
  6685. }
  6686. }
  6687. return new BufferAttribute( array2, itemSize, normalized );
  6688. }
  6689. //
  6690. if ( this.index === null ) {
  6691. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6692. return this;
  6693. }
  6694. const geometry2 = new BufferGeometry();
  6695. const indices = this.index.array;
  6696. const attributes = this.attributes;
  6697. // attributes
  6698. for ( const name in attributes ) {
  6699. const attribute = attributes[ name ];
  6700. const newAttribute = convertBufferAttribute( attribute, indices );
  6701. geometry2.setAttribute( name, newAttribute );
  6702. }
  6703. // morph attributes
  6704. const morphAttributes = this.morphAttributes;
  6705. for ( const name in morphAttributes ) {
  6706. const morphArray = [];
  6707. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6708. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6709. const attribute = morphAttribute[ i ];
  6710. const newAttribute = convertBufferAttribute( attribute, indices );
  6711. morphArray.push( newAttribute );
  6712. }
  6713. geometry2.morphAttributes[ name ] = morphArray;
  6714. }
  6715. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6716. // groups
  6717. const groups = this.groups;
  6718. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6719. const group = groups[ i ];
  6720. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6721. }
  6722. return geometry2;
  6723. }
  6724. toJSON() {
  6725. const data = {
  6726. metadata: {
  6727. version: 4.6,
  6728. type: 'BufferGeometry',
  6729. generator: 'BufferGeometry.toJSON'
  6730. }
  6731. };
  6732. // standard BufferGeometry serialization
  6733. data.uuid = this.uuid;
  6734. data.type = this.type;
  6735. if ( this.name !== '' ) data.name = this.name;
  6736. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6737. if ( this.parameters !== undefined ) {
  6738. const parameters = this.parameters;
  6739. for ( const key in parameters ) {
  6740. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6741. }
  6742. return data;
  6743. }
  6744. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6745. data.data = { attributes: {} };
  6746. const index = this.index;
  6747. if ( index !== null ) {
  6748. data.data.index = {
  6749. type: index.array.constructor.name,
  6750. array: Array.prototype.slice.call( index.array )
  6751. };
  6752. }
  6753. const attributes = this.attributes;
  6754. for ( const key in attributes ) {
  6755. const attribute = attributes[ key ];
  6756. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6757. }
  6758. const morphAttributes = {};
  6759. let hasMorphAttributes = false;
  6760. for ( const key in this.morphAttributes ) {
  6761. const attributeArray = this.morphAttributes[ key ];
  6762. const array = [];
  6763. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6764. const attribute = attributeArray[ i ];
  6765. array.push( attribute.toJSON( data.data ) );
  6766. }
  6767. if ( array.length > 0 ) {
  6768. morphAttributes[ key ] = array;
  6769. hasMorphAttributes = true;
  6770. }
  6771. }
  6772. if ( hasMorphAttributes ) {
  6773. data.data.morphAttributes = morphAttributes;
  6774. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6775. }
  6776. const groups = this.groups;
  6777. if ( groups.length > 0 ) {
  6778. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6779. }
  6780. const boundingSphere = this.boundingSphere;
  6781. if ( boundingSphere !== null ) {
  6782. data.data.boundingSphere = {
  6783. center: boundingSphere.center.toArray(),
  6784. radius: boundingSphere.radius
  6785. };
  6786. }
  6787. return data;
  6788. }
  6789. clone() {
  6790. return new this.constructor().copy( this );
  6791. }
  6792. copy( source ) {
  6793. // reset
  6794. this.index = null;
  6795. this.attributes = {};
  6796. this.morphAttributes = {};
  6797. this.groups = [];
  6798. this.boundingBox = null;
  6799. this.boundingSphere = null;
  6800. // used for storing cloned, shared data
  6801. const data = {};
  6802. // name
  6803. this.name = source.name;
  6804. // index
  6805. const index = source.index;
  6806. if ( index !== null ) {
  6807. this.setIndex( index.clone( data ) );
  6808. }
  6809. // attributes
  6810. const attributes = source.attributes;
  6811. for ( const name in attributes ) {
  6812. const attribute = attributes[ name ];
  6813. this.setAttribute( name, attribute.clone( data ) );
  6814. }
  6815. // morph attributes
  6816. const morphAttributes = source.morphAttributes;
  6817. for ( const name in morphAttributes ) {
  6818. const array = [];
  6819. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6820. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6821. array.push( morphAttribute[ i ].clone( data ) );
  6822. }
  6823. this.morphAttributes[ name ] = array;
  6824. }
  6825. this.morphTargetsRelative = source.morphTargetsRelative;
  6826. // groups
  6827. const groups = source.groups;
  6828. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6829. const group = groups[ i ];
  6830. this.addGroup( group.start, group.count, group.materialIndex );
  6831. }
  6832. // bounding box
  6833. const boundingBox = source.boundingBox;
  6834. if ( boundingBox !== null ) {
  6835. this.boundingBox = boundingBox.clone();
  6836. }
  6837. // bounding sphere
  6838. const boundingSphere = source.boundingSphere;
  6839. if ( boundingSphere !== null ) {
  6840. this.boundingSphere = boundingSphere.clone();
  6841. }
  6842. // draw range
  6843. this.drawRange.start = source.drawRange.start;
  6844. this.drawRange.count = source.drawRange.count;
  6845. // user data
  6846. this.userData = source.userData;
  6847. return this;
  6848. }
  6849. dispose() {
  6850. this.dispatchEvent( { type: 'dispose' } );
  6851. }
  6852. }
  6853. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6854. const _ray$3 = /*@__PURE__*/ new Ray();
  6855. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6856. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6857. const _vA$1 = /*@__PURE__*/ new Vector3();
  6858. const _vB$1 = /*@__PURE__*/ new Vector3();
  6859. const _vC$1 = /*@__PURE__*/ new Vector3();
  6860. const _tempA = /*@__PURE__*/ new Vector3();
  6861. const _morphA = /*@__PURE__*/ new Vector3();
  6862. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6863. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6864. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6865. const _normalA = /*@__PURE__*/ new Vector3();
  6866. const _normalB = /*@__PURE__*/ new Vector3();
  6867. const _normalC = /*@__PURE__*/ new Vector3();
  6868. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6869. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6870. class Mesh extends Object3D {
  6871. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6872. super();
  6873. this.isMesh = true;
  6874. this.type = 'Mesh';
  6875. this.geometry = geometry;
  6876. this.material = material;
  6877. this.updateMorphTargets();
  6878. }
  6879. copy( source, recursive ) {
  6880. super.copy( source, recursive );
  6881. if ( source.morphTargetInfluences !== undefined ) {
  6882. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6883. }
  6884. if ( source.morphTargetDictionary !== undefined ) {
  6885. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6886. }
  6887. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6888. this.geometry = source.geometry;
  6889. return this;
  6890. }
  6891. updateMorphTargets() {
  6892. const geometry = this.geometry;
  6893. const morphAttributes = geometry.morphAttributes;
  6894. const keys = Object.keys( morphAttributes );
  6895. if ( keys.length > 0 ) {
  6896. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6897. if ( morphAttribute !== undefined ) {
  6898. this.morphTargetInfluences = [];
  6899. this.morphTargetDictionary = {};
  6900. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6901. const name = morphAttribute[ m ].name || String( m );
  6902. this.morphTargetInfluences.push( 0 );
  6903. this.morphTargetDictionary[ name ] = m;
  6904. }
  6905. }
  6906. }
  6907. }
  6908. getVertexPosition( index, target ) {
  6909. const geometry = this.geometry;
  6910. const position = geometry.attributes.position;
  6911. const morphPosition = geometry.morphAttributes.position;
  6912. const morphTargetsRelative = geometry.morphTargetsRelative;
  6913. target.fromBufferAttribute( position, index );
  6914. const morphInfluences = this.morphTargetInfluences;
  6915. if ( morphPosition && morphInfluences ) {
  6916. _morphA.set( 0, 0, 0 );
  6917. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6918. const influence = morphInfluences[ i ];
  6919. const morphAttribute = morphPosition[ i ];
  6920. if ( influence === 0 ) continue;
  6921. _tempA.fromBufferAttribute( morphAttribute, index );
  6922. if ( morphTargetsRelative ) {
  6923. _morphA.addScaledVector( _tempA, influence );
  6924. } else {
  6925. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6926. }
  6927. }
  6928. target.add( _morphA );
  6929. }
  6930. return target;
  6931. }
  6932. raycast( raycaster, intersects ) {
  6933. const geometry = this.geometry;
  6934. const material = this.material;
  6935. const matrixWorld = this.matrixWorld;
  6936. if ( material === undefined ) return;
  6937. // test with bounding sphere in world space
  6938. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6939. _sphere$6.copy( geometry.boundingSphere );
  6940. _sphere$6.applyMatrix4( matrixWorld );
  6941. // check distance from ray origin to bounding sphere
  6942. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6943. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6944. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6945. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6946. }
  6947. // convert ray to local space of mesh
  6948. _inverseMatrix$3.copy( matrixWorld ).invert();
  6949. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6950. // test with bounding box in local space
  6951. if ( geometry.boundingBox !== null ) {
  6952. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6953. }
  6954. // test for intersections with geometry
  6955. this._computeIntersections( raycaster, intersects, _ray$3 );
  6956. }
  6957. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6958. let intersection;
  6959. const geometry = this.geometry;
  6960. const material = this.material;
  6961. const index = geometry.index;
  6962. const position = geometry.attributes.position;
  6963. const uv = geometry.attributes.uv;
  6964. const uv1 = geometry.attributes.uv1;
  6965. const normal = geometry.attributes.normal;
  6966. const groups = geometry.groups;
  6967. const drawRange = geometry.drawRange;
  6968. if ( index !== null ) {
  6969. // indexed buffer geometry
  6970. if ( Array.isArray( material ) ) {
  6971. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6972. const group = groups[ i ];
  6973. const groupMaterial = material[ group.materialIndex ];
  6974. const start = Math.max( group.start, drawRange.start );
  6975. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6976. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6977. const a = index.getX( j );
  6978. const b = index.getX( j + 1 );
  6979. const c = index.getX( j + 2 );
  6980. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6981. if ( intersection ) {
  6982. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6983. intersection.face.materialIndex = group.materialIndex;
  6984. intersects.push( intersection );
  6985. }
  6986. }
  6987. }
  6988. } else {
  6989. const start = Math.max( 0, drawRange.start );
  6990. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6991. for ( let i = start, il = end; i < il; i += 3 ) {
  6992. const a = index.getX( i );
  6993. const b = index.getX( i + 1 );
  6994. const c = index.getX( i + 2 );
  6995. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6996. if ( intersection ) {
  6997. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6998. intersects.push( intersection );
  6999. }
  7000. }
  7001. }
  7002. } else if ( position !== undefined ) {
  7003. // non-indexed buffer geometry
  7004. if ( Array.isArray( material ) ) {
  7005. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7006. const group = groups[ i ];
  7007. const groupMaterial = material[ group.materialIndex ];
  7008. const start = Math.max( group.start, drawRange.start );
  7009. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7010. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7011. const a = j;
  7012. const b = j + 1;
  7013. const c = j + 2;
  7014. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7015. if ( intersection ) {
  7016. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7017. intersection.face.materialIndex = group.materialIndex;
  7018. intersects.push( intersection );
  7019. }
  7020. }
  7021. }
  7022. } else {
  7023. const start = Math.max( 0, drawRange.start );
  7024. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7025. for ( let i = start, il = end; i < il; i += 3 ) {
  7026. const a = i;
  7027. const b = i + 1;
  7028. const c = i + 2;
  7029. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7030. if ( intersection ) {
  7031. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7032. intersects.push( intersection );
  7033. }
  7034. }
  7035. }
  7036. }
  7037. }
  7038. }
  7039. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7040. let intersect;
  7041. if ( material.side === BackSide ) {
  7042. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7043. } else {
  7044. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7045. }
  7046. if ( intersect === null ) return null;
  7047. _intersectionPointWorld.copy( point );
  7048. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7049. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7050. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7051. return {
  7052. distance: distance,
  7053. point: _intersectionPointWorld.clone(),
  7054. object: object
  7055. };
  7056. }
  7057. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7058. object.getVertexPosition( a, _vA$1 );
  7059. object.getVertexPosition( b, _vB$1 );
  7060. object.getVertexPosition( c, _vC$1 );
  7061. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7062. if ( intersection ) {
  7063. if ( uv ) {
  7064. _uvA$1.fromBufferAttribute( uv, a );
  7065. _uvB$1.fromBufferAttribute( uv, b );
  7066. _uvC$1.fromBufferAttribute( uv, c );
  7067. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7068. }
  7069. if ( uv1 ) {
  7070. _uvA$1.fromBufferAttribute( uv1, a );
  7071. _uvB$1.fromBufferAttribute( uv1, b );
  7072. _uvC$1.fromBufferAttribute( uv1, c );
  7073. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7074. }
  7075. if ( normal ) {
  7076. _normalA.fromBufferAttribute( normal, a );
  7077. _normalB.fromBufferAttribute( normal, b );
  7078. _normalC.fromBufferAttribute( normal, c );
  7079. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7080. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7081. intersection.normal.multiplyScalar( - 1 );
  7082. }
  7083. }
  7084. const face = {
  7085. a: a,
  7086. b: b,
  7087. c: c,
  7088. normal: new Vector3(),
  7089. materialIndex: 0
  7090. };
  7091. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7092. intersection.face = face;
  7093. }
  7094. return intersection;
  7095. }
  7096. class BoxGeometry extends BufferGeometry {
  7097. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7098. super();
  7099. this.type = 'BoxGeometry';
  7100. this.parameters = {
  7101. width: width,
  7102. height: height,
  7103. depth: depth,
  7104. widthSegments: widthSegments,
  7105. heightSegments: heightSegments,
  7106. depthSegments: depthSegments
  7107. };
  7108. const scope = this;
  7109. // segments
  7110. widthSegments = Math.floor( widthSegments );
  7111. heightSegments = Math.floor( heightSegments );
  7112. depthSegments = Math.floor( depthSegments );
  7113. // buffers
  7114. const indices = [];
  7115. const vertices = [];
  7116. const normals = [];
  7117. const uvs = [];
  7118. // helper variables
  7119. let numberOfVertices = 0;
  7120. let groupStart = 0;
  7121. // build each side of the box geometry
  7122. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7123. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7124. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7125. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7126. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7127. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7128. // build geometry
  7129. this.setIndex( indices );
  7130. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7131. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7132. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7133. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7134. const segmentWidth = width / gridX;
  7135. const segmentHeight = height / gridY;
  7136. const widthHalf = width / 2;
  7137. const heightHalf = height / 2;
  7138. const depthHalf = depth / 2;
  7139. const gridX1 = gridX + 1;
  7140. const gridY1 = gridY + 1;
  7141. let vertexCounter = 0;
  7142. let groupCount = 0;
  7143. const vector = new Vector3();
  7144. // generate vertices, normals and uvs
  7145. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7146. const y = iy * segmentHeight - heightHalf;
  7147. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7148. const x = ix * segmentWidth - widthHalf;
  7149. // set values to correct vector component
  7150. vector[ u ] = x * udir;
  7151. vector[ v ] = y * vdir;
  7152. vector[ w ] = depthHalf;
  7153. // now apply vector to vertex buffer
  7154. vertices.push( vector.x, vector.y, vector.z );
  7155. // set values to correct vector component
  7156. vector[ u ] = 0;
  7157. vector[ v ] = 0;
  7158. vector[ w ] = depth > 0 ? 1 : - 1;
  7159. // now apply vector to normal buffer
  7160. normals.push( vector.x, vector.y, vector.z );
  7161. // uvs
  7162. uvs.push( ix / gridX );
  7163. uvs.push( 1 - ( iy / gridY ) );
  7164. // counters
  7165. vertexCounter += 1;
  7166. }
  7167. }
  7168. // indices
  7169. // 1. you need three indices to draw a single face
  7170. // 2. a single segment consists of two faces
  7171. // 3. so we need to generate six (2*3) indices per segment
  7172. for ( let iy = 0; iy < gridY; iy ++ ) {
  7173. for ( let ix = 0; ix < gridX; ix ++ ) {
  7174. const a = numberOfVertices + ix + gridX1 * iy;
  7175. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7176. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7177. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7178. // faces
  7179. indices.push( a, b, d );
  7180. indices.push( b, c, d );
  7181. // increase counter
  7182. groupCount += 6;
  7183. }
  7184. }
  7185. // add a group to the geometry. this will ensure multi material support
  7186. scope.addGroup( groupStart, groupCount, materialIndex );
  7187. // calculate new start value for groups
  7188. groupStart += groupCount;
  7189. // update total number of vertices
  7190. numberOfVertices += vertexCounter;
  7191. }
  7192. }
  7193. copy( source ) {
  7194. super.copy( source );
  7195. this.parameters = Object.assign( {}, source.parameters );
  7196. return this;
  7197. }
  7198. static fromJSON( data ) {
  7199. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7200. }
  7201. }
  7202. /**
  7203. * Uniform Utilities
  7204. */
  7205. function cloneUniforms( src ) {
  7206. const dst = {};
  7207. for ( const u in src ) {
  7208. dst[ u ] = {};
  7209. for ( const p in src[ u ] ) {
  7210. const property = src[ u ][ p ];
  7211. if ( property && ( property.isColor ||
  7212. property.isMatrix3 || property.isMatrix4 ||
  7213. property.isVector2 || property.isVector3 || property.isVector4 ||
  7214. property.isTexture || property.isQuaternion ) ) {
  7215. if ( property.isRenderTargetTexture ) {
  7216. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7217. dst[ u ][ p ] = null;
  7218. } else {
  7219. dst[ u ][ p ] = property.clone();
  7220. }
  7221. } else if ( Array.isArray( property ) ) {
  7222. dst[ u ][ p ] = property.slice();
  7223. } else {
  7224. dst[ u ][ p ] = property;
  7225. }
  7226. }
  7227. }
  7228. return dst;
  7229. }
  7230. function cloneUniformsGroups( src ) {
  7231. const dst = [];
  7232. for ( let u = 0; u < src.length; u ++ ) {
  7233. dst.push( src[ u ].clone() );
  7234. }
  7235. return dst;
  7236. }
  7237. var default_vertex = /* glsl */`
  7238. void main() {
  7239. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7240. }
  7241. `;
  7242. var default_fragment = /* glsl */`
  7243. void main() {
  7244. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7245. }
  7246. `;
  7247. class ShaderMaterial extends Material {
  7248. constructor( parameters ) {
  7249. super();
  7250. this.isShaderMaterial = true;
  7251. this.type = 'ShaderMaterial';
  7252. this.defines = {};
  7253. this.uniforms = {};
  7254. this.uniformsGroups = [];
  7255. this.vertexShader = default_vertex;
  7256. this.fragmentShader = default_fragment;
  7257. this.linewidth = 1;
  7258. this.wireframe = false;
  7259. this.wireframeLinewidth = 1;
  7260. this.fog = false; // set to use scene fog
  7261. this.lights = false; // set to use scene lights
  7262. this.clipping = false; // set to use user-defined clipping planes
  7263. this.forceSinglePass = true;
  7264. this.extensions = {
  7265. clipCullDistance: false, // set to use vertex shader clipping
  7266. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7267. };
  7268. // When rendered geometry doesn't include these attributes but the material does,
  7269. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7270. this.defaultAttributeValues = {
  7271. 'color': [ 1, 1, 1 ],
  7272. 'uv': [ 0, 0 ],
  7273. 'uv1': [ 0, 0 ]
  7274. };
  7275. this.index0AttributeName = undefined;
  7276. this.uniformsNeedUpdate = false;
  7277. this.glslVersion = null;
  7278. if ( parameters !== undefined ) {
  7279. this.setValues( parameters );
  7280. }
  7281. }
  7282. copy( source ) {
  7283. super.copy( source );
  7284. this.fragmentShader = source.fragmentShader;
  7285. this.vertexShader = source.vertexShader;
  7286. this.uniforms = cloneUniforms( source.uniforms );
  7287. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7288. this.defines = Object.assign( {}, source.defines );
  7289. this.wireframe = source.wireframe;
  7290. this.wireframeLinewidth = source.wireframeLinewidth;
  7291. this.fog = source.fog;
  7292. this.lights = source.lights;
  7293. this.clipping = source.clipping;
  7294. this.extensions = Object.assign( {}, source.extensions );
  7295. this.glslVersion = source.glslVersion;
  7296. return this;
  7297. }
  7298. toJSON( meta ) {
  7299. const data = super.toJSON( meta );
  7300. data.glslVersion = this.glslVersion;
  7301. data.uniforms = {};
  7302. for ( const name in this.uniforms ) {
  7303. const uniform = this.uniforms[ name ];
  7304. const value = uniform.value;
  7305. if ( value && value.isTexture ) {
  7306. data.uniforms[ name ] = {
  7307. type: 't',
  7308. value: value.toJSON( meta ).uuid
  7309. };
  7310. } else if ( value && value.isColor ) {
  7311. data.uniforms[ name ] = {
  7312. type: 'c',
  7313. value: value.getHex()
  7314. };
  7315. } else if ( value && value.isVector2 ) {
  7316. data.uniforms[ name ] = {
  7317. type: 'v2',
  7318. value: value.toArray()
  7319. };
  7320. } else if ( value && value.isVector3 ) {
  7321. data.uniforms[ name ] = {
  7322. type: 'v3',
  7323. value: value.toArray()
  7324. };
  7325. } else if ( value && value.isVector4 ) {
  7326. data.uniforms[ name ] = {
  7327. type: 'v4',
  7328. value: value.toArray()
  7329. };
  7330. } else if ( value && value.isMatrix3 ) {
  7331. data.uniforms[ name ] = {
  7332. type: 'm3',
  7333. value: value.toArray()
  7334. };
  7335. } else if ( value && value.isMatrix4 ) {
  7336. data.uniforms[ name ] = {
  7337. type: 'm4',
  7338. value: value.toArray()
  7339. };
  7340. } else {
  7341. data.uniforms[ name ] = {
  7342. value: value
  7343. };
  7344. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7345. }
  7346. }
  7347. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7348. data.vertexShader = this.vertexShader;
  7349. data.fragmentShader = this.fragmentShader;
  7350. data.lights = this.lights;
  7351. data.clipping = this.clipping;
  7352. const extensions = {};
  7353. for ( const key in this.extensions ) {
  7354. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7355. }
  7356. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7357. return data;
  7358. }
  7359. }
  7360. class Camera extends Object3D {
  7361. constructor() {
  7362. super();
  7363. this.isCamera = true;
  7364. this.type = 'Camera';
  7365. this.matrixWorldInverse = new Matrix4();
  7366. this.projectionMatrix = new Matrix4();
  7367. this.projectionMatrixInverse = new Matrix4();
  7368. this.coordinateSystem = WebGLCoordinateSystem;
  7369. }
  7370. copy( source, recursive ) {
  7371. super.copy( source, recursive );
  7372. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7373. this.projectionMatrix.copy( source.projectionMatrix );
  7374. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7375. this.coordinateSystem = source.coordinateSystem;
  7376. return this;
  7377. }
  7378. getWorldDirection( target ) {
  7379. return super.getWorldDirection( target ).negate();
  7380. }
  7381. updateMatrixWorld( force ) {
  7382. super.updateMatrixWorld( force );
  7383. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7384. }
  7385. updateWorldMatrix( updateParents, updateChildren ) {
  7386. super.updateWorldMatrix( updateParents, updateChildren );
  7387. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7388. }
  7389. clone() {
  7390. return new this.constructor().copy( this );
  7391. }
  7392. }
  7393. const _v3$1 = /*@__PURE__*/ new Vector3();
  7394. const _minTarget = /*@__PURE__*/ new Vector2();
  7395. const _maxTarget = /*@__PURE__*/ new Vector2();
  7396. class PerspectiveCamera extends Camera {
  7397. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7398. super();
  7399. this.isPerspectiveCamera = true;
  7400. this.type = 'PerspectiveCamera';
  7401. this.fov = fov;
  7402. this.zoom = 1;
  7403. this.near = near;
  7404. this.far = far;
  7405. this.focus = 10;
  7406. this.aspect = aspect;
  7407. this.view = null;
  7408. this.filmGauge = 35; // width of the film (default in millimeters)
  7409. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7410. this.updateProjectionMatrix();
  7411. }
  7412. copy( source, recursive ) {
  7413. super.copy( source, recursive );
  7414. this.fov = source.fov;
  7415. this.zoom = source.zoom;
  7416. this.near = source.near;
  7417. this.far = source.far;
  7418. this.focus = source.focus;
  7419. this.aspect = source.aspect;
  7420. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7421. this.filmGauge = source.filmGauge;
  7422. this.filmOffset = source.filmOffset;
  7423. return this;
  7424. }
  7425. /**
  7426. * Sets the FOV by focal length in respect to the current .filmGauge.
  7427. *
  7428. * The default film gauge is 35, so that the focal length can be specified for
  7429. * a 35mm (full frame) camera.
  7430. *
  7431. * Values for focal length and film gauge must have the same unit.
  7432. */
  7433. setFocalLength( focalLength ) {
  7434. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7435. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7436. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7437. this.updateProjectionMatrix();
  7438. }
  7439. /**
  7440. * Calculates the focal length from the current .fov and .filmGauge.
  7441. */
  7442. getFocalLength() {
  7443. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7444. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7445. }
  7446. getEffectiveFOV() {
  7447. return RAD2DEG * 2 * Math.atan(
  7448. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7449. }
  7450. getFilmWidth() {
  7451. // film not completely covered in portrait format (aspect < 1)
  7452. return this.filmGauge * Math.min( this.aspect, 1 );
  7453. }
  7454. getFilmHeight() {
  7455. // film not completely covered in landscape format (aspect > 1)
  7456. return this.filmGauge / Math.max( this.aspect, 1 );
  7457. }
  7458. /**
  7459. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7460. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7461. */
  7462. getViewBounds( distance, minTarget, maxTarget ) {
  7463. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7464. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7465. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7466. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7467. }
  7468. /**
  7469. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7470. * Copies the result into the target Vector2, where x is width and y is height.
  7471. */
  7472. getViewSize( distance, target ) {
  7473. this.getViewBounds( distance, _minTarget, _maxTarget );
  7474. return target.subVectors( _maxTarget, _minTarget );
  7475. }
  7476. /**
  7477. * Sets an offset in a larger frustum. This is useful for multi-window or
  7478. * multi-monitor/multi-machine setups.
  7479. *
  7480. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7481. * the monitors are in grid like this
  7482. *
  7483. * +---+---+---+
  7484. * | A | B | C |
  7485. * +---+---+---+
  7486. * | D | E | F |
  7487. * +---+---+---+
  7488. *
  7489. * then for each monitor you would call it like this
  7490. *
  7491. * const w = 1920;
  7492. * const h = 1080;
  7493. * const fullWidth = w * 3;
  7494. * const fullHeight = h * 2;
  7495. *
  7496. * --A--
  7497. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7498. * --B--
  7499. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7500. * --C--
  7501. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7502. * --D--
  7503. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7504. * --E--
  7505. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7506. * --F--
  7507. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7508. *
  7509. * Note there is no reason monitors have to be the same size or in a grid.
  7510. */
  7511. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7512. this.aspect = fullWidth / fullHeight;
  7513. if ( this.view === null ) {
  7514. this.view = {
  7515. enabled: true,
  7516. fullWidth: 1,
  7517. fullHeight: 1,
  7518. offsetX: 0,
  7519. offsetY: 0,
  7520. width: 1,
  7521. height: 1
  7522. };
  7523. }
  7524. this.view.enabled = true;
  7525. this.view.fullWidth = fullWidth;
  7526. this.view.fullHeight = fullHeight;
  7527. this.view.offsetX = x;
  7528. this.view.offsetY = y;
  7529. this.view.width = width;
  7530. this.view.height = height;
  7531. this.updateProjectionMatrix();
  7532. }
  7533. clearViewOffset() {
  7534. if ( this.view !== null ) {
  7535. this.view.enabled = false;
  7536. }
  7537. this.updateProjectionMatrix();
  7538. }
  7539. updateProjectionMatrix() {
  7540. const near = this.near;
  7541. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7542. let height = 2 * top;
  7543. let width = this.aspect * height;
  7544. let left = - 0.5 * width;
  7545. const view = this.view;
  7546. if ( this.view !== null && this.view.enabled ) {
  7547. const fullWidth = view.fullWidth,
  7548. fullHeight = view.fullHeight;
  7549. left += view.offsetX * width / fullWidth;
  7550. top -= view.offsetY * height / fullHeight;
  7551. width *= view.width / fullWidth;
  7552. height *= view.height / fullHeight;
  7553. }
  7554. const skew = this.filmOffset;
  7555. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7556. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7557. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7558. }
  7559. toJSON( meta ) {
  7560. const data = super.toJSON( meta );
  7561. data.object.fov = this.fov;
  7562. data.object.zoom = this.zoom;
  7563. data.object.near = this.near;
  7564. data.object.far = this.far;
  7565. data.object.focus = this.focus;
  7566. data.object.aspect = this.aspect;
  7567. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7568. data.object.filmGauge = this.filmGauge;
  7569. data.object.filmOffset = this.filmOffset;
  7570. return data;
  7571. }
  7572. }
  7573. const fov = - 90; // negative fov is not an error
  7574. const aspect = 1;
  7575. class CubeCamera extends Object3D {
  7576. constructor( near, far, renderTarget ) {
  7577. super();
  7578. this.type = 'CubeCamera';
  7579. this.renderTarget = renderTarget;
  7580. this.coordinateSystem = null;
  7581. this.activeMipmapLevel = 0;
  7582. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7583. cameraPX.layers = this.layers;
  7584. this.add( cameraPX );
  7585. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7586. cameraNX.layers = this.layers;
  7587. this.add( cameraNX );
  7588. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7589. cameraPY.layers = this.layers;
  7590. this.add( cameraPY );
  7591. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7592. cameraNY.layers = this.layers;
  7593. this.add( cameraNY );
  7594. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7595. cameraPZ.layers = this.layers;
  7596. this.add( cameraPZ );
  7597. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7598. cameraNZ.layers = this.layers;
  7599. this.add( cameraNZ );
  7600. }
  7601. updateCoordinateSystem() {
  7602. const coordinateSystem = this.coordinateSystem;
  7603. const cameras = this.children.concat();
  7604. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7605. for ( const camera of cameras ) this.remove( camera );
  7606. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7607. cameraPX.up.set( 0, 1, 0 );
  7608. cameraPX.lookAt( 1, 0, 0 );
  7609. cameraNX.up.set( 0, 1, 0 );
  7610. cameraNX.lookAt( - 1, 0, 0 );
  7611. cameraPY.up.set( 0, 0, - 1 );
  7612. cameraPY.lookAt( 0, 1, 0 );
  7613. cameraNY.up.set( 0, 0, 1 );
  7614. cameraNY.lookAt( 0, - 1, 0 );
  7615. cameraPZ.up.set( 0, 1, 0 );
  7616. cameraPZ.lookAt( 0, 0, 1 );
  7617. cameraNZ.up.set( 0, 1, 0 );
  7618. cameraNZ.lookAt( 0, 0, - 1 );
  7619. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7620. cameraPX.up.set( 0, - 1, 0 );
  7621. cameraPX.lookAt( - 1, 0, 0 );
  7622. cameraNX.up.set( 0, - 1, 0 );
  7623. cameraNX.lookAt( 1, 0, 0 );
  7624. cameraPY.up.set( 0, 0, 1 );
  7625. cameraPY.lookAt( 0, 1, 0 );
  7626. cameraNY.up.set( 0, 0, - 1 );
  7627. cameraNY.lookAt( 0, - 1, 0 );
  7628. cameraPZ.up.set( 0, - 1, 0 );
  7629. cameraPZ.lookAt( 0, 0, 1 );
  7630. cameraNZ.up.set( 0, - 1, 0 );
  7631. cameraNZ.lookAt( 0, 0, - 1 );
  7632. } else {
  7633. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7634. }
  7635. for ( const camera of cameras ) {
  7636. this.add( camera );
  7637. camera.updateMatrixWorld();
  7638. }
  7639. }
  7640. update( renderer, scene ) {
  7641. if ( this.parent === null ) this.updateMatrixWorld();
  7642. const { renderTarget, activeMipmapLevel } = this;
  7643. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7644. this.coordinateSystem = renderer.coordinateSystem;
  7645. this.updateCoordinateSystem();
  7646. }
  7647. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7648. const currentRenderTarget = renderer.getRenderTarget();
  7649. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7650. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7651. const currentXrEnabled = renderer.xr.enabled;
  7652. renderer.xr.enabled = false;
  7653. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7654. renderTarget.texture.generateMipmaps = false;
  7655. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7656. renderer.render( scene, cameraPX );
  7657. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7658. renderer.render( scene, cameraNX );
  7659. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7660. renderer.render( scene, cameraPY );
  7661. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7662. renderer.render( scene, cameraNY );
  7663. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7664. renderer.render( scene, cameraPZ );
  7665. // mipmaps are generated during the last call of render()
  7666. // at this point, all sides of the cube render target are defined
  7667. renderTarget.texture.generateMipmaps = generateMipmaps;
  7668. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7669. renderer.render( scene, cameraNZ );
  7670. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7671. renderer.xr.enabled = currentXrEnabled;
  7672. renderTarget.texture.needsPMREMUpdate = true;
  7673. }
  7674. }
  7675. class CubeTexture extends Texture {
  7676. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7677. images = images !== undefined ? images : [];
  7678. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7679. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7680. this.isCubeTexture = true;
  7681. this.flipY = false;
  7682. }
  7683. get images() {
  7684. return this.image;
  7685. }
  7686. set images( value ) {
  7687. this.image = value;
  7688. }
  7689. }
  7690. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7691. constructor( size = 1, options = {} ) {
  7692. super( size, size, options );
  7693. this.isWebGLCubeRenderTarget = true;
  7694. const image = { width: size, height: size, depth: 1 };
  7695. const images = [ image, image, image, image, image, image ];
  7696. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7697. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7698. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7699. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7700. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7701. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7702. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7703. this.texture.isRenderTargetTexture = true;
  7704. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7705. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7706. }
  7707. fromEquirectangularTexture( renderer, texture ) {
  7708. this.texture.type = texture.type;
  7709. this.texture.colorSpace = texture.colorSpace;
  7710. this.texture.generateMipmaps = texture.generateMipmaps;
  7711. this.texture.minFilter = texture.minFilter;
  7712. this.texture.magFilter = texture.magFilter;
  7713. const shader = {
  7714. uniforms: {
  7715. tEquirect: { value: null },
  7716. },
  7717. vertexShader: /* glsl */`
  7718. varying vec3 vWorldDirection;
  7719. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7720. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7721. }
  7722. void main() {
  7723. vWorldDirection = transformDirection( position, modelMatrix );
  7724. #include <begin_vertex>
  7725. #include <project_vertex>
  7726. }
  7727. `,
  7728. fragmentShader: /* glsl */`
  7729. uniform sampler2D tEquirect;
  7730. varying vec3 vWorldDirection;
  7731. #include <common>
  7732. void main() {
  7733. vec3 direction = normalize( vWorldDirection );
  7734. vec2 sampleUV = equirectUv( direction );
  7735. gl_FragColor = texture2D( tEquirect, sampleUV );
  7736. }
  7737. `
  7738. };
  7739. const geometry = new BoxGeometry( 5, 5, 5 );
  7740. const material = new ShaderMaterial( {
  7741. name: 'CubemapFromEquirect',
  7742. uniforms: cloneUniforms( shader.uniforms ),
  7743. vertexShader: shader.vertexShader,
  7744. fragmentShader: shader.fragmentShader,
  7745. side: BackSide,
  7746. blending: NoBlending
  7747. } );
  7748. material.uniforms.tEquirect.value = texture;
  7749. const mesh = new Mesh( geometry, material );
  7750. const currentMinFilter = texture.minFilter;
  7751. // Avoid blurred poles
  7752. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7753. const camera = new CubeCamera( 1, 10, this );
  7754. camera.update( renderer, mesh );
  7755. texture.minFilter = currentMinFilter;
  7756. mesh.geometry.dispose();
  7757. mesh.material.dispose();
  7758. return this;
  7759. }
  7760. clear( renderer, color, depth, stencil ) {
  7761. const currentRenderTarget = renderer.getRenderTarget();
  7762. for ( let i = 0; i < 6; i ++ ) {
  7763. renderer.setRenderTarget( this, i );
  7764. renderer.clear( color, depth, stencil );
  7765. }
  7766. renderer.setRenderTarget( currentRenderTarget );
  7767. }
  7768. }
  7769. class FogExp2 {
  7770. constructor( color, density = 0.00025 ) {
  7771. this.isFogExp2 = true;
  7772. this.name = '';
  7773. this.color = new Color( color );
  7774. this.density = density;
  7775. }
  7776. clone() {
  7777. return new FogExp2( this.color, this.density );
  7778. }
  7779. toJSON( /* meta */ ) {
  7780. return {
  7781. type: 'FogExp2',
  7782. name: this.name,
  7783. color: this.color.getHex(),
  7784. density: this.density
  7785. };
  7786. }
  7787. }
  7788. class Fog {
  7789. constructor( color, near = 1, far = 1000 ) {
  7790. this.isFog = true;
  7791. this.name = '';
  7792. this.color = new Color( color );
  7793. this.near = near;
  7794. this.far = far;
  7795. }
  7796. clone() {
  7797. return new Fog( this.color, this.near, this.far );
  7798. }
  7799. toJSON( /* meta */ ) {
  7800. return {
  7801. type: 'Fog',
  7802. name: this.name,
  7803. color: this.color.getHex(),
  7804. near: this.near,
  7805. far: this.far
  7806. };
  7807. }
  7808. }
  7809. class Scene extends Object3D {
  7810. constructor() {
  7811. super();
  7812. this.isScene = true;
  7813. this.type = 'Scene';
  7814. this.background = null;
  7815. this.environment = null;
  7816. this.fog = null;
  7817. this.backgroundBlurriness = 0;
  7818. this.backgroundIntensity = 1;
  7819. this.backgroundRotation = new Euler();
  7820. this.environmentIntensity = 1;
  7821. this.environmentRotation = new Euler();
  7822. this.overrideMaterial = null;
  7823. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7824. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7825. }
  7826. }
  7827. copy( source, recursive ) {
  7828. super.copy( source, recursive );
  7829. if ( source.background !== null ) this.background = source.background.clone();
  7830. if ( source.environment !== null ) this.environment = source.environment.clone();
  7831. if ( source.fog !== null ) this.fog = source.fog.clone();
  7832. this.backgroundBlurriness = source.backgroundBlurriness;
  7833. this.backgroundIntensity = source.backgroundIntensity;
  7834. this.backgroundRotation.copy( source.backgroundRotation );
  7835. this.environmentIntensity = source.environmentIntensity;
  7836. this.environmentRotation.copy( source.environmentRotation );
  7837. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7838. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7839. return this;
  7840. }
  7841. toJSON( meta ) {
  7842. const data = super.toJSON( meta );
  7843. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7844. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7845. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7846. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7847. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7848. data.object.environmentRotation = this.environmentRotation.toArray();
  7849. return data;
  7850. }
  7851. }
  7852. class InterleavedBuffer {
  7853. constructor( array, stride ) {
  7854. this.isInterleavedBuffer = true;
  7855. this.array = array;
  7856. this.stride = stride;
  7857. this.count = array !== undefined ? array.length / stride : 0;
  7858. this.usage = StaticDrawUsage;
  7859. this._updateRange = { offset: 0, count: - 1 };
  7860. this.updateRanges = [];
  7861. this.version = 0;
  7862. this.uuid = generateUUID();
  7863. }
  7864. onUploadCallback() {}
  7865. set needsUpdate( value ) {
  7866. if ( value === true ) this.version ++;
  7867. }
  7868. get updateRange() {
  7869. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  7870. return this._updateRange;
  7871. }
  7872. setUsage( value ) {
  7873. this.usage = value;
  7874. return this;
  7875. }
  7876. addUpdateRange( start, count ) {
  7877. this.updateRanges.push( { start, count } );
  7878. }
  7879. clearUpdateRanges() {
  7880. this.updateRanges.length = 0;
  7881. }
  7882. copy( source ) {
  7883. this.array = new source.array.constructor( source.array );
  7884. this.count = source.count;
  7885. this.stride = source.stride;
  7886. this.usage = source.usage;
  7887. return this;
  7888. }
  7889. copyAt( index1, attribute, index2 ) {
  7890. index1 *= this.stride;
  7891. index2 *= attribute.stride;
  7892. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7893. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7894. }
  7895. return this;
  7896. }
  7897. set( value, offset = 0 ) {
  7898. this.array.set( value, offset );
  7899. return this;
  7900. }
  7901. clone( data ) {
  7902. if ( data.arrayBuffers === undefined ) {
  7903. data.arrayBuffers = {};
  7904. }
  7905. if ( this.array.buffer._uuid === undefined ) {
  7906. this.array.buffer._uuid = generateUUID();
  7907. }
  7908. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7909. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7910. }
  7911. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7912. const ib = new this.constructor( array, this.stride );
  7913. ib.setUsage( this.usage );
  7914. return ib;
  7915. }
  7916. onUpload( callback ) {
  7917. this.onUploadCallback = callback;
  7918. return this;
  7919. }
  7920. toJSON( data ) {
  7921. if ( data.arrayBuffers === undefined ) {
  7922. data.arrayBuffers = {};
  7923. }
  7924. // generate UUID for array buffer if necessary
  7925. if ( this.array.buffer._uuid === undefined ) {
  7926. this.array.buffer._uuid = generateUUID();
  7927. }
  7928. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7929. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7930. }
  7931. //
  7932. return {
  7933. uuid: this.uuid,
  7934. buffer: this.array.buffer._uuid,
  7935. type: this.array.constructor.name,
  7936. stride: this.stride
  7937. };
  7938. }
  7939. }
  7940. const _vector$7 = /*@__PURE__*/ new Vector3();
  7941. class InterleavedBufferAttribute {
  7942. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7943. this.isInterleavedBufferAttribute = true;
  7944. this.name = '';
  7945. this.data = interleavedBuffer;
  7946. this.itemSize = itemSize;
  7947. this.offset = offset;
  7948. this.normalized = normalized;
  7949. }
  7950. get count() {
  7951. return this.data.count;
  7952. }
  7953. get array() {
  7954. return this.data.array;
  7955. }
  7956. set needsUpdate( value ) {
  7957. this.data.needsUpdate = value;
  7958. }
  7959. applyMatrix4( m ) {
  7960. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7961. _vector$7.fromBufferAttribute( this, i );
  7962. _vector$7.applyMatrix4( m );
  7963. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7964. }
  7965. return this;
  7966. }
  7967. applyNormalMatrix( m ) {
  7968. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7969. _vector$7.fromBufferAttribute( this, i );
  7970. _vector$7.applyNormalMatrix( m );
  7971. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7972. }
  7973. return this;
  7974. }
  7975. transformDirection( m ) {
  7976. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7977. _vector$7.fromBufferAttribute( this, i );
  7978. _vector$7.transformDirection( m );
  7979. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7980. }
  7981. return this;
  7982. }
  7983. getComponent( index, component ) {
  7984. let value = this.array[ index * this.data.stride + this.offset + component ];
  7985. if ( this.normalized ) value = denormalize( value, this.array );
  7986. return value;
  7987. }
  7988. setComponent( index, component, value ) {
  7989. if ( this.normalized ) value = normalize$1( value, this.array );
  7990. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  7991. return this;
  7992. }
  7993. setX( index, x ) {
  7994. if ( this.normalized ) x = normalize$1( x, this.array );
  7995. this.data.array[ index * this.data.stride + this.offset ] = x;
  7996. return this;
  7997. }
  7998. setY( index, y ) {
  7999. if ( this.normalized ) y = normalize$1( y, this.array );
  8000. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8001. return this;
  8002. }
  8003. setZ( index, z ) {
  8004. if ( this.normalized ) z = normalize$1( z, this.array );
  8005. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8006. return this;
  8007. }
  8008. setW( index, w ) {
  8009. if ( this.normalized ) w = normalize$1( w, this.array );
  8010. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8011. return this;
  8012. }
  8013. getX( index ) {
  8014. let x = this.data.array[ index * this.data.stride + this.offset ];
  8015. if ( this.normalized ) x = denormalize( x, this.array );
  8016. return x;
  8017. }
  8018. getY( index ) {
  8019. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8020. if ( this.normalized ) y = denormalize( y, this.array );
  8021. return y;
  8022. }
  8023. getZ( index ) {
  8024. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8025. if ( this.normalized ) z = denormalize( z, this.array );
  8026. return z;
  8027. }
  8028. getW( index ) {
  8029. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8030. if ( this.normalized ) w = denormalize( w, this.array );
  8031. return w;
  8032. }
  8033. setXY( index, x, y ) {
  8034. index = index * this.data.stride + this.offset;
  8035. if ( this.normalized ) {
  8036. x = normalize$1( x, this.array );
  8037. y = normalize$1( y, this.array );
  8038. }
  8039. this.data.array[ index + 0 ] = x;
  8040. this.data.array[ index + 1 ] = y;
  8041. return this;
  8042. }
  8043. setXYZ( index, x, y, z ) {
  8044. index = index * this.data.stride + this.offset;
  8045. if ( this.normalized ) {
  8046. x = normalize$1( x, this.array );
  8047. y = normalize$1( y, this.array );
  8048. z = normalize$1( z, this.array );
  8049. }
  8050. this.data.array[ index + 0 ] = x;
  8051. this.data.array[ index + 1 ] = y;
  8052. this.data.array[ index + 2 ] = z;
  8053. return this;
  8054. }
  8055. setXYZW( index, x, y, z, w ) {
  8056. index = index * this.data.stride + this.offset;
  8057. if ( this.normalized ) {
  8058. x = normalize$1( x, this.array );
  8059. y = normalize$1( y, this.array );
  8060. z = normalize$1( z, this.array );
  8061. w = normalize$1( w, this.array );
  8062. }
  8063. this.data.array[ index + 0 ] = x;
  8064. this.data.array[ index + 1 ] = y;
  8065. this.data.array[ index + 2 ] = z;
  8066. this.data.array[ index + 3 ] = w;
  8067. return this;
  8068. }
  8069. clone( data ) {
  8070. if ( data === undefined ) {
  8071. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8072. const array = [];
  8073. for ( let i = 0; i < this.count; i ++ ) {
  8074. const index = i * this.data.stride + this.offset;
  8075. for ( let j = 0; j < this.itemSize; j ++ ) {
  8076. array.push( this.data.array[ index + j ] );
  8077. }
  8078. }
  8079. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8080. } else {
  8081. if ( data.interleavedBuffers === undefined ) {
  8082. data.interleavedBuffers = {};
  8083. }
  8084. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8085. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8086. }
  8087. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8088. }
  8089. }
  8090. toJSON( data ) {
  8091. if ( data === undefined ) {
  8092. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8093. const array = [];
  8094. for ( let i = 0; i < this.count; i ++ ) {
  8095. const index = i * this.data.stride + this.offset;
  8096. for ( let j = 0; j < this.itemSize; j ++ ) {
  8097. array.push( this.data.array[ index + j ] );
  8098. }
  8099. }
  8100. // de-interleave data and save it as an ordinary buffer attribute for now
  8101. return {
  8102. itemSize: this.itemSize,
  8103. type: this.array.constructor.name,
  8104. array: array,
  8105. normalized: this.normalized
  8106. };
  8107. } else {
  8108. // save as true interleaved attribute
  8109. if ( data.interleavedBuffers === undefined ) {
  8110. data.interleavedBuffers = {};
  8111. }
  8112. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8113. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8114. }
  8115. return {
  8116. isInterleavedBufferAttribute: true,
  8117. itemSize: this.itemSize,
  8118. data: this.data.uuid,
  8119. offset: this.offset,
  8120. normalized: this.normalized
  8121. };
  8122. }
  8123. }
  8124. }
  8125. class SpriteMaterial extends Material {
  8126. constructor( parameters ) {
  8127. super();
  8128. this.isSpriteMaterial = true;
  8129. this.type = 'SpriteMaterial';
  8130. this.color = new Color( 0xffffff );
  8131. this.map = null;
  8132. this.alphaMap = null;
  8133. this.rotation = 0;
  8134. this.sizeAttenuation = true;
  8135. this.transparent = true;
  8136. this.fog = true;
  8137. this.setValues( parameters );
  8138. }
  8139. copy( source ) {
  8140. super.copy( source );
  8141. this.color.copy( source.color );
  8142. this.map = source.map;
  8143. this.alphaMap = source.alphaMap;
  8144. this.rotation = source.rotation;
  8145. this.sizeAttenuation = source.sizeAttenuation;
  8146. this.fog = source.fog;
  8147. return this;
  8148. }
  8149. }
  8150. let _geometry$1;
  8151. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8152. const _worldScale = /*@__PURE__*/ new Vector3();
  8153. const _mvPosition = /*@__PURE__*/ new Vector3();
  8154. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8155. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8156. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8157. const _vA = /*@__PURE__*/ new Vector3();
  8158. const _vB = /*@__PURE__*/ new Vector3();
  8159. const _vC = /*@__PURE__*/ new Vector3();
  8160. const _uvA = /*@__PURE__*/ new Vector2();
  8161. const _uvB = /*@__PURE__*/ new Vector2();
  8162. const _uvC = /*@__PURE__*/ new Vector2();
  8163. class Sprite extends Object3D {
  8164. constructor( material = new SpriteMaterial() ) {
  8165. super();
  8166. this.isSprite = true;
  8167. this.type = 'Sprite';
  8168. if ( _geometry$1 === undefined ) {
  8169. _geometry$1 = new BufferGeometry();
  8170. const float32Array = new Float32Array( [
  8171. - 0.5, - 0.5, 0, 0, 0,
  8172. 0.5, - 0.5, 0, 1, 0,
  8173. 0.5, 0.5, 0, 1, 1,
  8174. - 0.5, 0.5, 0, 0, 1
  8175. ] );
  8176. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8177. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8178. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8179. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8180. }
  8181. this.geometry = _geometry$1;
  8182. this.material = material;
  8183. this.center = new Vector2( 0.5, 0.5 );
  8184. }
  8185. raycast( raycaster, intersects ) {
  8186. if ( raycaster.camera === null ) {
  8187. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8188. }
  8189. _worldScale.setFromMatrixScale( this.matrixWorld );
  8190. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8191. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8192. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8193. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8194. _worldScale.multiplyScalar( - _mvPosition.z );
  8195. }
  8196. const rotation = this.material.rotation;
  8197. let sin, cos;
  8198. if ( rotation !== 0 ) {
  8199. cos = Math.cos( rotation );
  8200. sin = Math.sin( rotation );
  8201. }
  8202. const center = this.center;
  8203. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8204. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8205. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8206. _uvA.set( 0, 0 );
  8207. _uvB.set( 1, 0 );
  8208. _uvC.set( 1, 1 );
  8209. // check first triangle
  8210. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8211. if ( intersect === null ) {
  8212. // check second triangle
  8213. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8214. _uvB.set( 0, 1 );
  8215. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8216. if ( intersect === null ) {
  8217. return;
  8218. }
  8219. }
  8220. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8221. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8222. intersects.push( {
  8223. distance: distance,
  8224. point: _intersectPoint.clone(),
  8225. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8226. face: null,
  8227. object: this
  8228. } );
  8229. }
  8230. copy( source, recursive ) {
  8231. super.copy( source, recursive );
  8232. if ( source.center !== undefined ) this.center.copy( source.center );
  8233. this.material = source.material;
  8234. return this;
  8235. }
  8236. }
  8237. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8238. // compute position in camera space
  8239. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8240. // to check if rotation is not zero
  8241. if ( sin !== undefined ) {
  8242. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8243. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8244. } else {
  8245. _rotatedPosition.copy( _alignedPosition );
  8246. }
  8247. vertexPosition.copy( mvPosition );
  8248. vertexPosition.x += _rotatedPosition.x;
  8249. vertexPosition.y += _rotatedPosition.y;
  8250. // transform to world space
  8251. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8252. }
  8253. const _v1$2 = /*@__PURE__*/ new Vector3();
  8254. const _v2$1 = /*@__PURE__*/ new Vector3();
  8255. class LOD extends Object3D {
  8256. constructor() {
  8257. super();
  8258. this._currentLevel = 0;
  8259. this.type = 'LOD';
  8260. Object.defineProperties( this, {
  8261. levels: {
  8262. enumerable: true,
  8263. value: []
  8264. },
  8265. isLOD: {
  8266. value: true,
  8267. }
  8268. } );
  8269. this.autoUpdate = true;
  8270. }
  8271. copy( source ) {
  8272. super.copy( source, false );
  8273. const levels = source.levels;
  8274. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8275. const level = levels[ i ];
  8276. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8277. }
  8278. this.autoUpdate = source.autoUpdate;
  8279. return this;
  8280. }
  8281. addLevel( object, distance = 0, hysteresis = 0 ) {
  8282. distance = Math.abs( distance );
  8283. const levels = this.levels;
  8284. let l;
  8285. for ( l = 0; l < levels.length; l ++ ) {
  8286. if ( distance < levels[ l ].distance ) {
  8287. break;
  8288. }
  8289. }
  8290. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8291. this.add( object );
  8292. return this;
  8293. }
  8294. getCurrentLevel() {
  8295. return this._currentLevel;
  8296. }
  8297. getObjectForDistance( distance ) {
  8298. const levels = this.levels;
  8299. if ( levels.length > 0 ) {
  8300. let i, l;
  8301. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8302. let levelDistance = levels[ i ].distance;
  8303. if ( levels[ i ].object.visible ) {
  8304. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8305. }
  8306. if ( distance < levelDistance ) {
  8307. break;
  8308. }
  8309. }
  8310. return levels[ i - 1 ].object;
  8311. }
  8312. return null;
  8313. }
  8314. raycast( raycaster, intersects ) {
  8315. const levels = this.levels;
  8316. if ( levels.length > 0 ) {
  8317. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8318. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8319. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8320. }
  8321. }
  8322. update( camera ) {
  8323. const levels = this.levels;
  8324. if ( levels.length > 1 ) {
  8325. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8326. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8327. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8328. levels[ 0 ].object.visible = true;
  8329. let i, l;
  8330. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8331. let levelDistance = levels[ i ].distance;
  8332. if ( levels[ i ].object.visible ) {
  8333. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8334. }
  8335. if ( distance >= levelDistance ) {
  8336. levels[ i - 1 ].object.visible = false;
  8337. levels[ i ].object.visible = true;
  8338. } else {
  8339. break;
  8340. }
  8341. }
  8342. this._currentLevel = i - 1;
  8343. for ( ; i < l; i ++ ) {
  8344. levels[ i ].object.visible = false;
  8345. }
  8346. }
  8347. }
  8348. toJSON( meta ) {
  8349. const data = super.toJSON( meta );
  8350. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8351. data.object.levels = [];
  8352. const levels = this.levels;
  8353. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8354. const level = levels[ i ];
  8355. data.object.levels.push( {
  8356. object: level.object.uuid,
  8357. distance: level.distance,
  8358. hysteresis: level.hysteresis
  8359. } );
  8360. }
  8361. return data;
  8362. }
  8363. }
  8364. const _basePosition = /*@__PURE__*/ new Vector3();
  8365. const _skinIndex = /*@__PURE__*/ new Vector4();
  8366. const _skinWeight = /*@__PURE__*/ new Vector4();
  8367. const _vector3$1 = /*@__PURE__*/ new Vector3();
  8368. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8369. const _vertex = /*@__PURE__*/ new Vector3();
  8370. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8371. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8372. const _ray$2 = /*@__PURE__*/ new Ray();
  8373. class SkinnedMesh extends Mesh {
  8374. constructor( geometry, material ) {
  8375. super( geometry, material );
  8376. this.isSkinnedMesh = true;
  8377. this.type = 'SkinnedMesh';
  8378. this.bindMode = AttachedBindMode;
  8379. this.bindMatrix = new Matrix4();
  8380. this.bindMatrixInverse = new Matrix4();
  8381. this.boundingBox = null;
  8382. this.boundingSphere = null;
  8383. }
  8384. computeBoundingBox() {
  8385. const geometry = this.geometry;
  8386. if ( this.boundingBox === null ) {
  8387. this.boundingBox = new Box3();
  8388. }
  8389. this.boundingBox.makeEmpty();
  8390. const positionAttribute = geometry.getAttribute( 'position' );
  8391. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8392. this.getVertexPosition( i, _vertex );
  8393. this.boundingBox.expandByPoint( _vertex );
  8394. }
  8395. }
  8396. computeBoundingSphere() {
  8397. const geometry = this.geometry;
  8398. if ( this.boundingSphere === null ) {
  8399. this.boundingSphere = new Sphere();
  8400. }
  8401. this.boundingSphere.makeEmpty();
  8402. const positionAttribute = geometry.getAttribute( 'position' );
  8403. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8404. this.getVertexPosition( i, _vertex );
  8405. this.boundingSphere.expandByPoint( _vertex );
  8406. }
  8407. }
  8408. copy( source, recursive ) {
  8409. super.copy( source, recursive );
  8410. this.bindMode = source.bindMode;
  8411. this.bindMatrix.copy( source.bindMatrix );
  8412. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8413. this.skeleton = source.skeleton;
  8414. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8415. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8416. return this;
  8417. }
  8418. raycast( raycaster, intersects ) {
  8419. const material = this.material;
  8420. const matrixWorld = this.matrixWorld;
  8421. if ( material === undefined ) return;
  8422. // test with bounding sphere in world space
  8423. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8424. _sphere$5.copy( this.boundingSphere );
  8425. _sphere$5.applyMatrix4( matrixWorld );
  8426. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8427. // convert ray to local space of skinned mesh
  8428. _inverseMatrix$2.copy( matrixWorld ).invert();
  8429. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8430. // test with bounding box in local space
  8431. if ( this.boundingBox !== null ) {
  8432. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8433. }
  8434. // test for intersections with geometry
  8435. this._computeIntersections( raycaster, intersects, _ray$2 );
  8436. }
  8437. getVertexPosition( index, target ) {
  8438. super.getVertexPosition( index, target );
  8439. this.applyBoneTransform( index, target );
  8440. return target;
  8441. }
  8442. bind( skeleton, bindMatrix ) {
  8443. this.skeleton = skeleton;
  8444. if ( bindMatrix === undefined ) {
  8445. this.updateMatrixWorld( true );
  8446. this.skeleton.calculateInverses();
  8447. bindMatrix = this.matrixWorld;
  8448. }
  8449. this.bindMatrix.copy( bindMatrix );
  8450. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8451. }
  8452. pose() {
  8453. this.skeleton.pose();
  8454. }
  8455. normalizeSkinWeights() {
  8456. const vector = new Vector4();
  8457. const skinWeight = this.geometry.attributes.skinWeight;
  8458. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8459. vector.fromBufferAttribute( skinWeight, i );
  8460. const scale = 1.0 / vector.manhattanLength();
  8461. if ( scale !== Infinity ) {
  8462. vector.multiplyScalar( scale );
  8463. } else {
  8464. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8465. }
  8466. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8467. }
  8468. }
  8469. updateMatrixWorld( force ) {
  8470. super.updateMatrixWorld( force );
  8471. if ( this.bindMode === AttachedBindMode ) {
  8472. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8473. } else if ( this.bindMode === DetachedBindMode ) {
  8474. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8475. } else {
  8476. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8477. }
  8478. }
  8479. applyBoneTransform( index, vector ) {
  8480. const skeleton = this.skeleton;
  8481. const geometry = this.geometry;
  8482. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8483. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8484. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8485. vector.set( 0, 0, 0 );
  8486. for ( let i = 0; i < 4; i ++ ) {
  8487. const weight = _skinWeight.getComponent( i );
  8488. if ( weight !== 0 ) {
  8489. const boneIndex = _skinIndex.getComponent( i );
  8490. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8491. vector.addScaledVector( _vector3$1.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8492. }
  8493. }
  8494. return vector.applyMatrix4( this.bindMatrixInverse );
  8495. }
  8496. }
  8497. class Bone extends Object3D {
  8498. constructor() {
  8499. super();
  8500. this.isBone = true;
  8501. this.type = 'Bone';
  8502. }
  8503. }
  8504. class DataTexture extends Texture {
  8505. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8506. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8507. this.isDataTexture = true;
  8508. this.image = { data: data, width: width, height: height };
  8509. this.generateMipmaps = false;
  8510. this.flipY = false;
  8511. this.unpackAlignment = 1;
  8512. }
  8513. }
  8514. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8515. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8516. class Skeleton {
  8517. constructor( bones = [], boneInverses = [] ) {
  8518. this.uuid = generateUUID();
  8519. this.bones = bones.slice( 0 );
  8520. this.boneInverses = boneInverses;
  8521. this.boneMatrices = null;
  8522. this.boneTexture = null;
  8523. this.init();
  8524. }
  8525. init() {
  8526. const bones = this.bones;
  8527. const boneInverses = this.boneInverses;
  8528. this.boneMatrices = new Float32Array( bones.length * 16 );
  8529. // calculate inverse bone matrices if necessary
  8530. if ( boneInverses.length === 0 ) {
  8531. this.calculateInverses();
  8532. } else {
  8533. // handle special case
  8534. if ( bones.length !== boneInverses.length ) {
  8535. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8536. this.boneInverses = [];
  8537. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8538. this.boneInverses.push( new Matrix4() );
  8539. }
  8540. }
  8541. }
  8542. }
  8543. calculateInverses() {
  8544. this.boneInverses.length = 0;
  8545. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8546. const inverse = new Matrix4();
  8547. if ( this.bones[ i ] ) {
  8548. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8549. }
  8550. this.boneInverses.push( inverse );
  8551. }
  8552. }
  8553. pose() {
  8554. // recover the bind-time world matrices
  8555. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8556. const bone = this.bones[ i ];
  8557. if ( bone ) {
  8558. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8559. }
  8560. }
  8561. // compute the local matrices, positions, rotations and scales
  8562. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8563. const bone = this.bones[ i ];
  8564. if ( bone ) {
  8565. if ( bone.parent && bone.parent.isBone ) {
  8566. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8567. bone.matrix.multiply( bone.matrixWorld );
  8568. } else {
  8569. bone.matrix.copy( bone.matrixWorld );
  8570. }
  8571. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8572. }
  8573. }
  8574. }
  8575. update() {
  8576. const bones = this.bones;
  8577. const boneInverses = this.boneInverses;
  8578. const boneMatrices = this.boneMatrices;
  8579. const boneTexture = this.boneTexture;
  8580. // flatten bone matrices to array
  8581. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8582. // compute the offset between the current and the original transform
  8583. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8584. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8585. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8586. }
  8587. if ( boneTexture !== null ) {
  8588. boneTexture.needsUpdate = true;
  8589. }
  8590. }
  8591. clone() {
  8592. return new Skeleton( this.bones, this.boneInverses );
  8593. }
  8594. computeBoneTexture() {
  8595. // layout (1 matrix = 4 pixels)
  8596. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8597. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8598. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8599. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8600. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8601. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8602. size = Math.ceil( size / 4 ) * 4;
  8603. size = Math.max( size, 4 );
  8604. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8605. boneMatrices.set( this.boneMatrices ); // copy current values
  8606. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8607. boneTexture.needsUpdate = true;
  8608. this.boneMatrices = boneMatrices;
  8609. this.boneTexture = boneTexture;
  8610. return this;
  8611. }
  8612. getBoneByName( name ) {
  8613. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8614. const bone = this.bones[ i ];
  8615. if ( bone.name === name ) {
  8616. return bone;
  8617. }
  8618. }
  8619. return undefined;
  8620. }
  8621. dispose( ) {
  8622. if ( this.boneTexture !== null ) {
  8623. this.boneTexture.dispose();
  8624. this.boneTexture = null;
  8625. }
  8626. }
  8627. fromJSON( json, bones ) {
  8628. this.uuid = json.uuid;
  8629. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8630. const uuid = json.bones[ i ];
  8631. let bone = bones[ uuid ];
  8632. if ( bone === undefined ) {
  8633. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8634. bone = new Bone();
  8635. }
  8636. this.bones.push( bone );
  8637. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8638. }
  8639. this.init();
  8640. return this;
  8641. }
  8642. toJSON() {
  8643. const data = {
  8644. metadata: {
  8645. version: 4.6,
  8646. type: 'Skeleton',
  8647. generator: 'Skeleton.toJSON'
  8648. },
  8649. bones: [],
  8650. boneInverses: []
  8651. };
  8652. data.uuid = this.uuid;
  8653. const bones = this.bones;
  8654. const boneInverses = this.boneInverses;
  8655. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8656. const bone = bones[ i ];
  8657. data.bones.push( bone.uuid );
  8658. const boneInverse = boneInverses[ i ];
  8659. data.boneInverses.push( boneInverse.toArray() );
  8660. }
  8661. return data;
  8662. }
  8663. }
  8664. class InstancedBufferAttribute extends BufferAttribute {
  8665. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8666. super( array, itemSize, normalized );
  8667. this.isInstancedBufferAttribute = true;
  8668. this.meshPerAttribute = meshPerAttribute;
  8669. }
  8670. copy( source ) {
  8671. super.copy( source );
  8672. this.meshPerAttribute = source.meshPerAttribute;
  8673. return this;
  8674. }
  8675. toJSON() {
  8676. const data = super.toJSON();
  8677. data.meshPerAttribute = this.meshPerAttribute;
  8678. data.isInstancedBufferAttribute = true;
  8679. return data;
  8680. }
  8681. }
  8682. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8683. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8684. const _instanceIntersects = [];
  8685. const _box3 = /*@__PURE__*/ new Box3();
  8686. const _identity = /*@__PURE__*/ new Matrix4();
  8687. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8688. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8689. class InstancedMesh extends Mesh {
  8690. constructor( geometry, material, count ) {
  8691. super( geometry, material );
  8692. this.isInstancedMesh = true;
  8693. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8694. this.instanceColor = null;
  8695. this.morphTexture = null;
  8696. this.count = count;
  8697. this.boundingBox = null;
  8698. this.boundingSphere = null;
  8699. for ( let i = 0; i < count; i ++ ) {
  8700. this.setMatrixAt( i, _identity );
  8701. }
  8702. }
  8703. computeBoundingBox() {
  8704. const geometry = this.geometry;
  8705. const count = this.count;
  8706. if ( this.boundingBox === null ) {
  8707. this.boundingBox = new Box3();
  8708. }
  8709. if ( geometry.boundingBox === null ) {
  8710. geometry.computeBoundingBox();
  8711. }
  8712. this.boundingBox.makeEmpty();
  8713. for ( let i = 0; i < count; i ++ ) {
  8714. this.getMatrixAt( i, _instanceLocalMatrix );
  8715. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8716. this.boundingBox.union( _box3 );
  8717. }
  8718. }
  8719. computeBoundingSphere() {
  8720. const geometry = this.geometry;
  8721. const count = this.count;
  8722. if ( this.boundingSphere === null ) {
  8723. this.boundingSphere = new Sphere();
  8724. }
  8725. if ( geometry.boundingSphere === null ) {
  8726. geometry.computeBoundingSphere();
  8727. }
  8728. this.boundingSphere.makeEmpty();
  8729. for ( let i = 0; i < count; i ++ ) {
  8730. this.getMatrixAt( i, _instanceLocalMatrix );
  8731. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8732. this.boundingSphere.union( _sphere$4 );
  8733. }
  8734. }
  8735. copy( source, recursive ) {
  8736. super.copy( source, recursive );
  8737. this.instanceMatrix.copy( source.instanceMatrix );
  8738. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8739. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8740. this.count = source.count;
  8741. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8742. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8743. return this;
  8744. }
  8745. getColorAt( index, color ) {
  8746. color.fromArray( this.instanceColor.array, index * 3 );
  8747. }
  8748. getMatrixAt( index, matrix ) {
  8749. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8750. }
  8751. getMorphAt( index, object ) {
  8752. const objectInfluences = object.morphTargetInfluences;
  8753. const array = this.morphTexture.source.data.data;
  8754. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8755. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8756. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8757. objectInfluences[ i ] = array[ dataIndex + i ];
  8758. }
  8759. }
  8760. raycast( raycaster, intersects ) {
  8761. const matrixWorld = this.matrixWorld;
  8762. const raycastTimes = this.count;
  8763. _mesh$1.geometry = this.geometry;
  8764. _mesh$1.material = this.material;
  8765. if ( _mesh$1.material === undefined ) return;
  8766. // test with bounding sphere first
  8767. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8768. _sphere$4.copy( this.boundingSphere );
  8769. _sphere$4.applyMatrix4( matrixWorld );
  8770. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8771. // now test each instance
  8772. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8773. // calculate the world matrix for each instance
  8774. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8775. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8776. // the mesh represents this single instance
  8777. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8778. _mesh$1.raycast( raycaster, _instanceIntersects );
  8779. // process the result of raycast
  8780. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8781. const intersect = _instanceIntersects[ i ];
  8782. intersect.instanceId = instanceId;
  8783. intersect.object = this;
  8784. intersects.push( intersect );
  8785. }
  8786. _instanceIntersects.length = 0;
  8787. }
  8788. }
  8789. setColorAt( index, color ) {
  8790. if ( this.instanceColor === null ) {
  8791. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  8792. }
  8793. color.toArray( this.instanceColor.array, index * 3 );
  8794. }
  8795. setMatrixAt( index, matrix ) {
  8796. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8797. }
  8798. setMorphAt( index, object ) {
  8799. const objectInfluences = object.morphTargetInfluences;
  8800. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8801. if ( this.morphTexture === null ) {
  8802. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8803. }
  8804. const array = this.morphTexture.source.data.data;
  8805. let morphInfluencesSum = 0;
  8806. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8807. morphInfluencesSum += objectInfluences[ i ];
  8808. }
  8809. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8810. const dataIndex = len * index;
  8811. array[ dataIndex ] = morphBaseInfluence;
  8812. array.set( objectInfluences, dataIndex + 1 );
  8813. }
  8814. updateMorphTargets() {
  8815. }
  8816. dispose() {
  8817. this.dispatchEvent( { type: 'dispose' } );
  8818. if ( this.morphTexture !== null ) {
  8819. this.morphTexture.dispose();
  8820. this.morphTexture = null;
  8821. }
  8822. return this;
  8823. }
  8824. }
  8825. const _vector1 = /*@__PURE__*/ new Vector3();
  8826. const _vector2 = /*@__PURE__*/ new Vector3();
  8827. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8828. class Plane {
  8829. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8830. this.isPlane = true;
  8831. // normal is assumed to be normalized
  8832. this.normal = normal;
  8833. this.constant = constant;
  8834. }
  8835. set( normal, constant ) {
  8836. this.normal.copy( normal );
  8837. this.constant = constant;
  8838. return this;
  8839. }
  8840. setComponents( x, y, z, w ) {
  8841. this.normal.set( x, y, z );
  8842. this.constant = w;
  8843. return this;
  8844. }
  8845. setFromNormalAndCoplanarPoint( normal, point ) {
  8846. this.normal.copy( normal );
  8847. this.constant = - point.dot( this.normal );
  8848. return this;
  8849. }
  8850. setFromCoplanarPoints( a, b, c ) {
  8851. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8852. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8853. this.setFromNormalAndCoplanarPoint( normal, a );
  8854. return this;
  8855. }
  8856. copy( plane ) {
  8857. this.normal.copy( plane.normal );
  8858. this.constant = plane.constant;
  8859. return this;
  8860. }
  8861. normalize() {
  8862. // Note: will lead to a divide by zero if the plane is invalid.
  8863. const inverseNormalLength = 1.0 / this.normal.length();
  8864. this.normal.multiplyScalar( inverseNormalLength );
  8865. this.constant *= inverseNormalLength;
  8866. return this;
  8867. }
  8868. negate() {
  8869. this.constant *= - 1;
  8870. this.normal.negate();
  8871. return this;
  8872. }
  8873. distanceToPoint( point ) {
  8874. return this.normal.dot( point ) + this.constant;
  8875. }
  8876. distanceToSphere( sphere ) {
  8877. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8878. }
  8879. projectPoint( point, target ) {
  8880. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8881. }
  8882. intersectLine( line, target ) {
  8883. const direction = line.delta( _vector1 );
  8884. const denominator = this.normal.dot( direction );
  8885. if ( denominator === 0 ) {
  8886. // line is coplanar, return origin
  8887. if ( this.distanceToPoint( line.start ) === 0 ) {
  8888. return target.copy( line.start );
  8889. }
  8890. // Unsure if this is the correct method to handle this case.
  8891. return null;
  8892. }
  8893. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8894. if ( t < 0 || t > 1 ) {
  8895. return null;
  8896. }
  8897. return target.copy( line.start ).addScaledVector( direction, t );
  8898. }
  8899. intersectsLine( line ) {
  8900. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8901. const startSign = this.distanceToPoint( line.start );
  8902. const endSign = this.distanceToPoint( line.end );
  8903. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8904. }
  8905. intersectsBox( box ) {
  8906. return box.intersectsPlane( this );
  8907. }
  8908. intersectsSphere( sphere ) {
  8909. return sphere.intersectsPlane( this );
  8910. }
  8911. coplanarPoint( target ) {
  8912. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8913. }
  8914. applyMatrix4( matrix, optionalNormalMatrix ) {
  8915. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8916. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8917. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8918. this.constant = - referencePoint.dot( normal );
  8919. return this;
  8920. }
  8921. translate( offset ) {
  8922. this.constant -= offset.dot( this.normal );
  8923. return this;
  8924. }
  8925. equals( plane ) {
  8926. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8927. }
  8928. clone() {
  8929. return new this.constructor().copy( this );
  8930. }
  8931. }
  8932. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8933. const _vector$6 = /*@__PURE__*/ new Vector3();
  8934. class Frustum {
  8935. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8936. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8937. }
  8938. set( p0, p1, p2, p3, p4, p5 ) {
  8939. const planes = this.planes;
  8940. planes[ 0 ].copy( p0 );
  8941. planes[ 1 ].copy( p1 );
  8942. planes[ 2 ].copy( p2 );
  8943. planes[ 3 ].copy( p3 );
  8944. planes[ 4 ].copy( p4 );
  8945. planes[ 5 ].copy( p5 );
  8946. return this;
  8947. }
  8948. copy( frustum ) {
  8949. const planes = this.planes;
  8950. for ( let i = 0; i < 6; i ++ ) {
  8951. planes[ i ].copy( frustum.planes[ i ] );
  8952. }
  8953. return this;
  8954. }
  8955. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  8956. const planes = this.planes;
  8957. const me = m.elements;
  8958. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8959. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8960. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8961. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8962. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8963. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8964. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8965. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8966. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8967. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8968. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8969. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8970. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  8971. } else {
  8972. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  8973. }
  8974. return this;
  8975. }
  8976. intersectsObject( object ) {
  8977. if ( object.boundingSphere !== undefined ) {
  8978. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  8979. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  8980. } else {
  8981. const geometry = object.geometry;
  8982. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8983. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8984. }
  8985. return this.intersectsSphere( _sphere$3 );
  8986. }
  8987. intersectsSprite( sprite ) {
  8988. _sphere$3.center.set( 0, 0, 0 );
  8989. _sphere$3.radius = 0.7071067811865476;
  8990. _sphere$3.applyMatrix4( sprite.matrixWorld );
  8991. return this.intersectsSphere( _sphere$3 );
  8992. }
  8993. intersectsSphere( sphere ) {
  8994. const planes = this.planes;
  8995. const center = sphere.center;
  8996. const negRadius = - sphere.radius;
  8997. for ( let i = 0; i < 6; i ++ ) {
  8998. const distance = planes[ i ].distanceToPoint( center );
  8999. if ( distance < negRadius ) {
  9000. return false;
  9001. }
  9002. }
  9003. return true;
  9004. }
  9005. intersectsBox( box ) {
  9006. const planes = this.planes;
  9007. for ( let i = 0; i < 6; i ++ ) {
  9008. const plane = planes[ i ];
  9009. // corner at max distance
  9010. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9011. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9012. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9013. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9014. return false;
  9015. }
  9016. }
  9017. return true;
  9018. }
  9019. containsPoint( point ) {
  9020. const planes = this.planes;
  9021. for ( let i = 0; i < 6; i ++ ) {
  9022. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9023. return false;
  9024. }
  9025. }
  9026. return true;
  9027. }
  9028. clone() {
  9029. return new this.constructor().copy( this );
  9030. }
  9031. }
  9032. function sortOpaque( a, b ) {
  9033. return a.z - b.z;
  9034. }
  9035. function sortTransparent( a, b ) {
  9036. return b.z - a.z;
  9037. }
  9038. class MultiDrawRenderList {
  9039. constructor() {
  9040. this.index = 0;
  9041. this.pool = [];
  9042. this.list = [];
  9043. }
  9044. push( drawRange, z, index ) {
  9045. const pool = this.pool;
  9046. const list = this.list;
  9047. if ( this.index >= pool.length ) {
  9048. pool.push( {
  9049. start: - 1,
  9050. count: - 1,
  9051. z: - 1,
  9052. index: - 1,
  9053. } );
  9054. }
  9055. const item = pool[ this.index ];
  9056. list.push( item );
  9057. this.index ++;
  9058. item.start = drawRange.start;
  9059. item.count = drawRange.count;
  9060. item.z = z;
  9061. item.index = index;
  9062. }
  9063. reset() {
  9064. this.list.length = 0;
  9065. this.index = 0;
  9066. }
  9067. }
  9068. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9069. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9070. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9071. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9072. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9073. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9074. const _box$1 = /*@__PURE__*/ new Box3();
  9075. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9076. const _vector$5 = /*@__PURE__*/ new Vector3();
  9077. const _forward = /*@__PURE__*/ new Vector3();
  9078. const _temp = /*@__PURE__*/ new Vector3();
  9079. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9080. const _mesh = /*@__PURE__*/ new Mesh();
  9081. const _batchIntersects = [];
  9082. // @TODO: SkinnedMesh support?
  9083. // @TODO: geometry.groups support?
  9084. // @TODO: geometry.drawRange support?
  9085. // @TODO: geometry.morphAttributes support?
  9086. // @TODO: Support uniform parameter per geometry
  9087. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9088. // copies data from attribute "src" into "target" starting at "targetOffset"
  9089. function copyAttributeData( src, target, targetOffset = 0 ) {
  9090. const itemSize = target.itemSize;
  9091. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9092. // use the component getters and setters if the array data cannot
  9093. // be copied directly
  9094. const vertexCount = src.count;
  9095. for ( let i = 0; i < vertexCount; i ++ ) {
  9096. for ( let c = 0; c < itemSize; c ++ ) {
  9097. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9098. }
  9099. }
  9100. } else {
  9101. // faster copy approach using typed array set function
  9102. target.array.set( src.array, targetOffset * itemSize );
  9103. }
  9104. target.needsUpdate = true;
  9105. }
  9106. class BatchedMesh extends Mesh {
  9107. get maxInstanceCount() {
  9108. return this._maxInstanceCount;
  9109. }
  9110. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9111. super( new BufferGeometry(), material );
  9112. this.isBatchedMesh = true;
  9113. this.perObjectFrustumCulled = true;
  9114. this.sortObjects = true;
  9115. this.boundingBox = null;
  9116. this.boundingSphere = null;
  9117. this.customSort = null;
  9118. // stores visible, active, and geometry id per object
  9119. this._drawInfo = [];
  9120. // geometry information
  9121. this._drawRanges = [];
  9122. this._reservedRanges = [];
  9123. this._bounds = [];
  9124. this._maxInstanceCount = maxInstanceCount;
  9125. this._maxVertexCount = maxVertexCount;
  9126. this._maxIndexCount = maxIndexCount;
  9127. this._geometryInitialized = false;
  9128. this._geometryCount = 0;
  9129. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9130. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9131. this._multiDrawCount = 0;
  9132. this._multiDrawInstances = null;
  9133. this._visibilityChanged = true;
  9134. // Local matrix per geometry by using data texture
  9135. this._matricesTexture = null;
  9136. this._indirectTexture = null;
  9137. this._colorsTexture = null;
  9138. this._initMatricesTexture();
  9139. this._initIndirectTexture();
  9140. }
  9141. _initMatricesTexture() {
  9142. // layout (1 matrix = 4 pixels)
  9143. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9144. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9145. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9146. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9147. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9148. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9149. size = Math.ceil( size / 4 ) * 4;
  9150. size = Math.max( size, 4 );
  9151. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9152. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9153. this._matricesTexture = matricesTexture;
  9154. }
  9155. _initIndirectTexture() {
  9156. let size = Math.sqrt( this._maxInstanceCount );
  9157. size = Math.ceil( size );
  9158. const indirectArray = new Uint32Array( size * size );
  9159. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9160. this._indirectTexture = indirectTexture;
  9161. }
  9162. _initColorsTexture() {
  9163. let size = Math.sqrt( this._maxIndexCount );
  9164. size = Math.ceil( size );
  9165. // 4 floats per RGBA pixel initialized to white
  9166. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9167. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9168. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9169. this._colorsTexture = colorsTexture;
  9170. }
  9171. _initializeGeometry( reference ) {
  9172. const geometry = this.geometry;
  9173. const maxVertexCount = this._maxVertexCount;
  9174. const maxIndexCount = this._maxIndexCount;
  9175. if ( this._geometryInitialized === false ) {
  9176. for ( const attributeName in reference.attributes ) {
  9177. const srcAttribute = reference.getAttribute( attributeName );
  9178. const { array, itemSize, normalized } = srcAttribute;
  9179. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9180. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9181. geometry.setAttribute( attributeName, dstAttribute );
  9182. }
  9183. if ( reference.getIndex() !== null ) {
  9184. // Reserve last u16 index for primitive restart.
  9185. const indexArray = maxVertexCount > 65535
  9186. ? new Uint32Array( maxIndexCount )
  9187. : new Uint16Array( maxIndexCount );
  9188. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9189. }
  9190. this._geometryInitialized = true;
  9191. }
  9192. }
  9193. // Make sure the geometry is compatible with the existing combined geometry attributes
  9194. _validateGeometry( geometry ) {
  9195. // check to ensure the geometries are using consistent attributes and indices
  9196. const batchGeometry = this.geometry;
  9197. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9198. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9199. }
  9200. for ( const attributeName in batchGeometry.attributes ) {
  9201. if ( ! geometry.hasAttribute( attributeName ) ) {
  9202. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9203. }
  9204. const srcAttribute = geometry.getAttribute( attributeName );
  9205. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9206. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9207. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9208. }
  9209. }
  9210. }
  9211. setCustomSort( func ) {
  9212. this.customSort = func;
  9213. return this;
  9214. }
  9215. computeBoundingBox() {
  9216. if ( this.boundingBox === null ) {
  9217. this.boundingBox = new Box3();
  9218. }
  9219. const geometryCount = this._geometryCount;
  9220. const boundingBox = this.boundingBox;
  9221. const drawInfo = this._drawInfo;
  9222. boundingBox.makeEmpty();
  9223. for ( let i = 0; i < geometryCount; i ++ ) {
  9224. if ( drawInfo[ i ].active === false ) continue;
  9225. const geometryId = drawInfo[ i ].geometryIndex;
  9226. this.getMatrixAt( i, _matrix$1 );
  9227. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9228. boundingBox.union( _box$1 );
  9229. }
  9230. }
  9231. computeBoundingSphere() {
  9232. if ( this.boundingSphere === null ) {
  9233. this.boundingSphere = new Sphere();
  9234. }
  9235. const boundingSphere = this.boundingSphere;
  9236. const drawInfo = this._drawInfo;
  9237. boundingSphere.makeEmpty();
  9238. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9239. if ( drawInfo[ i ].active === false ) continue;
  9240. const geometryId = drawInfo[ i ].geometryIndex;
  9241. this.getMatrixAt( i, _matrix$1 );
  9242. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9243. boundingSphere.union( _sphere$2 );
  9244. }
  9245. }
  9246. addInstance( geometryId ) {
  9247. // ensure we're not over geometry
  9248. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9249. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9250. }
  9251. this._drawInfo.push( {
  9252. visible: true,
  9253. active: true,
  9254. geometryIndex: geometryId,
  9255. } );
  9256. // initialize the matrix
  9257. const drawId = this._drawInfo.length - 1;
  9258. const matricesTexture = this._matricesTexture;
  9259. const matricesArray = matricesTexture.image.data;
  9260. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9261. matricesTexture.needsUpdate = true;
  9262. const colorsTexture = this._colorsTexture;
  9263. if ( colorsTexture ) {
  9264. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9265. colorsTexture.needsUpdate = true;
  9266. }
  9267. return drawId;
  9268. }
  9269. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9270. this._initializeGeometry( geometry );
  9271. this._validateGeometry( geometry );
  9272. // ensure we're not over geometry
  9273. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9274. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9275. }
  9276. // get the necessary range fo the geometry
  9277. const reservedRange = {
  9278. vertexStart: - 1,
  9279. vertexCount: - 1,
  9280. indexStart: - 1,
  9281. indexCount: - 1,
  9282. };
  9283. let lastRange = null;
  9284. const reservedRanges = this._reservedRanges;
  9285. const drawRanges = this._drawRanges;
  9286. const bounds = this._bounds;
  9287. if ( this._geometryCount !== 0 ) {
  9288. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9289. }
  9290. if ( vertexCount === - 1 ) {
  9291. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9292. } else {
  9293. reservedRange.vertexCount = vertexCount;
  9294. }
  9295. if ( lastRange === null ) {
  9296. reservedRange.vertexStart = 0;
  9297. } else {
  9298. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9299. }
  9300. const index = geometry.getIndex();
  9301. const hasIndex = index !== null;
  9302. if ( hasIndex ) {
  9303. if ( indexCount === - 1 ) {
  9304. reservedRange.indexCount = index.count;
  9305. } else {
  9306. reservedRange.indexCount = indexCount;
  9307. }
  9308. if ( lastRange === null ) {
  9309. reservedRange.indexStart = 0;
  9310. } else {
  9311. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9312. }
  9313. }
  9314. if (
  9315. reservedRange.indexStart !== - 1 &&
  9316. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9317. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9318. ) {
  9319. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9320. }
  9321. // update id
  9322. const geometryId = this._geometryCount;
  9323. this._geometryCount ++;
  9324. // add the reserved range and draw range objects
  9325. reservedRanges.push( reservedRange );
  9326. drawRanges.push( {
  9327. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9328. count: - 1
  9329. } );
  9330. bounds.push( {
  9331. boxInitialized: false,
  9332. box: new Box3(),
  9333. sphereInitialized: false,
  9334. sphere: new Sphere()
  9335. } );
  9336. // update the geometry
  9337. this.setGeometryAt( geometryId, geometry );
  9338. return geometryId;
  9339. }
  9340. setGeometryAt( geometryId, geometry ) {
  9341. if ( geometryId >= this._geometryCount ) {
  9342. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9343. }
  9344. this._validateGeometry( geometry );
  9345. const batchGeometry = this.geometry;
  9346. const hasIndex = batchGeometry.getIndex() !== null;
  9347. const dstIndex = batchGeometry.getIndex();
  9348. const srcIndex = geometry.getIndex();
  9349. const reservedRange = this._reservedRanges[ geometryId ];
  9350. if (
  9351. hasIndex &&
  9352. srcIndex.count > reservedRange.indexCount ||
  9353. geometry.attributes.position.count > reservedRange.vertexCount
  9354. ) {
  9355. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9356. }
  9357. // copy geometry over
  9358. const vertexStart = reservedRange.vertexStart;
  9359. const vertexCount = reservedRange.vertexCount;
  9360. for ( const attributeName in batchGeometry.attributes ) {
  9361. // copy attribute data
  9362. const srcAttribute = geometry.getAttribute( attributeName );
  9363. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9364. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9365. // fill the rest in with zeroes
  9366. const itemSize = srcAttribute.itemSize;
  9367. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9368. const index = vertexStart + i;
  9369. for ( let c = 0; c < itemSize; c ++ ) {
  9370. dstAttribute.setComponent( index, c, 0 );
  9371. }
  9372. }
  9373. dstAttribute.needsUpdate = true;
  9374. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9375. }
  9376. // copy index
  9377. if ( hasIndex ) {
  9378. const indexStart = reservedRange.indexStart;
  9379. // copy index data over
  9380. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9381. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9382. }
  9383. // fill the rest in with zeroes
  9384. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9385. dstIndex.setX( indexStart + i, vertexStart );
  9386. }
  9387. dstIndex.needsUpdate = true;
  9388. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9389. }
  9390. // store the bounding boxes
  9391. const bound = this._bounds[ geometryId ];
  9392. if ( geometry.boundingBox !== null ) {
  9393. bound.box.copy( geometry.boundingBox );
  9394. bound.boxInitialized = true;
  9395. } else {
  9396. bound.boxInitialized = false;
  9397. }
  9398. if ( geometry.boundingSphere !== null ) {
  9399. bound.sphere.copy( geometry.boundingSphere );
  9400. bound.sphereInitialized = true;
  9401. } else {
  9402. bound.sphereInitialized = false;
  9403. }
  9404. // set drawRange count
  9405. const drawRange = this._drawRanges[ geometryId ];
  9406. const posAttr = geometry.getAttribute( 'position' );
  9407. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9408. this._visibilityChanged = true;
  9409. return geometryId;
  9410. }
  9411. /*
  9412. deleteGeometry( geometryId ) {
  9413. // TODO: delete geometry and associated instances
  9414. }
  9415. */
  9416. /*
  9417. deleteInstance( instanceId ) {
  9418. // Note: User needs to call optimize() afterward to pack the data.
  9419. const drawInfo = this._drawInfo;
  9420. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9421. return this;
  9422. }
  9423. drawInfo[ instanceId ].active = false;
  9424. this._visibilityChanged = true;
  9425. return this;
  9426. }
  9427. */
  9428. // get bounding box and compute it if it doesn't exist
  9429. getBoundingBoxAt( geometryId, target ) {
  9430. if ( geometryId >= this._geometryCount ) {
  9431. return null;
  9432. }
  9433. // compute bounding box
  9434. const bound = this._bounds[ geometryId ];
  9435. const box = bound.box;
  9436. const geometry = this.geometry;
  9437. if ( bound.boxInitialized === false ) {
  9438. box.makeEmpty();
  9439. const index = geometry.index;
  9440. const position = geometry.attributes.position;
  9441. const drawRange = this._drawRanges[ geometryId ];
  9442. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9443. let iv = i;
  9444. if ( index ) {
  9445. iv = index.getX( iv );
  9446. }
  9447. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9448. }
  9449. bound.boxInitialized = true;
  9450. }
  9451. target.copy( box );
  9452. return target;
  9453. }
  9454. // get bounding sphere and compute it if it doesn't exist
  9455. getBoundingSphereAt( geometryId, target ) {
  9456. if ( geometryId >= this._geometryCount ) {
  9457. return null;
  9458. }
  9459. // compute bounding sphere
  9460. const bound = this._bounds[ geometryId ];
  9461. const sphere = bound.sphere;
  9462. const geometry = this.geometry;
  9463. if ( bound.sphereInitialized === false ) {
  9464. sphere.makeEmpty();
  9465. this.getBoundingBoxAt( geometryId, _box$1 );
  9466. _box$1.getCenter( sphere.center );
  9467. const index = geometry.index;
  9468. const position = geometry.attributes.position;
  9469. const drawRange = this._drawRanges[ geometryId ];
  9470. let maxRadiusSq = 0;
  9471. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9472. let iv = i;
  9473. if ( index ) {
  9474. iv = index.getX( iv );
  9475. }
  9476. _vector$5.fromBufferAttribute( position, iv );
  9477. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9478. }
  9479. sphere.radius = Math.sqrt( maxRadiusSq );
  9480. bound.sphereInitialized = true;
  9481. }
  9482. target.copy( sphere );
  9483. return target;
  9484. }
  9485. setMatrixAt( instanceId, matrix ) {
  9486. // @TODO: Map geometryId to index of the arrays because
  9487. // optimize() can make geometryId mismatch the index
  9488. const drawInfo = this._drawInfo;
  9489. const matricesTexture = this._matricesTexture;
  9490. const matricesArray = this._matricesTexture.image.data;
  9491. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9492. return this;
  9493. }
  9494. matrix.toArray( matricesArray, instanceId * 16 );
  9495. matricesTexture.needsUpdate = true;
  9496. return this;
  9497. }
  9498. getMatrixAt( instanceId, matrix ) {
  9499. const drawInfo = this._drawInfo;
  9500. const matricesArray = this._matricesTexture.image.data;
  9501. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9502. return null;
  9503. }
  9504. return matrix.fromArray( matricesArray, instanceId * 16 );
  9505. }
  9506. setColorAt( instanceId, color ) {
  9507. if ( this._colorsTexture === null ) {
  9508. this._initColorsTexture();
  9509. }
  9510. // @TODO: Map id to index of the arrays because
  9511. // optimize() can make id mismatch the index
  9512. const colorsTexture = this._colorsTexture;
  9513. const colorsArray = this._colorsTexture.image.data;
  9514. const drawInfo = this._drawInfo;
  9515. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9516. return this;
  9517. }
  9518. color.toArray( colorsArray, instanceId * 4 );
  9519. colorsTexture.needsUpdate = true;
  9520. return this;
  9521. }
  9522. getColorAt( instanceId, color ) {
  9523. const colorsArray = this._colorsTexture.image.data;
  9524. const drawInfo = this._drawInfo;
  9525. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9526. return null;
  9527. }
  9528. return color.fromArray( colorsArray, instanceId * 4 );
  9529. }
  9530. setVisibleAt( instanceId, value ) {
  9531. // if the geometry is out of range, not active, or visibility state
  9532. // does not change then return early
  9533. const drawInfo = this._drawInfo;
  9534. if (
  9535. instanceId >= drawInfo.length ||
  9536. drawInfo[ instanceId ].active === false ||
  9537. drawInfo[ instanceId ].visible === value
  9538. ) {
  9539. return this;
  9540. }
  9541. drawInfo[ instanceId ].visible = value;
  9542. this._visibilityChanged = true;
  9543. return this;
  9544. }
  9545. getVisibleAt( instanceId ) {
  9546. // return early if the geometry is out of range or not active
  9547. const drawInfo = this._drawInfo;
  9548. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9549. return false;
  9550. }
  9551. return drawInfo[ instanceId ].visible;
  9552. }
  9553. raycast( raycaster, intersects ) {
  9554. const drawInfo = this._drawInfo;
  9555. const drawRanges = this._drawRanges;
  9556. const matrixWorld = this.matrixWorld;
  9557. const batchGeometry = this.geometry;
  9558. // iterate over each geometry
  9559. _mesh.material = this.material;
  9560. _mesh.geometry.index = batchGeometry.index;
  9561. _mesh.geometry.attributes = batchGeometry.attributes;
  9562. if ( _mesh.geometry.boundingBox === null ) {
  9563. _mesh.geometry.boundingBox = new Box3();
  9564. }
  9565. if ( _mesh.geometry.boundingSphere === null ) {
  9566. _mesh.geometry.boundingSphere = new Sphere();
  9567. }
  9568. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9569. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9570. continue;
  9571. }
  9572. const geometryId = drawInfo[ i ].geometryIndex;
  9573. const drawRange = drawRanges[ geometryId ];
  9574. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9575. // ge the intersects
  9576. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9577. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9578. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9579. _mesh.raycast( raycaster, _batchIntersects );
  9580. // add batch id to the intersects
  9581. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9582. const intersect = _batchIntersects[ j ];
  9583. intersect.object = this;
  9584. intersect.batchId = i;
  9585. intersects.push( intersect );
  9586. }
  9587. _batchIntersects.length = 0;
  9588. }
  9589. _mesh.material = null;
  9590. _mesh.geometry.index = null;
  9591. _mesh.geometry.attributes = {};
  9592. _mesh.geometry.setDrawRange( 0, Infinity );
  9593. }
  9594. copy( source ) {
  9595. super.copy( source );
  9596. this.geometry = source.geometry.clone();
  9597. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9598. this.sortObjects = source.sortObjects;
  9599. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9600. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9601. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9602. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9603. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9604. this._bounds = source._bounds.map( bound => ( {
  9605. boxInitialized: bound.boxInitialized,
  9606. box: bound.box.clone(),
  9607. sphereInitialized: bound.sphereInitialized,
  9608. sphere: bound.sphere.clone()
  9609. } ) );
  9610. this._maxInstanceCount = source._maxInstanceCount;
  9611. this._maxVertexCount = source._maxVertexCount;
  9612. this._maxIndexCount = source._maxIndexCount;
  9613. this._geometryInitialized = source._geometryInitialized;
  9614. this._geometryCount = source._geometryCount;
  9615. this._multiDrawCounts = source._multiDrawCounts.slice();
  9616. this._multiDrawStarts = source._multiDrawStarts.slice();
  9617. this._matricesTexture = source._matricesTexture.clone();
  9618. this._matricesTexture.image.data = this._matricesTexture.image.slice();
  9619. if ( this._colorsTexture !== null ) {
  9620. this._colorsTexture = source._colorsTexture.clone();
  9621. this._colorsTexture.image.data = this._colorsTexture.image.slice();
  9622. }
  9623. return this;
  9624. }
  9625. dispose() {
  9626. // Assuming the geometry is not shared with other meshes
  9627. this.geometry.dispose();
  9628. this._matricesTexture.dispose();
  9629. this._matricesTexture = null;
  9630. this._indirectTexture.dispose();
  9631. this._indirectTexture = null;
  9632. if ( this._colorsTexture !== null ) {
  9633. this._colorsTexture.dispose();
  9634. this._colorsTexture = null;
  9635. }
  9636. return this;
  9637. }
  9638. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9639. // if visibility has not changed and frustum culling and object sorting is not required
  9640. // then skip iterating over all items
  9641. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9642. return;
  9643. }
  9644. // the indexed version of the multi draw function requires specifying the start
  9645. // offset in bytes.
  9646. const index = geometry.getIndex();
  9647. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9648. const drawInfo = this._drawInfo;
  9649. const multiDrawStarts = this._multiDrawStarts;
  9650. const multiDrawCounts = this._multiDrawCounts;
  9651. const drawRanges = this._drawRanges;
  9652. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9653. const indirectTexture = this._indirectTexture;
  9654. const indirectArray = indirectTexture.image.data;
  9655. // prepare the frustum in the local frame
  9656. if ( perObjectFrustumCulled ) {
  9657. _projScreenMatrix$3
  9658. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9659. .multiply( this.matrixWorld );
  9660. _frustum$1.setFromProjectionMatrix(
  9661. _projScreenMatrix$3,
  9662. renderer.coordinateSystem
  9663. );
  9664. }
  9665. let count = 0;
  9666. if ( this.sortObjects ) {
  9667. // get the camera position in the local frame
  9668. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9669. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9670. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9671. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9672. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9673. const geometryId = drawInfo[ i ].geometryIndex;
  9674. // get the bounds in world space
  9675. this.getMatrixAt( i, _matrix$1 );
  9676. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9677. // determine whether the batched geometry is within the frustum
  9678. let culled = false;
  9679. if ( perObjectFrustumCulled ) {
  9680. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9681. }
  9682. if ( ! culled ) {
  9683. // get the distance from camera used for sorting
  9684. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9685. _renderList.push( drawRanges[ geometryId ], z, i );
  9686. }
  9687. }
  9688. }
  9689. // Sort the draw ranges and prep for rendering
  9690. const list = _renderList.list;
  9691. const customSort = this.customSort;
  9692. if ( customSort === null ) {
  9693. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9694. } else {
  9695. customSort.call( this, list, camera );
  9696. }
  9697. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9698. const item = list[ i ];
  9699. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9700. multiDrawCounts[ count ] = item.count;
  9701. indirectArray[ count ] = item.index;
  9702. count ++;
  9703. }
  9704. _renderList.reset();
  9705. } else {
  9706. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9707. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9708. const geometryId = drawInfo[ i ].geometryIndex;
  9709. // determine whether the batched geometry is within the frustum
  9710. let culled = false;
  9711. if ( perObjectFrustumCulled ) {
  9712. // get the bounds in world space
  9713. this.getMatrixAt( i, _matrix$1 );
  9714. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9715. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9716. }
  9717. if ( ! culled ) {
  9718. const range = drawRanges[ geometryId ];
  9719. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9720. multiDrawCounts[ count ] = range.count;
  9721. indirectArray[ count ] = i;
  9722. count ++;
  9723. }
  9724. }
  9725. }
  9726. }
  9727. indirectTexture.needsUpdate = true;
  9728. this._multiDrawCount = count;
  9729. this._visibilityChanged = false;
  9730. }
  9731. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9732. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9733. }
  9734. }
  9735. class LineBasicMaterial extends Material {
  9736. constructor( parameters ) {
  9737. super();
  9738. this.isLineBasicMaterial = true;
  9739. this.type = 'LineBasicMaterial';
  9740. this.color = new Color( 0xffffff );
  9741. this.map = null;
  9742. this.linewidth = 1;
  9743. this.linecap = 'round';
  9744. this.linejoin = 'round';
  9745. this.fog = true;
  9746. this.setValues( parameters );
  9747. }
  9748. copy( source ) {
  9749. super.copy( source );
  9750. this.color.copy( source.color );
  9751. this.map = source.map;
  9752. this.linewidth = source.linewidth;
  9753. this.linecap = source.linecap;
  9754. this.linejoin = source.linejoin;
  9755. this.fog = source.fog;
  9756. return this;
  9757. }
  9758. }
  9759. const _vStart = /*@__PURE__*/ new Vector3();
  9760. const _vEnd = /*@__PURE__*/ new Vector3();
  9761. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9762. const _ray$1 = /*@__PURE__*/ new Ray();
  9763. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9764. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9765. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9766. class Line extends Object3D {
  9767. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9768. super();
  9769. this.isLine = true;
  9770. this.type = 'Line';
  9771. this.geometry = geometry;
  9772. this.material = material;
  9773. this.updateMorphTargets();
  9774. }
  9775. copy( source, recursive ) {
  9776. super.copy( source, recursive );
  9777. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9778. this.geometry = source.geometry;
  9779. return this;
  9780. }
  9781. computeLineDistances() {
  9782. const geometry = this.geometry;
  9783. // we assume non-indexed geometry
  9784. if ( geometry.index === null ) {
  9785. const positionAttribute = geometry.attributes.position;
  9786. const lineDistances = [ 0 ];
  9787. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  9788. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  9789. _vEnd.fromBufferAttribute( positionAttribute, i );
  9790. lineDistances[ i ] = lineDistances[ i - 1 ];
  9791. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  9792. }
  9793. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9794. } else {
  9795. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9796. }
  9797. return this;
  9798. }
  9799. raycast( raycaster, intersects ) {
  9800. const geometry = this.geometry;
  9801. const matrixWorld = this.matrixWorld;
  9802. const threshold = raycaster.params.Line.threshold;
  9803. const drawRange = geometry.drawRange;
  9804. // Checking boundingSphere distance to ray
  9805. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9806. _sphere$1.copy( geometry.boundingSphere );
  9807. _sphere$1.applyMatrix4( matrixWorld );
  9808. _sphere$1.radius += threshold;
  9809. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  9810. //
  9811. _inverseMatrix$1.copy( matrixWorld ).invert();
  9812. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  9813. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9814. const localThresholdSq = localThreshold * localThreshold;
  9815. const step = this.isLineSegments ? 2 : 1;
  9816. const index = geometry.index;
  9817. const attributes = geometry.attributes;
  9818. const positionAttribute = attributes.position;
  9819. if ( index !== null ) {
  9820. const start = Math.max( 0, drawRange.start );
  9821. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9822. for ( let i = start, l = end - 1; i < l; i += step ) {
  9823. const a = index.getX( i );
  9824. const b = index.getX( i + 1 );
  9825. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9826. if ( intersect ) {
  9827. intersects.push( intersect );
  9828. }
  9829. }
  9830. if ( this.isLineLoop ) {
  9831. const a = index.getX( end - 1 );
  9832. const b = index.getX( start );
  9833. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9834. if ( intersect ) {
  9835. intersects.push( intersect );
  9836. }
  9837. }
  9838. } else {
  9839. const start = Math.max( 0, drawRange.start );
  9840. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  9841. for ( let i = start, l = end - 1; i < l; i += step ) {
  9842. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  9843. if ( intersect ) {
  9844. intersects.push( intersect );
  9845. }
  9846. }
  9847. if ( this.isLineLoop ) {
  9848. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  9849. if ( intersect ) {
  9850. intersects.push( intersect );
  9851. }
  9852. }
  9853. }
  9854. }
  9855. updateMorphTargets() {
  9856. const geometry = this.geometry;
  9857. const morphAttributes = geometry.morphAttributes;
  9858. const keys = Object.keys( morphAttributes );
  9859. if ( keys.length > 0 ) {
  9860. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  9861. if ( morphAttribute !== undefined ) {
  9862. this.morphTargetInfluences = [];
  9863. this.morphTargetDictionary = {};
  9864. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9865. const name = morphAttribute[ m ].name || String( m );
  9866. this.morphTargetInfluences.push( 0 );
  9867. this.morphTargetDictionary[ name ] = m;
  9868. }
  9869. }
  9870. }
  9871. }
  9872. }
  9873. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  9874. const positionAttribute = object.geometry.attributes.position;
  9875. _vStart.fromBufferAttribute( positionAttribute, a );
  9876. _vEnd.fromBufferAttribute( positionAttribute, b );
  9877. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  9878. if ( distSq > thresholdSq ) return;
  9879. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  9880. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  9881. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9882. return {
  9883. distance: distance,
  9884. // What do we want? intersection point on the ray or on the segment??
  9885. // point: raycaster.ray.at( distance ),
  9886. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  9887. index: a,
  9888. face: null,
  9889. faceIndex: null,
  9890. object: object
  9891. };
  9892. }
  9893. const _start = /*@__PURE__*/ new Vector3();
  9894. const _end = /*@__PURE__*/ new Vector3();
  9895. class LineSegments extends Line {
  9896. constructor( geometry, material ) {
  9897. super( geometry, material );
  9898. this.isLineSegments = true;
  9899. this.type = 'LineSegments';
  9900. }
  9901. computeLineDistances() {
  9902. const geometry = this.geometry;
  9903. // we assume non-indexed geometry
  9904. if ( geometry.index === null ) {
  9905. const positionAttribute = geometry.attributes.position;
  9906. const lineDistances = [];
  9907. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  9908. _start.fromBufferAttribute( positionAttribute, i );
  9909. _end.fromBufferAttribute( positionAttribute, i + 1 );
  9910. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  9911. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  9912. }
  9913. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9914. } else {
  9915. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9916. }
  9917. return this;
  9918. }
  9919. }
  9920. class LineLoop extends Line {
  9921. constructor( geometry, material ) {
  9922. super( geometry, material );
  9923. this.isLineLoop = true;
  9924. this.type = 'LineLoop';
  9925. }
  9926. }
  9927. class PointsMaterial extends Material {
  9928. constructor( parameters ) {
  9929. super();
  9930. this.isPointsMaterial = true;
  9931. this.type = 'PointsMaterial';
  9932. this.color = new Color( 0xffffff );
  9933. this.map = null;
  9934. this.alphaMap = null;
  9935. this.size = 1;
  9936. this.sizeAttenuation = true;
  9937. this.fog = true;
  9938. this.setValues( parameters );
  9939. }
  9940. copy( source ) {
  9941. super.copy( source );
  9942. this.color.copy( source.color );
  9943. this.map = source.map;
  9944. this.alphaMap = source.alphaMap;
  9945. this.size = source.size;
  9946. this.sizeAttenuation = source.sizeAttenuation;
  9947. this.fog = source.fog;
  9948. return this;
  9949. }
  9950. }
  9951. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  9952. const _ray = /*@__PURE__*/ new Ray();
  9953. const _sphere = /*@__PURE__*/ new Sphere();
  9954. const _position$2 = /*@__PURE__*/ new Vector3();
  9955. class Points extends Object3D {
  9956. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  9957. super();
  9958. this.isPoints = true;
  9959. this.type = 'Points';
  9960. this.geometry = geometry;
  9961. this.material = material;
  9962. this.updateMorphTargets();
  9963. }
  9964. copy( source, recursive ) {
  9965. super.copy( source, recursive );
  9966. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9967. this.geometry = source.geometry;
  9968. return this;
  9969. }
  9970. raycast( raycaster, intersects ) {
  9971. const geometry = this.geometry;
  9972. const matrixWorld = this.matrixWorld;
  9973. const threshold = raycaster.params.Points.threshold;
  9974. const drawRange = geometry.drawRange;
  9975. // Checking boundingSphere distance to ray
  9976. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9977. _sphere.copy( geometry.boundingSphere );
  9978. _sphere.applyMatrix4( matrixWorld );
  9979. _sphere.radius += threshold;
  9980. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  9981. //
  9982. _inverseMatrix.copy( matrixWorld ).invert();
  9983. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  9984. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9985. const localThresholdSq = localThreshold * localThreshold;
  9986. const index = geometry.index;
  9987. const attributes = geometry.attributes;
  9988. const positionAttribute = attributes.position;
  9989. if ( index !== null ) {
  9990. const start = Math.max( 0, drawRange.start );
  9991. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9992. for ( let i = start, il = end; i < il; i ++ ) {
  9993. const a = index.getX( i );
  9994. _position$2.fromBufferAttribute( positionAttribute, a );
  9995. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  9996. }
  9997. } else {
  9998. const start = Math.max( 0, drawRange.start );
  9999. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10000. for ( let i = start, l = end; i < l; i ++ ) {
  10001. _position$2.fromBufferAttribute( positionAttribute, i );
  10002. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10003. }
  10004. }
  10005. }
  10006. updateMorphTargets() {
  10007. const geometry = this.geometry;
  10008. const morphAttributes = geometry.morphAttributes;
  10009. const keys = Object.keys( morphAttributes );
  10010. if ( keys.length > 0 ) {
  10011. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10012. if ( morphAttribute !== undefined ) {
  10013. this.morphTargetInfluences = [];
  10014. this.morphTargetDictionary = {};
  10015. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10016. const name = morphAttribute[ m ].name || String( m );
  10017. this.morphTargetInfluences.push( 0 );
  10018. this.morphTargetDictionary[ name ] = m;
  10019. }
  10020. }
  10021. }
  10022. }
  10023. }
  10024. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10025. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10026. if ( rayPointDistanceSq < localThresholdSq ) {
  10027. const intersectPoint = new Vector3();
  10028. _ray.closestPointToPoint( point, intersectPoint );
  10029. intersectPoint.applyMatrix4( matrixWorld );
  10030. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10031. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10032. intersects.push( {
  10033. distance: distance,
  10034. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10035. point: intersectPoint,
  10036. index: index,
  10037. face: null,
  10038. object: object
  10039. } );
  10040. }
  10041. }
  10042. class Group extends Object3D {
  10043. constructor() {
  10044. super();
  10045. this.isGroup = true;
  10046. this.type = 'Group';
  10047. }
  10048. }
  10049. class VideoTexture extends Texture {
  10050. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10051. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10052. this.isVideoTexture = true;
  10053. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10054. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10055. this.generateMipmaps = false;
  10056. const scope = this;
  10057. function updateVideo() {
  10058. scope.needsUpdate = true;
  10059. video.requestVideoFrameCallback( updateVideo );
  10060. }
  10061. if ( 'requestVideoFrameCallback' in video ) {
  10062. video.requestVideoFrameCallback( updateVideo );
  10063. }
  10064. }
  10065. clone() {
  10066. return new this.constructor( this.image ).copy( this );
  10067. }
  10068. update() {
  10069. const video = this.image;
  10070. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10071. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10072. this.needsUpdate = true;
  10073. }
  10074. }
  10075. }
  10076. class FramebufferTexture extends Texture {
  10077. constructor( width, height ) {
  10078. super( { width, height } );
  10079. this.isFramebufferTexture = true;
  10080. this.magFilter = NearestFilter;
  10081. this.minFilter = NearestFilter;
  10082. this.generateMipmaps = false;
  10083. this.needsUpdate = true;
  10084. }
  10085. }
  10086. class CompressedTexture extends Texture {
  10087. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10088. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10089. this.isCompressedTexture = true;
  10090. this.image = { width: width, height: height };
  10091. this.mipmaps = mipmaps;
  10092. // no flipping for cube textures
  10093. // (also flipping doesn't work for compressed textures )
  10094. this.flipY = false;
  10095. // can't generate mipmaps for compressed textures
  10096. // mips must be embedded in DDS files
  10097. this.generateMipmaps = false;
  10098. }
  10099. }
  10100. class CompressedArrayTexture extends CompressedTexture {
  10101. constructor( mipmaps, width, height, depth, format, type ) {
  10102. super( mipmaps, width, height, format, type );
  10103. this.isCompressedArrayTexture = true;
  10104. this.image.depth = depth;
  10105. this.wrapR = ClampToEdgeWrapping;
  10106. this.layerUpdates = new Set();
  10107. }
  10108. addLayerUpdate( layerIndex ) {
  10109. this.layerUpdates.add( layerIndex );
  10110. }
  10111. clearLayerUpdates() {
  10112. this.layerUpdates.clear();
  10113. }
  10114. }
  10115. class CompressedCubeTexture extends CompressedTexture {
  10116. constructor( images, format, type ) {
  10117. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10118. this.isCompressedCubeTexture = true;
  10119. this.isCubeTexture = true;
  10120. this.image = images;
  10121. }
  10122. }
  10123. class CanvasTexture extends Texture {
  10124. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10125. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10126. this.isCanvasTexture = true;
  10127. this.needsUpdate = true;
  10128. }
  10129. }
  10130. class DepthTexture extends Texture {
  10131. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10132. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10133. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10134. }
  10135. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10136. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10137. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10138. this.isDepthTexture = true;
  10139. this.image = { width: width, height: height };
  10140. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10141. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10142. this.flipY = false;
  10143. this.generateMipmaps = false;
  10144. this.compareFunction = null;
  10145. }
  10146. copy( source ) {
  10147. super.copy( source );
  10148. this.compareFunction = source.compareFunction;
  10149. return this;
  10150. }
  10151. toJSON( meta ) {
  10152. const data = super.toJSON( meta );
  10153. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10154. return data;
  10155. }
  10156. }
  10157. /**
  10158. * Extensible curve object.
  10159. *
  10160. * Some common of curve methods:
  10161. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10162. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10163. * .getPoints(), .getSpacedPoints()
  10164. * .getLength()
  10165. * .updateArcLengths()
  10166. *
  10167. * This following curves inherit from THREE.Curve:
  10168. *
  10169. * -- 2D curves --
  10170. * THREE.ArcCurve
  10171. * THREE.CubicBezierCurve
  10172. * THREE.EllipseCurve
  10173. * THREE.LineCurve
  10174. * THREE.QuadraticBezierCurve
  10175. * THREE.SplineCurve
  10176. *
  10177. * -- 3D curves --
  10178. * THREE.CatmullRomCurve3
  10179. * THREE.CubicBezierCurve3
  10180. * THREE.LineCurve3
  10181. * THREE.QuadraticBezierCurve3
  10182. *
  10183. * A series of curves can be represented as a THREE.CurvePath.
  10184. *
  10185. **/
  10186. class Curve {
  10187. constructor() {
  10188. this.type = 'Curve';
  10189. this.arcLengthDivisions = 200;
  10190. }
  10191. // Virtual base class method to overwrite and implement in subclasses
  10192. // - t [0 .. 1]
  10193. getPoint( /* t, optionalTarget */ ) {
  10194. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10195. return null;
  10196. }
  10197. // Get point at relative position in curve according to arc length
  10198. // - u [0 .. 1]
  10199. getPointAt( u, optionalTarget ) {
  10200. const t = this.getUtoTmapping( u );
  10201. return this.getPoint( t, optionalTarget );
  10202. }
  10203. // Get sequence of points using getPoint( t )
  10204. getPoints( divisions = 5 ) {
  10205. const points = [];
  10206. for ( let d = 0; d <= divisions; d ++ ) {
  10207. points.push( this.getPoint( d / divisions ) );
  10208. }
  10209. return points;
  10210. }
  10211. // Get sequence of points using getPointAt( u )
  10212. getSpacedPoints( divisions = 5 ) {
  10213. const points = [];
  10214. for ( let d = 0; d <= divisions; d ++ ) {
  10215. points.push( this.getPointAt( d / divisions ) );
  10216. }
  10217. return points;
  10218. }
  10219. // Get total curve arc length
  10220. getLength() {
  10221. const lengths = this.getLengths();
  10222. return lengths[ lengths.length - 1 ];
  10223. }
  10224. // Get list of cumulative segment lengths
  10225. getLengths( divisions = this.arcLengthDivisions ) {
  10226. if ( this.cacheArcLengths &&
  10227. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10228. ! this.needsUpdate ) {
  10229. return this.cacheArcLengths;
  10230. }
  10231. this.needsUpdate = false;
  10232. const cache = [];
  10233. let current, last = this.getPoint( 0 );
  10234. let sum = 0;
  10235. cache.push( 0 );
  10236. for ( let p = 1; p <= divisions; p ++ ) {
  10237. current = this.getPoint( p / divisions );
  10238. sum += current.distanceTo( last );
  10239. cache.push( sum );
  10240. last = current;
  10241. }
  10242. this.cacheArcLengths = cache;
  10243. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10244. }
  10245. updateArcLengths() {
  10246. this.needsUpdate = true;
  10247. this.getLengths();
  10248. }
  10249. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10250. getUtoTmapping( u, distance ) {
  10251. const arcLengths = this.getLengths();
  10252. let i = 0;
  10253. const il = arcLengths.length;
  10254. let targetArcLength; // The targeted u distance value to get
  10255. if ( distance ) {
  10256. targetArcLength = distance;
  10257. } else {
  10258. targetArcLength = u * arcLengths[ il - 1 ];
  10259. }
  10260. // binary search for the index with largest value smaller than target u distance
  10261. let low = 0, high = il - 1, comparison;
  10262. while ( low <= high ) {
  10263. 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
  10264. comparison = arcLengths[ i ] - targetArcLength;
  10265. if ( comparison < 0 ) {
  10266. low = i + 1;
  10267. } else if ( comparison > 0 ) {
  10268. high = i - 1;
  10269. } else {
  10270. high = i;
  10271. break;
  10272. // DONE
  10273. }
  10274. }
  10275. i = high;
  10276. if ( arcLengths[ i ] === targetArcLength ) {
  10277. return i / ( il - 1 );
  10278. }
  10279. // we could get finer grain at lengths, or use simple interpolation between two points
  10280. const lengthBefore = arcLengths[ i ];
  10281. const lengthAfter = arcLengths[ i + 1 ];
  10282. const segmentLength = lengthAfter - lengthBefore;
  10283. // determine where we are between the 'before' and 'after' points
  10284. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10285. // add that fractional amount to t
  10286. const t = ( i + segmentFraction ) / ( il - 1 );
  10287. return t;
  10288. }
  10289. // Returns a unit vector tangent at t
  10290. // In case any sub curve does not implement its tangent derivation,
  10291. // 2 points a small delta apart will be used to find its gradient
  10292. // which seems to give a reasonable approximation
  10293. getTangent( t, optionalTarget ) {
  10294. const delta = 0.0001;
  10295. let t1 = t - delta;
  10296. let t2 = t + delta;
  10297. // Capping in case of danger
  10298. if ( t1 < 0 ) t1 = 0;
  10299. if ( t2 > 1 ) t2 = 1;
  10300. const pt1 = this.getPoint( t1 );
  10301. const pt2 = this.getPoint( t2 );
  10302. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10303. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10304. return tangent;
  10305. }
  10306. getTangentAt( u, optionalTarget ) {
  10307. const t = this.getUtoTmapping( u );
  10308. return this.getTangent( t, optionalTarget );
  10309. }
  10310. computeFrenetFrames( segments, closed ) {
  10311. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10312. const normal = new Vector3();
  10313. const tangents = [];
  10314. const normals = [];
  10315. const binormals = [];
  10316. const vec = new Vector3();
  10317. const mat = new Matrix4();
  10318. // compute the tangent vectors for each segment on the curve
  10319. for ( let i = 0; i <= segments; i ++ ) {
  10320. const u = i / segments;
  10321. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10322. }
  10323. // select an initial normal vector perpendicular to the first tangent vector,
  10324. // and in the direction of the minimum tangent xyz component
  10325. normals[ 0 ] = new Vector3();
  10326. binormals[ 0 ] = new Vector3();
  10327. let min = Number.MAX_VALUE;
  10328. const tx = Math.abs( tangents[ 0 ].x );
  10329. const ty = Math.abs( tangents[ 0 ].y );
  10330. const tz = Math.abs( tangents[ 0 ].z );
  10331. if ( tx <= min ) {
  10332. min = tx;
  10333. normal.set( 1, 0, 0 );
  10334. }
  10335. if ( ty <= min ) {
  10336. min = ty;
  10337. normal.set( 0, 1, 0 );
  10338. }
  10339. if ( tz <= min ) {
  10340. normal.set( 0, 0, 1 );
  10341. }
  10342. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10343. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10344. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10345. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10346. for ( let i = 1; i <= segments; i ++ ) {
  10347. normals[ i ] = normals[ i - 1 ].clone();
  10348. binormals[ i ] = binormals[ i - 1 ].clone();
  10349. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10350. if ( vec.length() > Number.EPSILON ) {
  10351. vec.normalize();
  10352. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10353. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10354. }
  10355. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10356. }
  10357. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10358. if ( closed === true ) {
  10359. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10360. theta /= segments;
  10361. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10362. theta = - theta;
  10363. }
  10364. for ( let i = 1; i <= segments; i ++ ) {
  10365. // twist a little...
  10366. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10367. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10368. }
  10369. }
  10370. return {
  10371. tangents: tangents,
  10372. normals: normals,
  10373. binormals: binormals
  10374. };
  10375. }
  10376. clone() {
  10377. return new this.constructor().copy( this );
  10378. }
  10379. copy( source ) {
  10380. this.arcLengthDivisions = source.arcLengthDivisions;
  10381. return this;
  10382. }
  10383. toJSON() {
  10384. const data = {
  10385. metadata: {
  10386. version: 4.6,
  10387. type: 'Curve',
  10388. generator: 'Curve.toJSON'
  10389. }
  10390. };
  10391. data.arcLengthDivisions = this.arcLengthDivisions;
  10392. data.type = this.type;
  10393. return data;
  10394. }
  10395. fromJSON( json ) {
  10396. this.arcLengthDivisions = json.arcLengthDivisions;
  10397. return this;
  10398. }
  10399. }
  10400. class EllipseCurve extends Curve {
  10401. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10402. super();
  10403. this.isEllipseCurve = true;
  10404. this.type = 'EllipseCurve';
  10405. this.aX = aX;
  10406. this.aY = aY;
  10407. this.xRadius = xRadius;
  10408. this.yRadius = yRadius;
  10409. this.aStartAngle = aStartAngle;
  10410. this.aEndAngle = aEndAngle;
  10411. this.aClockwise = aClockwise;
  10412. this.aRotation = aRotation;
  10413. }
  10414. getPoint( t, optionalTarget = new Vector2() ) {
  10415. const point = optionalTarget;
  10416. const twoPi = Math.PI * 2;
  10417. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10418. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10419. // ensures that deltaAngle is 0 .. 2 PI
  10420. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10421. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10422. if ( deltaAngle < Number.EPSILON ) {
  10423. if ( samePoints ) {
  10424. deltaAngle = 0;
  10425. } else {
  10426. deltaAngle = twoPi;
  10427. }
  10428. }
  10429. if ( this.aClockwise === true && ! samePoints ) {
  10430. if ( deltaAngle === twoPi ) {
  10431. deltaAngle = - twoPi;
  10432. } else {
  10433. deltaAngle = deltaAngle - twoPi;
  10434. }
  10435. }
  10436. const angle = this.aStartAngle + t * deltaAngle;
  10437. let x = this.aX + this.xRadius * Math.cos( angle );
  10438. let y = this.aY + this.yRadius * Math.sin( angle );
  10439. if ( this.aRotation !== 0 ) {
  10440. const cos = Math.cos( this.aRotation );
  10441. const sin = Math.sin( this.aRotation );
  10442. const tx = x - this.aX;
  10443. const ty = y - this.aY;
  10444. // Rotate the point about the center of the ellipse.
  10445. x = tx * cos - ty * sin + this.aX;
  10446. y = tx * sin + ty * cos + this.aY;
  10447. }
  10448. return point.set( x, y );
  10449. }
  10450. copy( source ) {
  10451. super.copy( source );
  10452. this.aX = source.aX;
  10453. this.aY = source.aY;
  10454. this.xRadius = source.xRadius;
  10455. this.yRadius = source.yRadius;
  10456. this.aStartAngle = source.aStartAngle;
  10457. this.aEndAngle = source.aEndAngle;
  10458. this.aClockwise = source.aClockwise;
  10459. this.aRotation = source.aRotation;
  10460. return this;
  10461. }
  10462. toJSON() {
  10463. const data = super.toJSON();
  10464. data.aX = this.aX;
  10465. data.aY = this.aY;
  10466. data.xRadius = this.xRadius;
  10467. data.yRadius = this.yRadius;
  10468. data.aStartAngle = this.aStartAngle;
  10469. data.aEndAngle = this.aEndAngle;
  10470. data.aClockwise = this.aClockwise;
  10471. data.aRotation = this.aRotation;
  10472. return data;
  10473. }
  10474. fromJSON( json ) {
  10475. super.fromJSON( json );
  10476. this.aX = json.aX;
  10477. this.aY = json.aY;
  10478. this.xRadius = json.xRadius;
  10479. this.yRadius = json.yRadius;
  10480. this.aStartAngle = json.aStartAngle;
  10481. this.aEndAngle = json.aEndAngle;
  10482. this.aClockwise = json.aClockwise;
  10483. this.aRotation = json.aRotation;
  10484. return this;
  10485. }
  10486. }
  10487. class ArcCurve extends EllipseCurve {
  10488. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10489. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10490. this.isArcCurve = true;
  10491. this.type = 'ArcCurve';
  10492. }
  10493. }
  10494. /**
  10495. * Centripetal CatmullRom Curve - which is useful for avoiding
  10496. * cusps and self-intersections in non-uniform catmull rom curves.
  10497. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10498. *
  10499. * curve.type accepts centripetal(default), chordal and catmullrom
  10500. * curve.tension is used for catmullrom which defaults to 0.5
  10501. */
  10502. /*
  10503. Based on an optimized c++ solution in
  10504. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10505. - http://ideone.com/NoEbVM
  10506. This CubicPoly class could be used for reusing some variables and calculations,
  10507. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10508. which can be placed in CurveUtils.
  10509. */
  10510. function CubicPoly() {
  10511. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10512. /*
  10513. * Compute coefficients for a cubic polynomial
  10514. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10515. * such that
  10516. * p(0) = x0, p(1) = x1
  10517. * and
  10518. * p'(0) = t0, p'(1) = t1.
  10519. */
  10520. function init( x0, x1, t0, t1 ) {
  10521. c0 = x0;
  10522. c1 = t0;
  10523. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10524. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10525. }
  10526. return {
  10527. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10528. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10529. },
  10530. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10531. // compute tangents when parameterized in [t1,t2]
  10532. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10533. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10534. // rescale tangents for parametrization in [0,1]
  10535. t1 *= dt1;
  10536. t2 *= dt1;
  10537. init( x1, x2, t1, t2 );
  10538. },
  10539. calc: function ( t ) {
  10540. const t2 = t * t;
  10541. const t3 = t2 * t;
  10542. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10543. }
  10544. };
  10545. }
  10546. //
  10547. const tmp = /*@__PURE__*/ new Vector3();
  10548. const px = /*@__PURE__*/ new CubicPoly();
  10549. const py = /*@__PURE__*/ new CubicPoly();
  10550. const pz = /*@__PURE__*/ new CubicPoly();
  10551. class CatmullRomCurve3 extends Curve {
  10552. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10553. super();
  10554. this.isCatmullRomCurve3 = true;
  10555. this.type = 'CatmullRomCurve3';
  10556. this.points = points;
  10557. this.closed = closed;
  10558. this.curveType = curveType;
  10559. this.tension = tension;
  10560. }
  10561. getPoint( t, optionalTarget = new Vector3() ) {
  10562. const point = optionalTarget;
  10563. const points = this.points;
  10564. const l = points.length;
  10565. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10566. let intPoint = Math.floor( p );
  10567. let weight = p - intPoint;
  10568. if ( this.closed ) {
  10569. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10570. } else if ( weight === 0 && intPoint === l - 1 ) {
  10571. intPoint = l - 2;
  10572. weight = 1;
  10573. }
  10574. let p0, p3; // 4 points (p1 & p2 defined below)
  10575. if ( this.closed || intPoint > 0 ) {
  10576. p0 = points[ ( intPoint - 1 ) % l ];
  10577. } else {
  10578. // extrapolate first point
  10579. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10580. p0 = tmp;
  10581. }
  10582. const p1 = points[ intPoint % l ];
  10583. const p2 = points[ ( intPoint + 1 ) % l ];
  10584. if ( this.closed || intPoint + 2 < l ) {
  10585. p3 = points[ ( intPoint + 2 ) % l ];
  10586. } else {
  10587. // extrapolate last point
  10588. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10589. p3 = tmp;
  10590. }
  10591. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10592. // init Centripetal / Chordal Catmull-Rom
  10593. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10594. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10595. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10596. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10597. // safety check for repeated points
  10598. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10599. if ( dt0 < 1e-4 ) dt0 = dt1;
  10600. if ( dt2 < 1e-4 ) dt2 = dt1;
  10601. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10602. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10603. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10604. } else if ( this.curveType === 'catmullrom' ) {
  10605. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10606. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10607. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10608. }
  10609. point.set(
  10610. px.calc( weight ),
  10611. py.calc( weight ),
  10612. pz.calc( weight )
  10613. );
  10614. return point;
  10615. }
  10616. copy( source ) {
  10617. super.copy( source );
  10618. this.points = [];
  10619. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10620. const point = source.points[ i ];
  10621. this.points.push( point.clone() );
  10622. }
  10623. this.closed = source.closed;
  10624. this.curveType = source.curveType;
  10625. this.tension = source.tension;
  10626. return this;
  10627. }
  10628. toJSON() {
  10629. const data = super.toJSON();
  10630. data.points = [];
  10631. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10632. const point = this.points[ i ];
  10633. data.points.push( point.toArray() );
  10634. }
  10635. data.closed = this.closed;
  10636. data.curveType = this.curveType;
  10637. data.tension = this.tension;
  10638. return data;
  10639. }
  10640. fromJSON( json ) {
  10641. super.fromJSON( json );
  10642. this.points = [];
  10643. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10644. const point = json.points[ i ];
  10645. this.points.push( new Vector3().fromArray( point ) );
  10646. }
  10647. this.closed = json.closed;
  10648. this.curveType = json.curveType;
  10649. this.tension = json.tension;
  10650. return this;
  10651. }
  10652. }
  10653. /**
  10654. * Bezier Curves formulas obtained from
  10655. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10656. */
  10657. function CatmullRom( t, p0, p1, p2, p3 ) {
  10658. const v0 = ( p2 - p0 ) * 0.5;
  10659. const v1 = ( p3 - p1 ) * 0.5;
  10660. const t2 = t * t;
  10661. const t3 = t * t2;
  10662. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10663. }
  10664. //
  10665. function QuadraticBezierP0( t, p ) {
  10666. const k = 1 - t;
  10667. return k * k * p;
  10668. }
  10669. function QuadraticBezierP1( t, p ) {
  10670. return 2 * ( 1 - t ) * t * p;
  10671. }
  10672. function QuadraticBezierP2( t, p ) {
  10673. return t * t * p;
  10674. }
  10675. function QuadraticBezier( t, p0, p1, p2 ) {
  10676. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10677. QuadraticBezierP2( t, p2 );
  10678. }
  10679. //
  10680. function CubicBezierP0( t, p ) {
  10681. const k = 1 - t;
  10682. return k * k * k * p;
  10683. }
  10684. function CubicBezierP1( t, p ) {
  10685. const k = 1 - t;
  10686. return 3 * k * k * t * p;
  10687. }
  10688. function CubicBezierP2( t, p ) {
  10689. return 3 * ( 1 - t ) * t * t * p;
  10690. }
  10691. function CubicBezierP3( t, p ) {
  10692. return t * t * t * p;
  10693. }
  10694. function CubicBezier( t, p0, p1, p2, p3 ) {
  10695. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10696. CubicBezierP3( t, p3 );
  10697. }
  10698. class CubicBezierCurve extends Curve {
  10699. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10700. super();
  10701. this.isCubicBezierCurve = true;
  10702. this.type = 'CubicBezierCurve';
  10703. this.v0 = v0;
  10704. this.v1 = v1;
  10705. this.v2 = v2;
  10706. this.v3 = v3;
  10707. }
  10708. getPoint( t, optionalTarget = new Vector2() ) {
  10709. const point = optionalTarget;
  10710. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10711. point.set(
  10712. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10713. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10714. );
  10715. return point;
  10716. }
  10717. copy( source ) {
  10718. super.copy( source );
  10719. this.v0.copy( source.v0 );
  10720. this.v1.copy( source.v1 );
  10721. this.v2.copy( source.v2 );
  10722. this.v3.copy( source.v3 );
  10723. return this;
  10724. }
  10725. toJSON() {
  10726. const data = super.toJSON();
  10727. data.v0 = this.v0.toArray();
  10728. data.v1 = this.v1.toArray();
  10729. data.v2 = this.v2.toArray();
  10730. data.v3 = this.v3.toArray();
  10731. return data;
  10732. }
  10733. fromJSON( json ) {
  10734. super.fromJSON( json );
  10735. this.v0.fromArray( json.v0 );
  10736. this.v1.fromArray( json.v1 );
  10737. this.v2.fromArray( json.v2 );
  10738. this.v3.fromArray( json.v3 );
  10739. return this;
  10740. }
  10741. }
  10742. class CubicBezierCurve3 extends Curve {
  10743. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10744. super();
  10745. this.isCubicBezierCurve3 = true;
  10746. this.type = 'CubicBezierCurve3';
  10747. this.v0 = v0;
  10748. this.v1 = v1;
  10749. this.v2 = v2;
  10750. this.v3 = v3;
  10751. }
  10752. getPoint( t, optionalTarget = new Vector3() ) {
  10753. const point = optionalTarget;
  10754. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10755. point.set(
  10756. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10757. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10758. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10759. );
  10760. return point;
  10761. }
  10762. copy( source ) {
  10763. super.copy( source );
  10764. this.v0.copy( source.v0 );
  10765. this.v1.copy( source.v1 );
  10766. this.v2.copy( source.v2 );
  10767. this.v3.copy( source.v3 );
  10768. return this;
  10769. }
  10770. toJSON() {
  10771. const data = super.toJSON();
  10772. data.v0 = this.v0.toArray();
  10773. data.v1 = this.v1.toArray();
  10774. data.v2 = this.v2.toArray();
  10775. data.v3 = this.v3.toArray();
  10776. return data;
  10777. }
  10778. fromJSON( json ) {
  10779. super.fromJSON( json );
  10780. this.v0.fromArray( json.v0 );
  10781. this.v1.fromArray( json.v1 );
  10782. this.v2.fromArray( json.v2 );
  10783. this.v3.fromArray( json.v3 );
  10784. return this;
  10785. }
  10786. }
  10787. class LineCurve extends Curve {
  10788. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  10789. super();
  10790. this.isLineCurve = true;
  10791. this.type = 'LineCurve';
  10792. this.v1 = v1;
  10793. this.v2 = v2;
  10794. }
  10795. getPoint( t, optionalTarget = new Vector2() ) {
  10796. const point = optionalTarget;
  10797. if ( t === 1 ) {
  10798. point.copy( this.v2 );
  10799. } else {
  10800. point.copy( this.v2 ).sub( this.v1 );
  10801. point.multiplyScalar( t ).add( this.v1 );
  10802. }
  10803. return point;
  10804. }
  10805. // Line curve is linear, so we can overwrite default getPointAt
  10806. getPointAt( u, optionalTarget ) {
  10807. return this.getPoint( u, optionalTarget );
  10808. }
  10809. getTangent( t, optionalTarget = new Vector2() ) {
  10810. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10811. }
  10812. getTangentAt( u, optionalTarget ) {
  10813. return this.getTangent( u, optionalTarget );
  10814. }
  10815. copy( source ) {
  10816. super.copy( source );
  10817. this.v1.copy( source.v1 );
  10818. this.v2.copy( source.v2 );
  10819. return this;
  10820. }
  10821. toJSON() {
  10822. const data = super.toJSON();
  10823. data.v1 = this.v1.toArray();
  10824. data.v2 = this.v2.toArray();
  10825. return data;
  10826. }
  10827. fromJSON( json ) {
  10828. super.fromJSON( json );
  10829. this.v1.fromArray( json.v1 );
  10830. this.v2.fromArray( json.v2 );
  10831. return this;
  10832. }
  10833. }
  10834. class LineCurve3 extends Curve {
  10835. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  10836. super();
  10837. this.isLineCurve3 = true;
  10838. this.type = 'LineCurve3';
  10839. this.v1 = v1;
  10840. this.v2 = v2;
  10841. }
  10842. getPoint( t, optionalTarget = new Vector3() ) {
  10843. const point = optionalTarget;
  10844. if ( t === 1 ) {
  10845. point.copy( this.v2 );
  10846. } else {
  10847. point.copy( this.v2 ).sub( this.v1 );
  10848. point.multiplyScalar( t ).add( this.v1 );
  10849. }
  10850. return point;
  10851. }
  10852. // Line curve is linear, so we can overwrite default getPointAt
  10853. getPointAt( u, optionalTarget ) {
  10854. return this.getPoint( u, optionalTarget );
  10855. }
  10856. getTangent( t, optionalTarget = new Vector3() ) {
  10857. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10858. }
  10859. getTangentAt( u, optionalTarget ) {
  10860. return this.getTangent( u, optionalTarget );
  10861. }
  10862. copy( source ) {
  10863. super.copy( source );
  10864. this.v1.copy( source.v1 );
  10865. this.v2.copy( source.v2 );
  10866. return this;
  10867. }
  10868. toJSON() {
  10869. const data = super.toJSON();
  10870. data.v1 = this.v1.toArray();
  10871. data.v2 = this.v2.toArray();
  10872. return data;
  10873. }
  10874. fromJSON( json ) {
  10875. super.fromJSON( json );
  10876. this.v1.fromArray( json.v1 );
  10877. this.v2.fromArray( json.v2 );
  10878. return this;
  10879. }
  10880. }
  10881. class QuadraticBezierCurve extends Curve {
  10882. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  10883. super();
  10884. this.isQuadraticBezierCurve = true;
  10885. this.type = 'QuadraticBezierCurve';
  10886. this.v0 = v0;
  10887. this.v1 = v1;
  10888. this.v2 = v2;
  10889. }
  10890. getPoint( t, optionalTarget = new Vector2() ) {
  10891. const point = optionalTarget;
  10892. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10893. point.set(
  10894. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10895. QuadraticBezier( t, v0.y, v1.y, v2.y )
  10896. );
  10897. return point;
  10898. }
  10899. copy( source ) {
  10900. super.copy( source );
  10901. this.v0.copy( source.v0 );
  10902. this.v1.copy( source.v1 );
  10903. this.v2.copy( source.v2 );
  10904. return this;
  10905. }
  10906. toJSON() {
  10907. const data = super.toJSON();
  10908. data.v0 = this.v0.toArray();
  10909. data.v1 = this.v1.toArray();
  10910. data.v2 = this.v2.toArray();
  10911. return data;
  10912. }
  10913. fromJSON( json ) {
  10914. super.fromJSON( json );
  10915. this.v0.fromArray( json.v0 );
  10916. this.v1.fromArray( json.v1 );
  10917. this.v2.fromArray( json.v2 );
  10918. return this;
  10919. }
  10920. }
  10921. class QuadraticBezierCurve3 extends Curve {
  10922. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  10923. super();
  10924. this.isQuadraticBezierCurve3 = true;
  10925. this.type = 'QuadraticBezierCurve3';
  10926. this.v0 = v0;
  10927. this.v1 = v1;
  10928. this.v2 = v2;
  10929. }
  10930. getPoint( t, optionalTarget = new Vector3() ) {
  10931. const point = optionalTarget;
  10932. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10933. point.set(
  10934. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10935. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  10936. QuadraticBezier( t, v0.z, v1.z, v2.z )
  10937. );
  10938. return point;
  10939. }
  10940. copy( source ) {
  10941. super.copy( source );
  10942. this.v0.copy( source.v0 );
  10943. this.v1.copy( source.v1 );
  10944. this.v2.copy( source.v2 );
  10945. return this;
  10946. }
  10947. toJSON() {
  10948. const data = super.toJSON();
  10949. data.v0 = this.v0.toArray();
  10950. data.v1 = this.v1.toArray();
  10951. data.v2 = this.v2.toArray();
  10952. return data;
  10953. }
  10954. fromJSON( json ) {
  10955. super.fromJSON( json );
  10956. this.v0.fromArray( json.v0 );
  10957. this.v1.fromArray( json.v1 );
  10958. this.v2.fromArray( json.v2 );
  10959. return this;
  10960. }
  10961. }
  10962. class SplineCurve extends Curve {
  10963. constructor( points = [] ) {
  10964. super();
  10965. this.isSplineCurve = true;
  10966. this.type = 'SplineCurve';
  10967. this.points = points;
  10968. }
  10969. getPoint( t, optionalTarget = new Vector2() ) {
  10970. const point = optionalTarget;
  10971. const points = this.points;
  10972. const p = ( points.length - 1 ) * t;
  10973. const intPoint = Math.floor( p );
  10974. const weight = p - intPoint;
  10975. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  10976. const p1 = points[ intPoint ];
  10977. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  10978. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  10979. point.set(
  10980. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  10981. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  10982. );
  10983. return point;
  10984. }
  10985. copy( source ) {
  10986. super.copy( source );
  10987. this.points = [];
  10988. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10989. const point = source.points[ i ];
  10990. this.points.push( point.clone() );
  10991. }
  10992. return this;
  10993. }
  10994. toJSON() {
  10995. const data = super.toJSON();
  10996. data.points = [];
  10997. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10998. const point = this.points[ i ];
  10999. data.points.push( point.toArray() );
  11000. }
  11001. return data;
  11002. }
  11003. fromJSON( json ) {
  11004. super.fromJSON( json );
  11005. this.points = [];
  11006. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11007. const point = json.points[ i ];
  11008. this.points.push( new Vector2().fromArray( point ) );
  11009. }
  11010. return this;
  11011. }
  11012. }
  11013. var Curves = /*#__PURE__*/Object.freeze({
  11014. __proto__: null,
  11015. ArcCurve: ArcCurve,
  11016. CatmullRomCurve3: CatmullRomCurve3,
  11017. CubicBezierCurve: CubicBezierCurve,
  11018. CubicBezierCurve3: CubicBezierCurve3,
  11019. EllipseCurve: EllipseCurve,
  11020. LineCurve: LineCurve,
  11021. LineCurve3: LineCurve3,
  11022. QuadraticBezierCurve: QuadraticBezierCurve,
  11023. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11024. SplineCurve: SplineCurve
  11025. });
  11026. /**************************************************************
  11027. * Curved Path - a curve path is simply a array of connected
  11028. * curves, but retains the api of a curve
  11029. **************************************************************/
  11030. class CurvePath extends Curve {
  11031. constructor() {
  11032. super();
  11033. this.type = 'CurvePath';
  11034. this.curves = [];
  11035. this.autoClose = false; // Automatically closes the path
  11036. }
  11037. add( curve ) {
  11038. this.curves.push( curve );
  11039. }
  11040. closePath() {
  11041. // Add a line curve if start and end of lines are not connected
  11042. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11043. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11044. if ( ! startPoint.equals( endPoint ) ) {
  11045. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11046. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11047. }
  11048. return this;
  11049. }
  11050. // To get accurate point with reference to
  11051. // entire path distance at time t,
  11052. // following has to be done:
  11053. // 1. Length of each sub path have to be known
  11054. // 2. Locate and identify type of curve
  11055. // 3. Get t for the curve
  11056. // 4. Return curve.getPointAt(t')
  11057. getPoint( t, optionalTarget ) {
  11058. const d = t * this.getLength();
  11059. const curveLengths = this.getCurveLengths();
  11060. let i = 0;
  11061. // To think about boundaries points.
  11062. while ( i < curveLengths.length ) {
  11063. if ( curveLengths[ i ] >= d ) {
  11064. const diff = curveLengths[ i ] - d;
  11065. const curve = this.curves[ i ];
  11066. const segmentLength = curve.getLength();
  11067. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11068. return curve.getPointAt( u, optionalTarget );
  11069. }
  11070. i ++;
  11071. }
  11072. return null;
  11073. // loop where sum != 0, sum > d , sum+1 <d
  11074. }
  11075. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11076. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11077. // getPoint() depends on getLength
  11078. getLength() {
  11079. const lens = this.getCurveLengths();
  11080. return lens[ lens.length - 1 ];
  11081. }
  11082. // cacheLengths must be recalculated.
  11083. updateArcLengths() {
  11084. this.needsUpdate = true;
  11085. this.cacheLengths = null;
  11086. this.getCurveLengths();
  11087. }
  11088. // Compute lengths and cache them
  11089. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11090. getCurveLengths() {
  11091. // We use cache values if curves and cache array are same length
  11092. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11093. return this.cacheLengths;
  11094. }
  11095. // Get length of sub-curve
  11096. // Push sums into cached array
  11097. const lengths = [];
  11098. let sums = 0;
  11099. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11100. sums += this.curves[ i ].getLength();
  11101. lengths.push( sums );
  11102. }
  11103. this.cacheLengths = lengths;
  11104. return lengths;
  11105. }
  11106. getSpacedPoints( divisions = 40 ) {
  11107. const points = [];
  11108. for ( let i = 0; i <= divisions; i ++ ) {
  11109. points.push( this.getPoint( i / divisions ) );
  11110. }
  11111. if ( this.autoClose ) {
  11112. points.push( points[ 0 ] );
  11113. }
  11114. return points;
  11115. }
  11116. getPoints( divisions = 12 ) {
  11117. const points = [];
  11118. let last;
  11119. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11120. const curve = curves[ i ];
  11121. const resolution = curve.isEllipseCurve ? divisions * 2
  11122. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11123. : curve.isSplineCurve ? divisions * curve.points.length
  11124. : divisions;
  11125. const pts = curve.getPoints( resolution );
  11126. for ( let j = 0; j < pts.length; j ++ ) {
  11127. const point = pts[ j ];
  11128. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11129. points.push( point );
  11130. last = point;
  11131. }
  11132. }
  11133. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11134. points.push( points[ 0 ] );
  11135. }
  11136. return points;
  11137. }
  11138. copy( source ) {
  11139. super.copy( source );
  11140. this.curves = [];
  11141. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11142. const curve = source.curves[ i ];
  11143. this.curves.push( curve.clone() );
  11144. }
  11145. this.autoClose = source.autoClose;
  11146. return this;
  11147. }
  11148. toJSON() {
  11149. const data = super.toJSON();
  11150. data.autoClose = this.autoClose;
  11151. data.curves = [];
  11152. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11153. const curve = this.curves[ i ];
  11154. data.curves.push( curve.toJSON() );
  11155. }
  11156. return data;
  11157. }
  11158. fromJSON( json ) {
  11159. super.fromJSON( json );
  11160. this.autoClose = json.autoClose;
  11161. this.curves = [];
  11162. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11163. const curve = json.curves[ i ];
  11164. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11165. }
  11166. return this;
  11167. }
  11168. }
  11169. class Path extends CurvePath {
  11170. constructor( points ) {
  11171. super();
  11172. this.type = 'Path';
  11173. this.currentPoint = new Vector2();
  11174. if ( points ) {
  11175. this.setFromPoints( points );
  11176. }
  11177. }
  11178. setFromPoints( points ) {
  11179. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11180. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11181. this.lineTo( points[ i ].x, points[ i ].y );
  11182. }
  11183. return this;
  11184. }
  11185. moveTo( x, y ) {
  11186. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11187. return this;
  11188. }
  11189. lineTo( x, y ) {
  11190. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11191. this.curves.push( curve );
  11192. this.currentPoint.set( x, y );
  11193. return this;
  11194. }
  11195. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11196. const curve = new QuadraticBezierCurve(
  11197. this.currentPoint.clone(),
  11198. new Vector2( aCPx, aCPy ),
  11199. new Vector2( aX, aY )
  11200. );
  11201. this.curves.push( curve );
  11202. this.currentPoint.set( aX, aY );
  11203. return this;
  11204. }
  11205. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11206. const curve = new CubicBezierCurve(
  11207. this.currentPoint.clone(),
  11208. new Vector2( aCP1x, aCP1y ),
  11209. new Vector2( aCP2x, aCP2y ),
  11210. new Vector2( aX, aY )
  11211. );
  11212. this.curves.push( curve );
  11213. this.currentPoint.set( aX, aY );
  11214. return this;
  11215. }
  11216. splineThru( pts /*Array of Vector*/ ) {
  11217. const npts = [ this.currentPoint.clone() ].concat( pts );
  11218. const curve = new SplineCurve( npts );
  11219. this.curves.push( curve );
  11220. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11221. return this;
  11222. }
  11223. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11224. const x0 = this.currentPoint.x;
  11225. const y0 = this.currentPoint.y;
  11226. this.absarc( aX + x0, aY + y0, aRadius,
  11227. aStartAngle, aEndAngle, aClockwise );
  11228. return this;
  11229. }
  11230. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11231. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11232. return this;
  11233. }
  11234. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11235. const x0 = this.currentPoint.x;
  11236. const y0 = this.currentPoint.y;
  11237. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11238. return this;
  11239. }
  11240. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11241. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11242. if ( this.curves.length > 0 ) {
  11243. // if a previous curve is present, attempt to join
  11244. const firstPoint = curve.getPoint( 0 );
  11245. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11246. this.lineTo( firstPoint.x, firstPoint.y );
  11247. }
  11248. }
  11249. this.curves.push( curve );
  11250. const lastPoint = curve.getPoint( 1 );
  11251. this.currentPoint.copy( lastPoint );
  11252. return this;
  11253. }
  11254. copy( source ) {
  11255. super.copy( source );
  11256. this.currentPoint.copy( source.currentPoint );
  11257. return this;
  11258. }
  11259. toJSON() {
  11260. const data = super.toJSON();
  11261. data.currentPoint = this.currentPoint.toArray();
  11262. return data;
  11263. }
  11264. fromJSON( json ) {
  11265. super.fromJSON( json );
  11266. this.currentPoint.fromArray( json.currentPoint );
  11267. return this;
  11268. }
  11269. }
  11270. class LatheGeometry extends BufferGeometry {
  11271. 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 ) {
  11272. super();
  11273. this.type = 'LatheGeometry';
  11274. this.parameters = {
  11275. points: points,
  11276. segments: segments,
  11277. phiStart: phiStart,
  11278. phiLength: phiLength
  11279. };
  11280. segments = Math.floor( segments );
  11281. // clamp phiLength so it's in range of [ 0, 2PI ]
  11282. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11283. // buffers
  11284. const indices = [];
  11285. const vertices = [];
  11286. const uvs = [];
  11287. const initNormals = [];
  11288. const normals = [];
  11289. // helper variables
  11290. const inverseSegments = 1.0 / segments;
  11291. const vertex = new Vector3();
  11292. const uv = new Vector2();
  11293. const normal = new Vector3();
  11294. const curNormal = new Vector3();
  11295. const prevNormal = new Vector3();
  11296. let dx = 0;
  11297. let dy = 0;
  11298. // pre-compute normals for initial "meridian"
  11299. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11300. switch ( j ) {
  11301. case 0: // special handling for 1st vertex on path
  11302. dx = points[ j + 1 ].x - points[ j ].x;
  11303. dy = points[ j + 1 ].y - points[ j ].y;
  11304. normal.x = dy * 1.0;
  11305. normal.y = - dx;
  11306. normal.z = dy * 0.0;
  11307. prevNormal.copy( normal );
  11308. normal.normalize();
  11309. initNormals.push( normal.x, normal.y, normal.z );
  11310. break;
  11311. case ( points.length - 1 ): // special handling for last Vertex on path
  11312. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11313. break;
  11314. default: // default handling for all vertices in between
  11315. dx = points[ j + 1 ].x - points[ j ].x;
  11316. dy = points[ j + 1 ].y - points[ j ].y;
  11317. normal.x = dy * 1.0;
  11318. normal.y = - dx;
  11319. normal.z = dy * 0.0;
  11320. curNormal.copy( normal );
  11321. normal.x += prevNormal.x;
  11322. normal.y += prevNormal.y;
  11323. normal.z += prevNormal.z;
  11324. normal.normalize();
  11325. initNormals.push( normal.x, normal.y, normal.z );
  11326. prevNormal.copy( curNormal );
  11327. }
  11328. }
  11329. // generate vertices, uvs and normals
  11330. for ( let i = 0; i <= segments; i ++ ) {
  11331. const phi = phiStart + i * inverseSegments * phiLength;
  11332. const sin = Math.sin( phi );
  11333. const cos = Math.cos( phi );
  11334. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11335. // vertex
  11336. vertex.x = points[ j ].x * sin;
  11337. vertex.y = points[ j ].y;
  11338. vertex.z = points[ j ].x * cos;
  11339. vertices.push( vertex.x, vertex.y, vertex.z );
  11340. // uv
  11341. uv.x = i / segments;
  11342. uv.y = j / ( points.length - 1 );
  11343. uvs.push( uv.x, uv.y );
  11344. // normal
  11345. const x = initNormals[ 3 * j + 0 ] * sin;
  11346. const y = initNormals[ 3 * j + 1 ];
  11347. const z = initNormals[ 3 * j + 0 ] * cos;
  11348. normals.push( x, y, z );
  11349. }
  11350. }
  11351. // indices
  11352. for ( let i = 0; i < segments; i ++ ) {
  11353. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11354. const base = j + i * points.length;
  11355. const a = base;
  11356. const b = base + points.length;
  11357. const c = base + points.length + 1;
  11358. const d = base + 1;
  11359. // faces
  11360. indices.push( a, b, d );
  11361. indices.push( c, d, b );
  11362. }
  11363. }
  11364. // build geometry
  11365. this.setIndex( indices );
  11366. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11367. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11368. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11369. }
  11370. copy( source ) {
  11371. super.copy( source );
  11372. this.parameters = Object.assign( {}, source.parameters );
  11373. return this;
  11374. }
  11375. static fromJSON( data ) {
  11376. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11377. }
  11378. }
  11379. class CapsuleGeometry extends LatheGeometry {
  11380. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11381. const path = new Path();
  11382. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11383. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11384. super( path.getPoints( capSegments ), radialSegments );
  11385. this.type = 'CapsuleGeometry';
  11386. this.parameters = {
  11387. radius: radius,
  11388. length: length,
  11389. capSegments: capSegments,
  11390. radialSegments: radialSegments,
  11391. };
  11392. }
  11393. static fromJSON( data ) {
  11394. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11395. }
  11396. }
  11397. class CircleGeometry extends BufferGeometry {
  11398. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11399. super();
  11400. this.type = 'CircleGeometry';
  11401. this.parameters = {
  11402. radius: radius,
  11403. segments: segments,
  11404. thetaStart: thetaStart,
  11405. thetaLength: thetaLength
  11406. };
  11407. segments = Math.max( 3, segments );
  11408. // buffers
  11409. const indices = [];
  11410. const vertices = [];
  11411. const normals = [];
  11412. const uvs = [];
  11413. // helper variables
  11414. const vertex = new Vector3();
  11415. const uv = new Vector2();
  11416. // center point
  11417. vertices.push( 0, 0, 0 );
  11418. normals.push( 0, 0, 1 );
  11419. uvs.push( 0.5, 0.5 );
  11420. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11421. const segment = thetaStart + s / segments * thetaLength;
  11422. // vertex
  11423. vertex.x = radius * Math.cos( segment );
  11424. vertex.y = radius * Math.sin( segment );
  11425. vertices.push( vertex.x, vertex.y, vertex.z );
  11426. // normal
  11427. normals.push( 0, 0, 1 );
  11428. // uvs
  11429. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11430. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11431. uvs.push( uv.x, uv.y );
  11432. }
  11433. // indices
  11434. for ( let i = 1; i <= segments; i ++ ) {
  11435. indices.push( i, i + 1, 0 );
  11436. }
  11437. // build geometry
  11438. this.setIndex( indices );
  11439. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11440. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11441. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11442. }
  11443. copy( source ) {
  11444. super.copy( source );
  11445. this.parameters = Object.assign( {}, source.parameters );
  11446. return this;
  11447. }
  11448. static fromJSON( data ) {
  11449. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11450. }
  11451. }
  11452. class CylinderGeometry extends BufferGeometry {
  11453. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11454. super();
  11455. this.type = 'CylinderGeometry';
  11456. this.parameters = {
  11457. radiusTop: radiusTop,
  11458. radiusBottom: radiusBottom,
  11459. height: height,
  11460. radialSegments: radialSegments,
  11461. heightSegments: heightSegments,
  11462. openEnded: openEnded,
  11463. thetaStart: thetaStart,
  11464. thetaLength: thetaLength
  11465. };
  11466. const scope = this;
  11467. radialSegments = Math.floor( radialSegments );
  11468. heightSegments = Math.floor( heightSegments );
  11469. // buffers
  11470. const indices = [];
  11471. const vertices = [];
  11472. const normals = [];
  11473. const uvs = [];
  11474. // helper variables
  11475. let index = 0;
  11476. const indexArray = [];
  11477. const halfHeight = height / 2;
  11478. let groupStart = 0;
  11479. // generate geometry
  11480. generateTorso();
  11481. if ( openEnded === false ) {
  11482. if ( radiusTop > 0 ) generateCap( true );
  11483. if ( radiusBottom > 0 ) generateCap( false );
  11484. }
  11485. // build geometry
  11486. this.setIndex( indices );
  11487. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11488. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11489. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11490. function generateTorso() {
  11491. const normal = new Vector3();
  11492. const vertex = new Vector3();
  11493. let groupCount = 0;
  11494. // this will be used to calculate the normal
  11495. const slope = ( radiusBottom - radiusTop ) / height;
  11496. // generate vertices, normals and uvs
  11497. for ( let y = 0; y <= heightSegments; y ++ ) {
  11498. const indexRow = [];
  11499. const v = y / heightSegments;
  11500. // calculate the radius of the current row
  11501. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11502. for ( let x = 0; x <= radialSegments; x ++ ) {
  11503. const u = x / radialSegments;
  11504. const theta = u * thetaLength + thetaStart;
  11505. const sinTheta = Math.sin( theta );
  11506. const cosTheta = Math.cos( theta );
  11507. // vertex
  11508. vertex.x = radius * sinTheta;
  11509. vertex.y = - v * height + halfHeight;
  11510. vertex.z = radius * cosTheta;
  11511. vertices.push( vertex.x, vertex.y, vertex.z );
  11512. // normal
  11513. normal.set( sinTheta, slope, cosTheta ).normalize();
  11514. normals.push( normal.x, normal.y, normal.z );
  11515. // uv
  11516. uvs.push( u, 1 - v );
  11517. // save index of vertex in respective row
  11518. indexRow.push( index ++ );
  11519. }
  11520. // now save vertices of the row in our index array
  11521. indexArray.push( indexRow );
  11522. }
  11523. // generate indices
  11524. for ( let x = 0; x < radialSegments; x ++ ) {
  11525. for ( let y = 0; y < heightSegments; y ++ ) {
  11526. // we use the index array to access the correct indices
  11527. const a = indexArray[ y ][ x ];
  11528. const b = indexArray[ y + 1 ][ x ];
  11529. const c = indexArray[ y + 1 ][ x + 1 ];
  11530. const d = indexArray[ y ][ x + 1 ];
  11531. // faces
  11532. indices.push( a, b, d );
  11533. indices.push( b, c, d );
  11534. // update group counter
  11535. groupCount += 6;
  11536. }
  11537. }
  11538. // add a group to the geometry. this will ensure multi material support
  11539. scope.addGroup( groupStart, groupCount, 0 );
  11540. // calculate new start value for groups
  11541. groupStart += groupCount;
  11542. }
  11543. function generateCap( top ) {
  11544. // save the index of the first center vertex
  11545. const centerIndexStart = index;
  11546. const uv = new Vector2();
  11547. const vertex = new Vector3();
  11548. let groupCount = 0;
  11549. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11550. const sign = ( top === true ) ? 1 : - 1;
  11551. // first we generate the center vertex data of the cap.
  11552. // because the geometry needs one set of uvs per face,
  11553. // we must generate a center vertex per face/segment
  11554. for ( let x = 1; x <= radialSegments; x ++ ) {
  11555. // vertex
  11556. vertices.push( 0, halfHeight * sign, 0 );
  11557. // normal
  11558. normals.push( 0, sign, 0 );
  11559. // uv
  11560. uvs.push( 0.5, 0.5 );
  11561. // increase index
  11562. index ++;
  11563. }
  11564. // save the index of the last center vertex
  11565. const centerIndexEnd = index;
  11566. // now we generate the surrounding vertices, normals and uvs
  11567. for ( let x = 0; x <= radialSegments; x ++ ) {
  11568. const u = x / radialSegments;
  11569. const theta = u * thetaLength + thetaStart;
  11570. const cosTheta = Math.cos( theta );
  11571. const sinTheta = Math.sin( theta );
  11572. // vertex
  11573. vertex.x = radius * sinTheta;
  11574. vertex.y = halfHeight * sign;
  11575. vertex.z = radius * cosTheta;
  11576. vertices.push( vertex.x, vertex.y, vertex.z );
  11577. // normal
  11578. normals.push( 0, sign, 0 );
  11579. // uv
  11580. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11581. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11582. uvs.push( uv.x, uv.y );
  11583. // increase index
  11584. index ++;
  11585. }
  11586. // generate indices
  11587. for ( let x = 0; x < radialSegments; x ++ ) {
  11588. const c = centerIndexStart + x;
  11589. const i = centerIndexEnd + x;
  11590. if ( top === true ) {
  11591. // face top
  11592. indices.push( i, i + 1, c );
  11593. } else {
  11594. // face bottom
  11595. indices.push( i + 1, i, c );
  11596. }
  11597. groupCount += 3;
  11598. }
  11599. // add a group to the geometry. this will ensure multi material support
  11600. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11601. // calculate new start value for groups
  11602. groupStart += groupCount;
  11603. }
  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 CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11612. }
  11613. }
  11614. class ConeGeometry extends CylinderGeometry {
  11615. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11616. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11617. this.type = 'ConeGeometry';
  11618. this.parameters = {
  11619. radius: radius,
  11620. height: height,
  11621. radialSegments: radialSegments,
  11622. heightSegments: heightSegments,
  11623. openEnded: openEnded,
  11624. thetaStart: thetaStart,
  11625. thetaLength: thetaLength
  11626. };
  11627. }
  11628. static fromJSON( data ) {
  11629. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11630. }
  11631. }
  11632. class PolyhedronGeometry extends BufferGeometry {
  11633. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11634. super();
  11635. this.type = 'PolyhedronGeometry';
  11636. this.parameters = {
  11637. vertices: vertices,
  11638. indices: indices,
  11639. radius: radius,
  11640. detail: detail
  11641. };
  11642. // default buffer data
  11643. const vertexBuffer = [];
  11644. const uvBuffer = [];
  11645. // the subdivision creates the vertex buffer data
  11646. subdivide( detail );
  11647. // all vertices should lie on a conceptual sphere with a given radius
  11648. applyRadius( radius );
  11649. // finally, create the uv data
  11650. generateUVs();
  11651. // build non-indexed geometry
  11652. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11653. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11654. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11655. if ( detail === 0 ) {
  11656. this.computeVertexNormals(); // flat normals
  11657. } else {
  11658. this.normalizeNormals(); // smooth normals
  11659. }
  11660. // helper functions
  11661. function subdivide( detail ) {
  11662. const a = new Vector3();
  11663. const b = new Vector3();
  11664. const c = new Vector3();
  11665. // iterate over all faces and apply a subdivision with the given detail value
  11666. for ( let i = 0; i < indices.length; i += 3 ) {
  11667. // get the vertices of the face
  11668. getVertexByIndex( indices[ i + 0 ], a );
  11669. getVertexByIndex( indices[ i + 1 ], b );
  11670. getVertexByIndex( indices[ i + 2 ], c );
  11671. // perform subdivision
  11672. subdivideFace( a, b, c, detail );
  11673. }
  11674. }
  11675. function subdivideFace( a, b, c, detail ) {
  11676. const cols = detail + 1;
  11677. // we use this multidimensional array as a data structure for creating the subdivision
  11678. const v = [];
  11679. // construct all of the vertices for this subdivision
  11680. for ( let i = 0; i <= cols; i ++ ) {
  11681. v[ i ] = [];
  11682. const aj = a.clone().lerp( c, i / cols );
  11683. const bj = b.clone().lerp( c, i / cols );
  11684. const rows = cols - i;
  11685. for ( let j = 0; j <= rows; j ++ ) {
  11686. if ( j === 0 && i === cols ) {
  11687. v[ i ][ j ] = aj;
  11688. } else {
  11689. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11690. }
  11691. }
  11692. }
  11693. // construct all of the faces
  11694. for ( let i = 0; i < cols; i ++ ) {
  11695. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11696. const k = Math.floor( j / 2 );
  11697. if ( j % 2 === 0 ) {
  11698. pushVertex( v[ i ][ k + 1 ] );
  11699. pushVertex( v[ i + 1 ][ k ] );
  11700. pushVertex( v[ i ][ k ] );
  11701. } else {
  11702. pushVertex( v[ i ][ k + 1 ] );
  11703. pushVertex( v[ i + 1 ][ k + 1 ] );
  11704. pushVertex( v[ i + 1 ][ k ] );
  11705. }
  11706. }
  11707. }
  11708. }
  11709. function applyRadius( radius ) {
  11710. const vertex = new Vector3();
  11711. // iterate over the entire buffer and apply the radius to each vertex
  11712. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11713. vertex.x = vertexBuffer[ i + 0 ];
  11714. vertex.y = vertexBuffer[ i + 1 ];
  11715. vertex.z = vertexBuffer[ i + 2 ];
  11716. vertex.normalize().multiplyScalar( radius );
  11717. vertexBuffer[ i + 0 ] = vertex.x;
  11718. vertexBuffer[ i + 1 ] = vertex.y;
  11719. vertexBuffer[ i + 2 ] = vertex.z;
  11720. }
  11721. }
  11722. function generateUVs() {
  11723. const vertex = new Vector3();
  11724. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11725. vertex.x = vertexBuffer[ i + 0 ];
  11726. vertex.y = vertexBuffer[ i + 1 ];
  11727. vertex.z = vertexBuffer[ i + 2 ];
  11728. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11729. const v = inclination( vertex ) / Math.PI + 0.5;
  11730. uvBuffer.push( u, 1 - v );
  11731. }
  11732. correctUVs();
  11733. correctSeam();
  11734. }
  11735. function correctSeam() {
  11736. // handle case when face straddles the seam, see #3269
  11737. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11738. // uv data of a single face
  11739. const x0 = uvBuffer[ i + 0 ];
  11740. const x1 = uvBuffer[ i + 2 ];
  11741. const x2 = uvBuffer[ i + 4 ];
  11742. const max = Math.max( x0, x1, x2 );
  11743. const min = Math.min( x0, x1, x2 );
  11744. // 0.9 is somewhat arbitrary
  11745. if ( max > 0.9 && min < 0.1 ) {
  11746. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11747. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11748. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11749. }
  11750. }
  11751. }
  11752. function pushVertex( vertex ) {
  11753. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11754. }
  11755. function getVertexByIndex( index, vertex ) {
  11756. const stride = index * 3;
  11757. vertex.x = vertices[ stride + 0 ];
  11758. vertex.y = vertices[ stride + 1 ];
  11759. vertex.z = vertices[ stride + 2 ];
  11760. }
  11761. function correctUVs() {
  11762. const a = new Vector3();
  11763. const b = new Vector3();
  11764. const c = new Vector3();
  11765. const centroid = new Vector3();
  11766. const uvA = new Vector2();
  11767. const uvB = new Vector2();
  11768. const uvC = new Vector2();
  11769. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  11770. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  11771. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  11772. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  11773. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  11774. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  11775. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  11776. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  11777. const azi = azimuth( centroid );
  11778. correctUV( uvA, j + 0, a, azi );
  11779. correctUV( uvB, j + 2, b, azi );
  11780. correctUV( uvC, j + 4, c, azi );
  11781. }
  11782. }
  11783. function correctUV( uv, stride, vector, azimuth ) {
  11784. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  11785. uvBuffer[ stride ] = uv.x - 1;
  11786. }
  11787. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  11788. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  11789. }
  11790. }
  11791. // Angle around the Y axis, counter-clockwise when looking from above.
  11792. function azimuth( vector ) {
  11793. return Math.atan2( vector.z, - vector.x );
  11794. }
  11795. // Angle above the XZ plane.
  11796. function inclination( vector ) {
  11797. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  11798. }
  11799. }
  11800. copy( source ) {
  11801. super.copy( source );
  11802. this.parameters = Object.assign( {}, source.parameters );
  11803. return this;
  11804. }
  11805. static fromJSON( data ) {
  11806. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  11807. }
  11808. }
  11809. class DodecahedronGeometry extends PolyhedronGeometry {
  11810. constructor( radius = 1, detail = 0 ) {
  11811. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  11812. const r = 1 / t;
  11813. const vertices = [
  11814. // (±1, ±1, ±1)
  11815. - 1, - 1, - 1, - 1, - 1, 1,
  11816. - 1, 1, - 1, - 1, 1, 1,
  11817. 1, - 1, - 1, 1, - 1, 1,
  11818. 1, 1, - 1, 1, 1, 1,
  11819. // (0, ±1/φ, ±φ)
  11820. 0, - r, - t, 0, - r, t,
  11821. 0, r, - t, 0, r, t,
  11822. // (±1/φ, ±φ, 0)
  11823. - r, - t, 0, - r, t, 0,
  11824. r, - t, 0, r, t, 0,
  11825. // (±φ, 0, ±1/φ)
  11826. - t, 0, - r, t, 0, - r,
  11827. - t, 0, r, t, 0, r
  11828. ];
  11829. const indices = [
  11830. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  11831. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  11832. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  11833. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  11834. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  11835. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  11836. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  11837. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  11838. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  11839. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  11840. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  11841. 1, 12, 14, 1, 14, 5, 1, 5, 9
  11842. ];
  11843. super( vertices, indices, radius, detail );
  11844. this.type = 'DodecahedronGeometry';
  11845. this.parameters = {
  11846. radius: radius,
  11847. detail: detail
  11848. };
  11849. }
  11850. static fromJSON( data ) {
  11851. return new DodecahedronGeometry( data.radius, data.detail );
  11852. }
  11853. }
  11854. const _v0 = /*@__PURE__*/ new Vector3();
  11855. const _v1$1 = /*@__PURE__*/ new Vector3();
  11856. const _normal$1 = /*@__PURE__*/ new Vector3();
  11857. const _triangle = /*@__PURE__*/ new Triangle();
  11858. class EdgesGeometry extends BufferGeometry {
  11859. constructor( geometry = null, thresholdAngle = 1 ) {
  11860. super();
  11861. this.type = 'EdgesGeometry';
  11862. this.parameters = {
  11863. geometry: geometry,
  11864. thresholdAngle: thresholdAngle
  11865. };
  11866. if ( geometry !== null ) {
  11867. const precisionPoints = 4;
  11868. const precision = Math.pow( 10, precisionPoints );
  11869. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  11870. const indexAttr = geometry.getIndex();
  11871. const positionAttr = geometry.getAttribute( 'position' );
  11872. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  11873. const indexArr = [ 0, 0, 0 ];
  11874. const vertKeys = [ 'a', 'b', 'c' ];
  11875. const hashes = new Array( 3 );
  11876. const edgeData = {};
  11877. const vertices = [];
  11878. for ( let i = 0; i < indexCount; i += 3 ) {
  11879. if ( indexAttr ) {
  11880. indexArr[ 0 ] = indexAttr.getX( i );
  11881. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  11882. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  11883. } else {
  11884. indexArr[ 0 ] = i;
  11885. indexArr[ 1 ] = i + 1;
  11886. indexArr[ 2 ] = i + 2;
  11887. }
  11888. const { a, b, c } = _triangle;
  11889. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  11890. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  11891. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  11892. _triangle.getNormal( _normal$1 );
  11893. // create hashes for the edge from the vertices
  11894. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  11895. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  11896. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  11897. // skip degenerate triangles
  11898. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  11899. continue;
  11900. }
  11901. // iterate over every edge
  11902. for ( let j = 0; j < 3; j ++ ) {
  11903. // get the first and next vertex making up the edge
  11904. const jNext = ( j + 1 ) % 3;
  11905. const vecHash0 = hashes[ j ];
  11906. const vecHash1 = hashes[ jNext ];
  11907. const v0 = _triangle[ vertKeys[ j ] ];
  11908. const v1 = _triangle[ vertKeys[ jNext ] ];
  11909. const hash = `${ vecHash0 }_${ vecHash1 }`;
  11910. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  11911. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  11912. // if we found a sibling edge add it into the vertex array if
  11913. // it meets the angle threshold and delete the edge from the map.
  11914. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  11915. vertices.push( v0.x, v0.y, v0.z );
  11916. vertices.push( v1.x, v1.y, v1.z );
  11917. }
  11918. edgeData[ reverseHash ] = null;
  11919. } else if ( ! ( hash in edgeData ) ) {
  11920. // if we've already got an edge here then skip adding a new one
  11921. edgeData[ hash ] = {
  11922. index0: indexArr[ j ],
  11923. index1: indexArr[ jNext ],
  11924. normal: _normal$1.clone(),
  11925. };
  11926. }
  11927. }
  11928. }
  11929. // iterate over all remaining, unmatched edges and add them to the vertex array
  11930. for ( const key in edgeData ) {
  11931. if ( edgeData[ key ] ) {
  11932. const { index0, index1 } = edgeData[ key ];
  11933. _v0.fromBufferAttribute( positionAttr, index0 );
  11934. _v1$1.fromBufferAttribute( positionAttr, index1 );
  11935. vertices.push( _v0.x, _v0.y, _v0.z );
  11936. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  11937. }
  11938. }
  11939. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11940. }
  11941. }
  11942. copy( source ) {
  11943. super.copy( source );
  11944. this.parameters = Object.assign( {}, source.parameters );
  11945. return this;
  11946. }
  11947. }
  11948. class Shape extends Path {
  11949. constructor( points ) {
  11950. super( points );
  11951. this.uuid = generateUUID();
  11952. this.type = 'Shape';
  11953. this.holes = [];
  11954. }
  11955. getPointsHoles( divisions ) {
  11956. const holesPts = [];
  11957. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11958. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  11959. }
  11960. return holesPts;
  11961. }
  11962. // get points of shape and holes (keypoints based on segments parameter)
  11963. extractPoints( divisions ) {
  11964. return {
  11965. shape: this.getPoints( divisions ),
  11966. holes: this.getPointsHoles( divisions )
  11967. };
  11968. }
  11969. copy( source ) {
  11970. super.copy( source );
  11971. this.holes = [];
  11972. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  11973. const hole = source.holes[ i ];
  11974. this.holes.push( hole.clone() );
  11975. }
  11976. return this;
  11977. }
  11978. toJSON() {
  11979. const data = super.toJSON();
  11980. data.uuid = this.uuid;
  11981. data.holes = [];
  11982. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11983. const hole = this.holes[ i ];
  11984. data.holes.push( hole.toJSON() );
  11985. }
  11986. return data;
  11987. }
  11988. fromJSON( json ) {
  11989. super.fromJSON( json );
  11990. this.uuid = json.uuid;
  11991. this.holes = [];
  11992. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  11993. const hole = json.holes[ i ];
  11994. this.holes.push( new Path().fromJSON( hole ) );
  11995. }
  11996. return this;
  11997. }
  11998. }
  11999. /**
  12000. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12001. */
  12002. const Earcut = {
  12003. triangulate: function ( data, holeIndices, dim = 2 ) {
  12004. const hasHoles = holeIndices && holeIndices.length;
  12005. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12006. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12007. const triangles = [];
  12008. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12009. let minX, minY, maxX, maxY, x, y, invSize;
  12010. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12011. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12012. if ( data.length > 80 * dim ) {
  12013. minX = maxX = data[ 0 ];
  12014. minY = maxY = data[ 1 ];
  12015. for ( let i = dim; i < outerLen; i += dim ) {
  12016. x = data[ i ];
  12017. y = data[ i + 1 ];
  12018. if ( x < minX ) minX = x;
  12019. if ( y < minY ) minY = y;
  12020. if ( x > maxX ) maxX = x;
  12021. if ( y > maxY ) maxY = y;
  12022. }
  12023. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12024. invSize = Math.max( maxX - minX, maxY - minY );
  12025. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12026. }
  12027. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12028. return triangles;
  12029. }
  12030. };
  12031. // create a circular doubly linked list from polygon points in the specified winding order
  12032. function linkedList( data, start, end, dim, clockwise ) {
  12033. let i, last;
  12034. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12035. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12036. } else {
  12037. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12038. }
  12039. if ( last && equals$1( last, last.next ) ) {
  12040. removeNode( last );
  12041. last = last.next;
  12042. }
  12043. return last;
  12044. }
  12045. // eliminate colinear or duplicate points
  12046. function filterPoints( start, end ) {
  12047. if ( ! start ) return start;
  12048. if ( ! end ) end = start;
  12049. let p = start,
  12050. again;
  12051. do {
  12052. again = false;
  12053. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12054. removeNode( p );
  12055. p = end = p.prev;
  12056. if ( p === p.next ) break;
  12057. again = true;
  12058. } else {
  12059. p = p.next;
  12060. }
  12061. } while ( again || p !== end );
  12062. return end;
  12063. }
  12064. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12065. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12066. if ( ! ear ) return;
  12067. // interlink polygon nodes in z-order
  12068. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12069. let stop = ear,
  12070. prev, next;
  12071. // iterate through ears, slicing them one by one
  12072. while ( ear.prev !== ear.next ) {
  12073. prev = ear.prev;
  12074. next = ear.next;
  12075. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12076. // cut off the triangle
  12077. triangles.push( prev.i / dim | 0 );
  12078. triangles.push( ear.i / dim | 0 );
  12079. triangles.push( next.i / dim | 0 );
  12080. removeNode( ear );
  12081. // skipping the next vertex leads to less sliver triangles
  12082. ear = next.next;
  12083. stop = next.next;
  12084. continue;
  12085. }
  12086. ear = next;
  12087. // if we looped through the whole remaining polygon and can't find any more ears
  12088. if ( ear === stop ) {
  12089. // try filtering points and slicing again
  12090. if ( ! pass ) {
  12091. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12092. // if this didn't work, try curing all small self-intersections locally
  12093. } else if ( pass === 1 ) {
  12094. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12095. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12096. // as a last resort, try splitting the remaining polygon into two
  12097. } else if ( pass === 2 ) {
  12098. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12099. }
  12100. break;
  12101. }
  12102. }
  12103. }
  12104. // check whether a polygon node forms a valid ear with adjacent nodes
  12105. function isEar( ear ) {
  12106. const a = ear.prev,
  12107. b = ear,
  12108. c = ear.next;
  12109. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12110. // now make sure we don't have other points inside the potential ear
  12111. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12112. // triangle bbox; min & max are calculated like this for speed
  12113. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12114. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12115. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12116. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12117. let p = c.next;
  12118. while ( p !== a ) {
  12119. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12120. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12121. area( p.prev, p, p.next ) >= 0 ) return false;
  12122. p = p.next;
  12123. }
  12124. return true;
  12125. }
  12126. function isEarHashed( ear, minX, minY, invSize ) {
  12127. const a = ear.prev,
  12128. b = ear,
  12129. c = ear.next;
  12130. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12131. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12132. // triangle bbox; min & max are calculated like this for speed
  12133. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12134. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12135. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12136. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12137. // z-order range for the current triangle bbox;
  12138. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12139. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12140. let p = ear.prevZ,
  12141. n = ear.nextZ;
  12142. // look for points inside the triangle in both directions
  12143. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12144. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12145. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12146. p = p.prevZ;
  12147. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12148. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12149. n = n.nextZ;
  12150. }
  12151. // look for remaining points in decreasing z-order
  12152. while ( p && p.z >= minZ ) {
  12153. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12154. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12155. p = p.prevZ;
  12156. }
  12157. // look for remaining points in increasing z-order
  12158. while ( n && n.z <= maxZ ) {
  12159. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12160. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12161. n = n.nextZ;
  12162. }
  12163. return true;
  12164. }
  12165. // go through all polygon nodes and cure small local self-intersections
  12166. function cureLocalIntersections( start, triangles, dim ) {
  12167. let p = start;
  12168. do {
  12169. const a = p.prev,
  12170. b = p.next.next;
  12171. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12172. triangles.push( a.i / dim | 0 );
  12173. triangles.push( p.i / dim | 0 );
  12174. triangles.push( b.i / dim | 0 );
  12175. // remove two nodes involved
  12176. removeNode( p );
  12177. removeNode( p.next );
  12178. p = start = b;
  12179. }
  12180. p = p.next;
  12181. } while ( p !== start );
  12182. return filterPoints( p );
  12183. }
  12184. // try splitting polygon into two and triangulate them independently
  12185. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12186. // look for a valid diagonal that divides the polygon into two
  12187. let a = start;
  12188. do {
  12189. let b = a.next.next;
  12190. while ( b !== a.prev ) {
  12191. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12192. // split the polygon in two by the diagonal
  12193. let c = splitPolygon( a, b );
  12194. // filter colinear points around the cuts
  12195. a = filterPoints( a, a.next );
  12196. c = filterPoints( c, c.next );
  12197. // run earcut on each half
  12198. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12199. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12200. return;
  12201. }
  12202. b = b.next;
  12203. }
  12204. a = a.next;
  12205. } while ( a !== start );
  12206. }
  12207. // link every hole into the outer loop, producing a single-ring polygon without holes
  12208. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12209. const queue = [];
  12210. let i, len, start, end, list;
  12211. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12212. start = holeIndices[ i ] * dim;
  12213. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12214. list = linkedList( data, start, end, dim, false );
  12215. if ( list === list.next ) list.steiner = true;
  12216. queue.push( getLeftmost( list ) );
  12217. }
  12218. queue.sort( compareX );
  12219. // process holes from left to right
  12220. for ( i = 0; i < queue.length; i ++ ) {
  12221. outerNode = eliminateHole( queue[ i ], outerNode );
  12222. }
  12223. return outerNode;
  12224. }
  12225. function compareX( a, b ) {
  12226. return a.x - b.x;
  12227. }
  12228. // find a bridge between vertices that connects hole with an outer ring and link it
  12229. function eliminateHole( hole, outerNode ) {
  12230. const bridge = findHoleBridge( hole, outerNode );
  12231. if ( ! bridge ) {
  12232. return outerNode;
  12233. }
  12234. const bridgeReverse = splitPolygon( bridge, hole );
  12235. // filter collinear points around the cuts
  12236. filterPoints( bridgeReverse, bridgeReverse.next );
  12237. return filterPoints( bridge, bridge.next );
  12238. }
  12239. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12240. function findHoleBridge( hole, outerNode ) {
  12241. let p = outerNode,
  12242. qx = - Infinity,
  12243. m;
  12244. const hx = hole.x, hy = hole.y;
  12245. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12246. // segment's endpoint with lesser x will be potential connection point
  12247. do {
  12248. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12249. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12250. if ( x <= hx && x > qx ) {
  12251. qx = x;
  12252. m = p.x < p.next.x ? p : p.next;
  12253. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12254. }
  12255. }
  12256. p = p.next;
  12257. } while ( p !== outerNode );
  12258. if ( ! m ) return null;
  12259. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12260. // if there are no points found, we have a valid connection;
  12261. // otherwise choose the point of the minimum angle with the ray as connection point
  12262. const stop = m,
  12263. mx = m.x,
  12264. my = m.y;
  12265. let tanMin = Infinity, tan;
  12266. p = m;
  12267. do {
  12268. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12269. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12270. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12271. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12272. m = p;
  12273. tanMin = tan;
  12274. }
  12275. }
  12276. p = p.next;
  12277. } while ( p !== stop );
  12278. return m;
  12279. }
  12280. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12281. function sectorContainsSector( m, p ) {
  12282. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12283. }
  12284. // interlink polygon nodes in z-order
  12285. function indexCurve( start, minX, minY, invSize ) {
  12286. let p = start;
  12287. do {
  12288. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12289. p.prevZ = p.prev;
  12290. p.nextZ = p.next;
  12291. p = p.next;
  12292. } while ( p !== start );
  12293. p.prevZ.nextZ = null;
  12294. p.prevZ = null;
  12295. sortLinked( p );
  12296. }
  12297. // Simon Tatham's linked list merge sort algorithm
  12298. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12299. function sortLinked( list ) {
  12300. let i, p, q, e, tail, numMerges, pSize, qSize,
  12301. inSize = 1;
  12302. do {
  12303. p = list;
  12304. list = null;
  12305. tail = null;
  12306. numMerges = 0;
  12307. while ( p ) {
  12308. numMerges ++;
  12309. q = p;
  12310. pSize = 0;
  12311. for ( i = 0; i < inSize; i ++ ) {
  12312. pSize ++;
  12313. q = q.nextZ;
  12314. if ( ! q ) break;
  12315. }
  12316. qSize = inSize;
  12317. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12318. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12319. e = p;
  12320. p = p.nextZ;
  12321. pSize --;
  12322. } else {
  12323. e = q;
  12324. q = q.nextZ;
  12325. qSize --;
  12326. }
  12327. if ( tail ) tail.nextZ = e;
  12328. else list = e;
  12329. e.prevZ = tail;
  12330. tail = e;
  12331. }
  12332. p = q;
  12333. }
  12334. tail.nextZ = null;
  12335. inSize *= 2;
  12336. } while ( numMerges > 1 );
  12337. return list;
  12338. }
  12339. // z-order of a point given coords and inverse of the longer side of data bbox
  12340. function zOrder( x, y, minX, minY, invSize ) {
  12341. // coords are transformed into non-negative 15-bit integer range
  12342. x = ( x - minX ) * invSize | 0;
  12343. y = ( y - minY ) * invSize | 0;
  12344. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12345. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12346. x = ( x | ( x << 2 ) ) & 0x33333333;
  12347. x = ( x | ( x << 1 ) ) & 0x55555555;
  12348. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12349. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12350. y = ( y | ( y << 2 ) ) & 0x33333333;
  12351. y = ( y | ( y << 1 ) ) & 0x55555555;
  12352. return x | ( y << 1 );
  12353. }
  12354. // find the leftmost node of a polygon ring
  12355. function getLeftmost( start ) {
  12356. let p = start,
  12357. leftmost = start;
  12358. do {
  12359. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12360. p = p.next;
  12361. } while ( p !== start );
  12362. return leftmost;
  12363. }
  12364. // check if a point lies within a convex triangle
  12365. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12366. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12367. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12368. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12369. }
  12370. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12371. function isValidDiagonal( a, b ) {
  12372. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12373. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12374. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12375. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12376. }
  12377. // signed area of a triangle
  12378. function area( p, q, r ) {
  12379. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12380. }
  12381. // check if two points are equal
  12382. function equals$1( p1, p2 ) {
  12383. return p1.x === p2.x && p1.y === p2.y;
  12384. }
  12385. // check if two segments intersect
  12386. function intersects( p1, q1, p2, q2 ) {
  12387. const o1 = sign$1( area( p1, q1, p2 ) );
  12388. const o2 = sign$1( area( p1, q1, q2 ) );
  12389. const o3 = sign$1( area( p2, q2, p1 ) );
  12390. const o4 = sign$1( area( p2, q2, q1 ) );
  12391. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12392. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12393. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12394. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12395. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12396. return false;
  12397. }
  12398. // for collinear points p, q, r, check if point q lies on segment pr
  12399. function onSegment( p, q, r ) {
  12400. 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 );
  12401. }
  12402. function sign$1( num ) {
  12403. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12404. }
  12405. // check if a polygon diagonal intersects any polygon segments
  12406. function intersectsPolygon( a, b ) {
  12407. let p = a;
  12408. do {
  12409. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12410. intersects( p, p.next, a, b ) ) return true;
  12411. p = p.next;
  12412. } while ( p !== a );
  12413. return false;
  12414. }
  12415. // check if a polygon diagonal is locally inside the polygon
  12416. function locallyInside( a, b ) {
  12417. return area( a.prev, a, a.next ) < 0 ?
  12418. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12419. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12420. }
  12421. // check if the middle point of a polygon diagonal is inside the polygon
  12422. function middleInside( a, b ) {
  12423. let p = a,
  12424. inside = false;
  12425. const px = ( a.x + b.x ) / 2,
  12426. py = ( a.y + b.y ) / 2;
  12427. do {
  12428. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12429. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12430. inside = ! inside;
  12431. p = p.next;
  12432. } while ( p !== a );
  12433. return inside;
  12434. }
  12435. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12436. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12437. function splitPolygon( a, b ) {
  12438. const a2 = new Node$1( a.i, a.x, a.y ),
  12439. b2 = new Node$1( b.i, b.x, b.y ),
  12440. an = a.next,
  12441. bp = b.prev;
  12442. a.next = b;
  12443. b.prev = a;
  12444. a2.next = an;
  12445. an.prev = a2;
  12446. b2.next = a2;
  12447. a2.prev = b2;
  12448. bp.next = b2;
  12449. b2.prev = bp;
  12450. return b2;
  12451. }
  12452. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12453. function insertNode( i, x, y, last ) {
  12454. const p = new Node$1( i, x, y );
  12455. if ( ! last ) {
  12456. p.prev = p;
  12457. p.next = p;
  12458. } else {
  12459. p.next = last.next;
  12460. p.prev = last;
  12461. last.next.prev = p;
  12462. last.next = p;
  12463. }
  12464. return p;
  12465. }
  12466. function removeNode( p ) {
  12467. p.next.prev = p.prev;
  12468. p.prev.next = p.next;
  12469. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12470. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12471. }
  12472. function Node$1( i, x, y ) {
  12473. // vertex index in coordinates array
  12474. this.i = i;
  12475. // vertex coordinates
  12476. this.x = x;
  12477. this.y = y;
  12478. // previous and next vertex nodes in a polygon ring
  12479. this.prev = null;
  12480. this.next = null;
  12481. // z-order curve value
  12482. this.z = 0;
  12483. // previous and next nodes in z-order
  12484. this.prevZ = null;
  12485. this.nextZ = null;
  12486. // indicates whether this is a steiner point
  12487. this.steiner = false;
  12488. }
  12489. function signedArea( data, start, end, dim ) {
  12490. let sum = 0;
  12491. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12492. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12493. j = i;
  12494. }
  12495. return sum;
  12496. }
  12497. class ShapeUtils {
  12498. // calculate area of the contour polygon
  12499. static area( contour ) {
  12500. const n = contour.length;
  12501. let a = 0.0;
  12502. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12503. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12504. }
  12505. return a * 0.5;
  12506. }
  12507. static isClockWise( pts ) {
  12508. return ShapeUtils.area( pts ) < 0;
  12509. }
  12510. static triangulateShape( contour, holes ) {
  12511. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12512. const holeIndices = []; // array of hole indices
  12513. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12514. removeDupEndPts( contour );
  12515. addContour( vertices, contour );
  12516. //
  12517. let holeIndex = contour.length;
  12518. holes.forEach( removeDupEndPts );
  12519. for ( let i = 0; i < holes.length; i ++ ) {
  12520. holeIndices.push( holeIndex );
  12521. holeIndex += holes[ i ].length;
  12522. addContour( vertices, holes[ i ] );
  12523. }
  12524. //
  12525. const triangles = Earcut.triangulate( vertices, holeIndices );
  12526. //
  12527. for ( let i = 0; i < triangles.length; i += 3 ) {
  12528. faces.push( triangles.slice( i, i + 3 ) );
  12529. }
  12530. return faces;
  12531. }
  12532. }
  12533. function removeDupEndPts( points ) {
  12534. const l = points.length;
  12535. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12536. points.pop();
  12537. }
  12538. }
  12539. function addContour( vertices, contour ) {
  12540. for ( let i = 0; i < contour.length; i ++ ) {
  12541. vertices.push( contour[ i ].x );
  12542. vertices.push( contour[ i ].y );
  12543. }
  12544. }
  12545. /**
  12546. * Creates extruded geometry from a path shape.
  12547. *
  12548. * parameters = {
  12549. *
  12550. * curveSegments: <int>, // number of points on the curves
  12551. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12552. * depth: <float>, // Depth to extrude the shape
  12553. *
  12554. * bevelEnabled: <bool>, // turn on bevel
  12555. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12556. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12557. * bevelOffset: <float>, // how far from shape outline does bevel start
  12558. * bevelSegments: <int>, // number of bevel layers
  12559. *
  12560. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12561. *
  12562. * UVGenerator: <Object> // object that provides UV generator functions
  12563. *
  12564. * }
  12565. */
  12566. class ExtrudeGeometry extends BufferGeometry {
  12567. 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 = {} ) {
  12568. super();
  12569. this.type = 'ExtrudeGeometry';
  12570. this.parameters = {
  12571. shapes: shapes,
  12572. options: options
  12573. };
  12574. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12575. const scope = this;
  12576. const verticesArray = [];
  12577. const uvArray = [];
  12578. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12579. const shape = shapes[ i ];
  12580. addShape( shape );
  12581. }
  12582. // build geometry
  12583. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12584. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12585. this.computeVertexNormals();
  12586. // functions
  12587. function addShape( shape ) {
  12588. const placeholder = [];
  12589. // options
  12590. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12591. const steps = options.steps !== undefined ? options.steps : 1;
  12592. const depth = options.depth !== undefined ? options.depth : 1;
  12593. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12594. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12595. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12596. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12597. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12598. const extrudePath = options.extrudePath;
  12599. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12600. //
  12601. let extrudePts, extrudeByPath = false;
  12602. let splineTube, binormal, normal, position2;
  12603. if ( extrudePath ) {
  12604. extrudePts = extrudePath.getSpacedPoints( steps );
  12605. extrudeByPath = true;
  12606. bevelEnabled = false; // bevels not supported for path extrusion
  12607. // SETUP TNB variables
  12608. // TODO1 - have a .isClosed in spline?
  12609. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12610. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12611. binormal = new Vector3();
  12612. normal = new Vector3();
  12613. position2 = new Vector3();
  12614. }
  12615. // Safeguards if bevels are not enabled
  12616. if ( ! bevelEnabled ) {
  12617. bevelSegments = 0;
  12618. bevelThickness = 0;
  12619. bevelSize = 0;
  12620. bevelOffset = 0;
  12621. }
  12622. // Variables initialization
  12623. const shapePoints = shape.extractPoints( curveSegments );
  12624. let vertices = shapePoints.shape;
  12625. const holes = shapePoints.holes;
  12626. const reverse = ! ShapeUtils.isClockWise( vertices );
  12627. if ( reverse ) {
  12628. vertices = vertices.reverse();
  12629. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12630. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12631. const ahole = holes[ h ];
  12632. if ( ShapeUtils.isClockWise( ahole ) ) {
  12633. holes[ h ] = ahole.reverse();
  12634. }
  12635. }
  12636. }
  12637. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12638. /* Vertices */
  12639. const contour = vertices; // vertices has all points but contour has only points of circumference
  12640. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12641. const ahole = holes[ h ];
  12642. vertices = vertices.concat( ahole );
  12643. }
  12644. function scalePt2( pt, vec, size ) {
  12645. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12646. return pt.clone().addScaledVector( vec, size );
  12647. }
  12648. const vlen = vertices.length, flen = faces.length;
  12649. // Find directions for point movement
  12650. function getBevelVec( inPt, inPrev, inNext ) {
  12651. // computes for inPt the corresponding point inPt' on a new contour
  12652. // shifted by 1 unit (length of normalized vector) to the left
  12653. // if we walk along contour clockwise, this new contour is outside the old one
  12654. //
  12655. // inPt' is the intersection of the two lines parallel to the two
  12656. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12657. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12658. // good reading for geometry algorithms (here: line-line intersection)
  12659. // http://geomalgorithms.com/a05-_intersect-1.html
  12660. const v_prev_x = inPt.x - inPrev.x,
  12661. v_prev_y = inPt.y - inPrev.y;
  12662. const v_next_x = inNext.x - inPt.x,
  12663. v_next_y = inNext.y - inPt.y;
  12664. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12665. // check for collinear edges
  12666. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12667. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12668. // not collinear
  12669. // length of vectors for normalizing
  12670. const v_prev_len = Math.sqrt( v_prev_lensq );
  12671. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12672. // shift adjacent points by unit vectors to the left
  12673. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12674. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12675. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12676. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12677. // scaling factor for v_prev to intersection point
  12678. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12679. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12680. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12681. // vector from inPt to intersection point
  12682. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12683. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12684. // Don't normalize!, otherwise sharp corners become ugly
  12685. // but prevent crazy spikes
  12686. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12687. if ( v_trans_lensq <= 2 ) {
  12688. return new Vector2( v_trans_x, v_trans_y );
  12689. } else {
  12690. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12691. }
  12692. } else {
  12693. // handle special case of collinear edges
  12694. let direction_eq = false; // assumes: opposite
  12695. if ( v_prev_x > Number.EPSILON ) {
  12696. if ( v_next_x > Number.EPSILON ) {
  12697. direction_eq = true;
  12698. }
  12699. } else {
  12700. if ( v_prev_x < - Number.EPSILON ) {
  12701. if ( v_next_x < - Number.EPSILON ) {
  12702. direction_eq = true;
  12703. }
  12704. } else {
  12705. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12706. direction_eq = true;
  12707. }
  12708. }
  12709. }
  12710. if ( direction_eq ) {
  12711. // console.log("Warning: lines are a straight sequence");
  12712. v_trans_x = - v_prev_y;
  12713. v_trans_y = v_prev_x;
  12714. shrink_by = Math.sqrt( v_prev_lensq );
  12715. } else {
  12716. // console.log("Warning: lines are a straight spike");
  12717. v_trans_x = v_prev_x;
  12718. v_trans_y = v_prev_y;
  12719. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12720. }
  12721. }
  12722. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12723. }
  12724. const contourMovements = [];
  12725. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12726. if ( j === il ) j = 0;
  12727. if ( k === il ) k = 0;
  12728. // (j)---(i)---(k)
  12729. // console.log('i,j,k', i, j , k)
  12730. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12731. }
  12732. const holesMovements = [];
  12733. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12734. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12735. const ahole = holes[ h ];
  12736. oneHoleMovements = [];
  12737. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12738. if ( j === il ) j = 0;
  12739. if ( k === il ) k = 0;
  12740. // (j)---(i)---(k)
  12741. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12742. }
  12743. holesMovements.push( oneHoleMovements );
  12744. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12745. }
  12746. // Loop bevelSegments, 1 for the front, 1 for the back
  12747. for ( let b = 0; b < bevelSegments; b ++ ) {
  12748. //for ( b = bevelSegments; b > 0; b -- ) {
  12749. const t = b / bevelSegments;
  12750. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12751. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12752. // contract shape
  12753. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12754. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12755. v( vert.x, vert.y, - z );
  12756. }
  12757. // expand holes
  12758. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12759. const ahole = holes[ h ];
  12760. oneHoleMovements = holesMovements[ h ];
  12761. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12762. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12763. v( vert.x, vert.y, - z );
  12764. }
  12765. }
  12766. }
  12767. const bs = bevelSize + bevelOffset;
  12768. // Back facing vertices
  12769. for ( let i = 0; i < vlen; i ++ ) {
  12770. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12771. if ( ! extrudeByPath ) {
  12772. v( vert.x, vert.y, 0 );
  12773. } else {
  12774. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  12775. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  12776. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  12777. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  12778. v( position2.x, position2.y, position2.z );
  12779. }
  12780. }
  12781. // Add stepped vertices...
  12782. // Including front facing vertices
  12783. for ( let s = 1; s <= steps; s ++ ) {
  12784. for ( let i = 0; i < vlen; i ++ ) {
  12785. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12786. if ( ! extrudeByPath ) {
  12787. v( vert.x, vert.y, depth / steps * s );
  12788. } else {
  12789. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  12790. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  12791. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  12792. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  12793. v( position2.x, position2.y, position2.z );
  12794. }
  12795. }
  12796. }
  12797. // Add bevel segments planes
  12798. //for ( b = 1; b <= bevelSegments; b ++ ) {
  12799. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  12800. const t = b / bevelSegments;
  12801. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12802. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12803. // contract shape
  12804. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12805. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12806. v( vert.x, vert.y, depth + z );
  12807. }
  12808. // expand holes
  12809. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12810. const ahole = holes[ h ];
  12811. oneHoleMovements = holesMovements[ h ];
  12812. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12813. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12814. if ( ! extrudeByPath ) {
  12815. v( vert.x, vert.y, depth + z );
  12816. } else {
  12817. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  12818. }
  12819. }
  12820. }
  12821. }
  12822. /* Faces */
  12823. // Top and bottom faces
  12824. buildLidFaces();
  12825. // Sides faces
  12826. buildSideFaces();
  12827. ///// Internal functions
  12828. function buildLidFaces() {
  12829. const start = verticesArray.length / 3;
  12830. if ( bevelEnabled ) {
  12831. let layer = 0; // steps + 1
  12832. let offset = vlen * layer;
  12833. // Bottom faces
  12834. for ( let i = 0; i < flen; i ++ ) {
  12835. const face = faces[ i ];
  12836. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  12837. }
  12838. layer = steps + bevelSegments * 2;
  12839. offset = vlen * layer;
  12840. // Top faces
  12841. for ( let i = 0; i < flen; i ++ ) {
  12842. const face = faces[ i ];
  12843. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  12844. }
  12845. } else {
  12846. // Bottom faces
  12847. for ( let i = 0; i < flen; i ++ ) {
  12848. const face = faces[ i ];
  12849. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  12850. }
  12851. // Top faces
  12852. for ( let i = 0; i < flen; i ++ ) {
  12853. const face = faces[ i ];
  12854. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  12855. }
  12856. }
  12857. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  12858. }
  12859. // Create faces for the z-sides of the shape
  12860. function buildSideFaces() {
  12861. const start = verticesArray.length / 3;
  12862. let layeroffset = 0;
  12863. sidewalls( contour, layeroffset );
  12864. layeroffset += contour.length;
  12865. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12866. const ahole = holes[ h ];
  12867. sidewalls( ahole, layeroffset );
  12868. //, true
  12869. layeroffset += ahole.length;
  12870. }
  12871. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  12872. }
  12873. function sidewalls( contour, layeroffset ) {
  12874. let i = contour.length;
  12875. while ( -- i >= 0 ) {
  12876. const j = i;
  12877. let k = i - 1;
  12878. if ( k < 0 ) k = contour.length - 1;
  12879. //console.log('b', i,j, i-1, k,vertices.length);
  12880. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  12881. const slen1 = vlen * s;
  12882. const slen2 = vlen * ( s + 1 );
  12883. const a = layeroffset + j + slen1,
  12884. b = layeroffset + k + slen1,
  12885. c = layeroffset + k + slen2,
  12886. d = layeroffset + j + slen2;
  12887. f4( a, b, c, d );
  12888. }
  12889. }
  12890. }
  12891. function v( x, y, z ) {
  12892. placeholder.push( x );
  12893. placeholder.push( y );
  12894. placeholder.push( z );
  12895. }
  12896. function f3( a, b, c ) {
  12897. addVertex( a );
  12898. addVertex( b );
  12899. addVertex( c );
  12900. const nextIndex = verticesArray.length / 3;
  12901. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12902. addUV( uvs[ 0 ] );
  12903. addUV( uvs[ 1 ] );
  12904. addUV( uvs[ 2 ] );
  12905. }
  12906. function f4( a, b, c, d ) {
  12907. addVertex( a );
  12908. addVertex( b );
  12909. addVertex( d );
  12910. addVertex( b );
  12911. addVertex( c );
  12912. addVertex( d );
  12913. const nextIndex = verticesArray.length / 3;
  12914. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12915. addUV( uvs[ 0 ] );
  12916. addUV( uvs[ 1 ] );
  12917. addUV( uvs[ 3 ] );
  12918. addUV( uvs[ 1 ] );
  12919. addUV( uvs[ 2 ] );
  12920. addUV( uvs[ 3 ] );
  12921. }
  12922. function addVertex( index ) {
  12923. verticesArray.push( placeholder[ index * 3 + 0 ] );
  12924. verticesArray.push( placeholder[ index * 3 + 1 ] );
  12925. verticesArray.push( placeholder[ index * 3 + 2 ] );
  12926. }
  12927. function addUV( vector2 ) {
  12928. uvArray.push( vector2.x );
  12929. uvArray.push( vector2.y );
  12930. }
  12931. }
  12932. }
  12933. copy( source ) {
  12934. super.copy( source );
  12935. this.parameters = Object.assign( {}, source.parameters );
  12936. return this;
  12937. }
  12938. toJSON() {
  12939. const data = super.toJSON();
  12940. const shapes = this.parameters.shapes;
  12941. const options = this.parameters.options;
  12942. return toJSON$1( shapes, options, data );
  12943. }
  12944. static fromJSON( data, shapes ) {
  12945. const geometryShapes = [];
  12946. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  12947. const shape = shapes[ data.shapes[ j ] ];
  12948. geometryShapes.push( shape );
  12949. }
  12950. const extrudePath = data.options.extrudePath;
  12951. if ( extrudePath !== undefined ) {
  12952. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  12953. }
  12954. return new ExtrudeGeometry( geometryShapes, data.options );
  12955. }
  12956. }
  12957. const WorldUVGenerator = {
  12958. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  12959. const a_x = vertices[ indexA * 3 ];
  12960. const a_y = vertices[ indexA * 3 + 1 ];
  12961. const b_x = vertices[ indexB * 3 ];
  12962. const b_y = vertices[ indexB * 3 + 1 ];
  12963. const c_x = vertices[ indexC * 3 ];
  12964. const c_y = vertices[ indexC * 3 + 1 ];
  12965. return [
  12966. new Vector2( a_x, a_y ),
  12967. new Vector2( b_x, b_y ),
  12968. new Vector2( c_x, c_y )
  12969. ];
  12970. },
  12971. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  12972. const a_x = vertices[ indexA * 3 ];
  12973. const a_y = vertices[ indexA * 3 + 1 ];
  12974. const a_z = vertices[ indexA * 3 + 2 ];
  12975. const b_x = vertices[ indexB * 3 ];
  12976. const b_y = vertices[ indexB * 3 + 1 ];
  12977. const b_z = vertices[ indexB * 3 + 2 ];
  12978. const c_x = vertices[ indexC * 3 ];
  12979. const c_y = vertices[ indexC * 3 + 1 ];
  12980. const c_z = vertices[ indexC * 3 + 2 ];
  12981. const d_x = vertices[ indexD * 3 ];
  12982. const d_y = vertices[ indexD * 3 + 1 ];
  12983. const d_z = vertices[ indexD * 3 + 2 ];
  12984. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  12985. return [
  12986. new Vector2( a_x, 1 - a_z ),
  12987. new Vector2( b_x, 1 - b_z ),
  12988. new Vector2( c_x, 1 - c_z ),
  12989. new Vector2( d_x, 1 - d_z )
  12990. ];
  12991. } else {
  12992. return [
  12993. new Vector2( a_y, 1 - a_z ),
  12994. new Vector2( b_y, 1 - b_z ),
  12995. new Vector2( c_y, 1 - c_z ),
  12996. new Vector2( d_y, 1 - d_z )
  12997. ];
  12998. }
  12999. }
  13000. };
  13001. function toJSON$1( shapes, options, data ) {
  13002. data.shapes = [];
  13003. if ( Array.isArray( shapes ) ) {
  13004. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13005. const shape = shapes[ i ];
  13006. data.shapes.push( shape.uuid );
  13007. }
  13008. } else {
  13009. data.shapes.push( shapes.uuid );
  13010. }
  13011. data.options = Object.assign( {}, options );
  13012. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13013. return data;
  13014. }
  13015. class IcosahedronGeometry extends PolyhedronGeometry {
  13016. constructor( radius = 1, detail = 0 ) {
  13017. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13018. const vertices = [
  13019. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13020. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13021. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13022. ];
  13023. const indices = [
  13024. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13025. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13026. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13027. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13028. ];
  13029. super( vertices, indices, radius, detail );
  13030. this.type = 'IcosahedronGeometry';
  13031. this.parameters = {
  13032. radius: radius,
  13033. detail: detail
  13034. };
  13035. }
  13036. static fromJSON( data ) {
  13037. return new IcosahedronGeometry( data.radius, data.detail );
  13038. }
  13039. }
  13040. class OctahedronGeometry extends PolyhedronGeometry {
  13041. constructor( radius = 1, detail = 0 ) {
  13042. const vertices = [
  13043. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13044. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13045. ];
  13046. const indices = [
  13047. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13048. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13049. 1, 3, 4, 1, 4, 2
  13050. ];
  13051. super( vertices, indices, radius, detail );
  13052. this.type = 'OctahedronGeometry';
  13053. this.parameters = {
  13054. radius: radius,
  13055. detail: detail
  13056. };
  13057. }
  13058. static fromJSON( data ) {
  13059. return new OctahedronGeometry( data.radius, data.detail );
  13060. }
  13061. }
  13062. class PlaneGeometry extends BufferGeometry {
  13063. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13064. super();
  13065. this.type = 'PlaneGeometry';
  13066. this.parameters = {
  13067. width: width,
  13068. height: height,
  13069. widthSegments: widthSegments,
  13070. heightSegments: heightSegments
  13071. };
  13072. const width_half = width / 2;
  13073. const height_half = height / 2;
  13074. const gridX = Math.floor( widthSegments );
  13075. const gridY = Math.floor( heightSegments );
  13076. const gridX1 = gridX + 1;
  13077. const gridY1 = gridY + 1;
  13078. const segment_width = width / gridX;
  13079. const segment_height = height / gridY;
  13080. //
  13081. const indices = [];
  13082. const vertices = [];
  13083. const normals = [];
  13084. const uvs = [];
  13085. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13086. const y = iy * segment_height - height_half;
  13087. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13088. const x = ix * segment_width - width_half;
  13089. vertices.push( x, - y, 0 );
  13090. normals.push( 0, 0, 1 );
  13091. uvs.push( ix / gridX );
  13092. uvs.push( 1 - ( iy / gridY ) );
  13093. }
  13094. }
  13095. for ( let iy = 0; iy < gridY; iy ++ ) {
  13096. for ( let ix = 0; ix < gridX; ix ++ ) {
  13097. const a = ix + gridX1 * iy;
  13098. const b = ix + gridX1 * ( iy + 1 );
  13099. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13100. const d = ( ix + 1 ) + gridX1 * iy;
  13101. indices.push( a, b, d );
  13102. indices.push( b, c, d );
  13103. }
  13104. }
  13105. this.setIndex( indices );
  13106. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13107. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13108. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13109. }
  13110. copy( source ) {
  13111. super.copy( source );
  13112. this.parameters = Object.assign( {}, source.parameters );
  13113. return this;
  13114. }
  13115. static fromJSON( data ) {
  13116. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13117. }
  13118. }
  13119. class RingGeometry extends BufferGeometry {
  13120. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13121. super();
  13122. this.type = 'RingGeometry';
  13123. this.parameters = {
  13124. innerRadius: innerRadius,
  13125. outerRadius: outerRadius,
  13126. thetaSegments: thetaSegments,
  13127. phiSegments: phiSegments,
  13128. thetaStart: thetaStart,
  13129. thetaLength: thetaLength
  13130. };
  13131. thetaSegments = Math.max( 3, thetaSegments );
  13132. phiSegments = Math.max( 1, phiSegments );
  13133. // buffers
  13134. const indices = [];
  13135. const vertices = [];
  13136. const normals = [];
  13137. const uvs = [];
  13138. // some helper variables
  13139. let radius = innerRadius;
  13140. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13141. const vertex = new Vector3();
  13142. const uv = new Vector2();
  13143. // generate vertices, normals and uvs
  13144. for ( let j = 0; j <= phiSegments; j ++ ) {
  13145. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13146. // values are generate from the inside of the ring to the outside
  13147. const segment = thetaStart + i / thetaSegments * thetaLength;
  13148. // vertex
  13149. vertex.x = radius * Math.cos( segment );
  13150. vertex.y = radius * Math.sin( segment );
  13151. vertices.push( vertex.x, vertex.y, vertex.z );
  13152. // normal
  13153. normals.push( 0, 0, 1 );
  13154. // uv
  13155. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13156. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13157. uvs.push( uv.x, uv.y );
  13158. }
  13159. // increase the radius for next row of vertices
  13160. radius += radiusStep;
  13161. }
  13162. // indices
  13163. for ( let j = 0; j < phiSegments; j ++ ) {
  13164. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13165. for ( let i = 0; i < thetaSegments; i ++ ) {
  13166. const segment = i + thetaSegmentLevel;
  13167. const a = segment;
  13168. const b = segment + thetaSegments + 1;
  13169. const c = segment + thetaSegments + 2;
  13170. const d = segment + 1;
  13171. // faces
  13172. indices.push( a, b, d );
  13173. indices.push( b, c, d );
  13174. }
  13175. }
  13176. // build geometry
  13177. this.setIndex( indices );
  13178. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13179. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13180. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13181. }
  13182. copy( source ) {
  13183. super.copy( source );
  13184. this.parameters = Object.assign( {}, source.parameters );
  13185. return this;
  13186. }
  13187. static fromJSON( data ) {
  13188. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13189. }
  13190. }
  13191. class ShapeGeometry extends BufferGeometry {
  13192. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13193. super();
  13194. this.type = 'ShapeGeometry';
  13195. this.parameters = {
  13196. shapes: shapes,
  13197. curveSegments: curveSegments
  13198. };
  13199. // buffers
  13200. const indices = [];
  13201. const vertices = [];
  13202. const normals = [];
  13203. const uvs = [];
  13204. // helper variables
  13205. let groupStart = 0;
  13206. let groupCount = 0;
  13207. // allow single and array values for "shapes" parameter
  13208. if ( Array.isArray( shapes ) === false ) {
  13209. addShape( shapes );
  13210. } else {
  13211. for ( let i = 0; i < shapes.length; i ++ ) {
  13212. addShape( shapes[ i ] );
  13213. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13214. groupStart += groupCount;
  13215. groupCount = 0;
  13216. }
  13217. }
  13218. // build geometry
  13219. this.setIndex( indices );
  13220. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13221. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13222. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13223. // helper functions
  13224. function addShape( shape ) {
  13225. const indexOffset = vertices.length / 3;
  13226. const points = shape.extractPoints( curveSegments );
  13227. let shapeVertices = points.shape;
  13228. const shapeHoles = points.holes;
  13229. // check direction of vertices
  13230. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13231. shapeVertices = shapeVertices.reverse();
  13232. }
  13233. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13234. const shapeHole = shapeHoles[ i ];
  13235. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13236. shapeHoles[ i ] = shapeHole.reverse();
  13237. }
  13238. }
  13239. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13240. // join vertices of inner and outer paths to a single array
  13241. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13242. const shapeHole = shapeHoles[ i ];
  13243. shapeVertices = shapeVertices.concat( shapeHole );
  13244. }
  13245. // vertices, normals, uvs
  13246. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13247. const vertex = shapeVertices[ i ];
  13248. vertices.push( vertex.x, vertex.y, 0 );
  13249. normals.push( 0, 0, 1 );
  13250. uvs.push( vertex.x, vertex.y ); // world uvs
  13251. }
  13252. // indices
  13253. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13254. const face = faces[ i ];
  13255. const a = face[ 0 ] + indexOffset;
  13256. const b = face[ 1 ] + indexOffset;
  13257. const c = face[ 2 ] + indexOffset;
  13258. indices.push( a, b, c );
  13259. groupCount += 3;
  13260. }
  13261. }
  13262. }
  13263. copy( source ) {
  13264. super.copy( source );
  13265. this.parameters = Object.assign( {}, source.parameters );
  13266. return this;
  13267. }
  13268. toJSON() {
  13269. const data = super.toJSON();
  13270. const shapes = this.parameters.shapes;
  13271. return toJSON( shapes, data );
  13272. }
  13273. static fromJSON( data, shapes ) {
  13274. const geometryShapes = [];
  13275. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13276. const shape = shapes[ data.shapes[ j ] ];
  13277. geometryShapes.push( shape );
  13278. }
  13279. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13280. }
  13281. }
  13282. function toJSON( shapes, data ) {
  13283. data.shapes = [];
  13284. if ( Array.isArray( shapes ) ) {
  13285. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13286. const shape = shapes[ i ];
  13287. data.shapes.push( shape.uuid );
  13288. }
  13289. } else {
  13290. data.shapes.push( shapes.uuid );
  13291. }
  13292. return data;
  13293. }
  13294. class SphereGeometry extends BufferGeometry {
  13295. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13296. super();
  13297. this.type = 'SphereGeometry';
  13298. this.parameters = {
  13299. radius: radius,
  13300. widthSegments: widthSegments,
  13301. heightSegments: heightSegments,
  13302. phiStart: phiStart,
  13303. phiLength: phiLength,
  13304. thetaStart: thetaStart,
  13305. thetaLength: thetaLength
  13306. };
  13307. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13308. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13309. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13310. let index = 0;
  13311. const grid = [];
  13312. const vertex = new Vector3();
  13313. const normal = new Vector3();
  13314. // buffers
  13315. const indices = [];
  13316. const vertices = [];
  13317. const normals = [];
  13318. const uvs = [];
  13319. // generate vertices, normals and uvs
  13320. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13321. const verticesRow = [];
  13322. const v = iy / heightSegments;
  13323. // special case for the poles
  13324. let uOffset = 0;
  13325. if ( iy === 0 && thetaStart === 0 ) {
  13326. uOffset = 0.5 / widthSegments;
  13327. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13328. uOffset = - 0.5 / widthSegments;
  13329. }
  13330. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13331. const u = ix / widthSegments;
  13332. // vertex
  13333. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13334. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13335. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13336. vertices.push( vertex.x, vertex.y, vertex.z );
  13337. // normal
  13338. normal.copy( vertex ).normalize();
  13339. normals.push( normal.x, normal.y, normal.z );
  13340. // uv
  13341. uvs.push( u + uOffset, 1 - v );
  13342. verticesRow.push( index ++ );
  13343. }
  13344. grid.push( verticesRow );
  13345. }
  13346. // indices
  13347. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13348. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13349. const a = grid[ iy ][ ix + 1 ];
  13350. const b = grid[ iy ][ ix ];
  13351. const c = grid[ iy + 1 ][ ix ];
  13352. const d = grid[ iy + 1 ][ ix + 1 ];
  13353. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13354. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13355. }
  13356. }
  13357. // build geometry
  13358. this.setIndex( indices );
  13359. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13360. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13361. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13362. }
  13363. copy( source ) {
  13364. super.copy( source );
  13365. this.parameters = Object.assign( {}, source.parameters );
  13366. return this;
  13367. }
  13368. static fromJSON( data ) {
  13369. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13370. }
  13371. }
  13372. class TetrahedronGeometry extends PolyhedronGeometry {
  13373. constructor( radius = 1, detail = 0 ) {
  13374. const vertices = [
  13375. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13376. ];
  13377. const indices = [
  13378. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13379. ];
  13380. super( vertices, indices, radius, detail );
  13381. this.type = 'TetrahedronGeometry';
  13382. this.parameters = {
  13383. radius: radius,
  13384. detail: detail
  13385. };
  13386. }
  13387. static fromJSON( data ) {
  13388. return new TetrahedronGeometry( data.radius, data.detail );
  13389. }
  13390. }
  13391. class TorusGeometry extends BufferGeometry {
  13392. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13393. super();
  13394. this.type = 'TorusGeometry';
  13395. this.parameters = {
  13396. radius: radius,
  13397. tube: tube,
  13398. radialSegments: radialSegments,
  13399. tubularSegments: tubularSegments,
  13400. arc: arc
  13401. };
  13402. radialSegments = Math.floor( radialSegments );
  13403. tubularSegments = Math.floor( tubularSegments );
  13404. // buffers
  13405. const indices = [];
  13406. const vertices = [];
  13407. const normals = [];
  13408. const uvs = [];
  13409. // helper variables
  13410. const center = new Vector3();
  13411. const vertex = new Vector3();
  13412. const normal = new Vector3();
  13413. // generate vertices, normals and uvs
  13414. for ( let j = 0; j <= radialSegments; j ++ ) {
  13415. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13416. const u = i / tubularSegments * arc;
  13417. const v = j / radialSegments * Math.PI * 2;
  13418. // vertex
  13419. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13420. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13421. vertex.z = tube * Math.sin( v );
  13422. vertices.push( vertex.x, vertex.y, vertex.z );
  13423. // normal
  13424. center.x = radius * Math.cos( u );
  13425. center.y = radius * Math.sin( u );
  13426. normal.subVectors( vertex, center ).normalize();
  13427. normals.push( normal.x, normal.y, normal.z );
  13428. // uv
  13429. uvs.push( i / tubularSegments );
  13430. uvs.push( j / radialSegments );
  13431. }
  13432. }
  13433. // generate indices
  13434. for ( let j = 1; j <= radialSegments; j ++ ) {
  13435. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13436. // indices
  13437. const a = ( tubularSegments + 1 ) * j + i - 1;
  13438. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13439. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13440. const d = ( tubularSegments + 1 ) * j + i;
  13441. // faces
  13442. indices.push( a, b, d );
  13443. indices.push( b, c, d );
  13444. }
  13445. }
  13446. // build geometry
  13447. this.setIndex( indices );
  13448. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13449. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13450. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13451. }
  13452. copy( source ) {
  13453. super.copy( source );
  13454. this.parameters = Object.assign( {}, source.parameters );
  13455. return this;
  13456. }
  13457. static fromJSON( data ) {
  13458. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13459. }
  13460. }
  13461. class TorusKnotGeometry extends BufferGeometry {
  13462. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13463. super();
  13464. this.type = 'TorusKnotGeometry';
  13465. this.parameters = {
  13466. radius: radius,
  13467. tube: tube,
  13468. tubularSegments: tubularSegments,
  13469. radialSegments: radialSegments,
  13470. p: p,
  13471. q: q
  13472. };
  13473. tubularSegments = Math.floor( tubularSegments );
  13474. radialSegments = Math.floor( radialSegments );
  13475. // buffers
  13476. const indices = [];
  13477. const vertices = [];
  13478. const normals = [];
  13479. const uvs = [];
  13480. // helper variables
  13481. const vertex = new Vector3();
  13482. const normal = new Vector3();
  13483. const P1 = new Vector3();
  13484. const P2 = new Vector3();
  13485. const B = new Vector3();
  13486. const T = new Vector3();
  13487. const N = new Vector3();
  13488. // generate vertices, normals and uvs
  13489. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13490. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13491. const u = i / tubularSegments * p * Math.PI * 2;
  13492. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13493. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13494. calculatePositionOnCurve( u, p, q, radius, P1 );
  13495. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13496. // calculate orthonormal basis
  13497. T.subVectors( P2, P1 );
  13498. N.addVectors( P2, P1 );
  13499. B.crossVectors( T, N );
  13500. N.crossVectors( B, T );
  13501. // normalize B, N. T can be ignored, we don't use it
  13502. B.normalize();
  13503. N.normalize();
  13504. for ( let j = 0; j <= radialSegments; ++ j ) {
  13505. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13506. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13507. const v = j / radialSegments * Math.PI * 2;
  13508. const cx = - tube * Math.cos( v );
  13509. const cy = tube * Math.sin( v );
  13510. // now calculate the final vertex position.
  13511. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13512. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13513. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13514. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13515. vertices.push( vertex.x, vertex.y, vertex.z );
  13516. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13517. normal.subVectors( vertex, P1 ).normalize();
  13518. normals.push( normal.x, normal.y, normal.z );
  13519. // uv
  13520. uvs.push( i / tubularSegments );
  13521. uvs.push( j / radialSegments );
  13522. }
  13523. }
  13524. // generate indices
  13525. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13526. for ( let i = 1; i <= radialSegments; i ++ ) {
  13527. // indices
  13528. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13529. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13530. const c = ( radialSegments + 1 ) * j + i;
  13531. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13532. // faces
  13533. indices.push( a, b, d );
  13534. indices.push( b, c, d );
  13535. }
  13536. }
  13537. // build geometry
  13538. this.setIndex( indices );
  13539. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13540. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13541. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13542. // this function calculates the current position on the torus curve
  13543. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13544. const cu = Math.cos( u );
  13545. const su = Math.sin( u );
  13546. const quOverP = q / p * u;
  13547. const cs = Math.cos( quOverP );
  13548. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13549. position.y = radius * ( 2 + cs ) * su * 0.5;
  13550. position.z = radius * Math.sin( quOverP ) * 0.5;
  13551. }
  13552. }
  13553. copy( source ) {
  13554. super.copy( source );
  13555. this.parameters = Object.assign( {}, source.parameters );
  13556. return this;
  13557. }
  13558. static fromJSON( data ) {
  13559. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13560. }
  13561. }
  13562. class TubeGeometry extends BufferGeometry {
  13563. 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 ) {
  13564. super();
  13565. this.type = 'TubeGeometry';
  13566. this.parameters = {
  13567. path: path,
  13568. tubularSegments: tubularSegments,
  13569. radius: radius,
  13570. radialSegments: radialSegments,
  13571. closed: closed
  13572. };
  13573. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13574. // expose internals
  13575. this.tangents = frames.tangents;
  13576. this.normals = frames.normals;
  13577. this.binormals = frames.binormals;
  13578. // helper variables
  13579. const vertex = new Vector3();
  13580. const normal = new Vector3();
  13581. const uv = new Vector2();
  13582. let P = new Vector3();
  13583. // buffer
  13584. const vertices = [];
  13585. const normals = [];
  13586. const uvs = [];
  13587. const indices = [];
  13588. // create buffer data
  13589. generateBufferData();
  13590. // build geometry
  13591. this.setIndex( indices );
  13592. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13593. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13594. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13595. // functions
  13596. function generateBufferData() {
  13597. for ( let i = 0; i < tubularSegments; i ++ ) {
  13598. generateSegment( i );
  13599. }
  13600. // if the geometry is not closed, generate the last row of vertices and normals
  13601. // at the regular position on the given path
  13602. //
  13603. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13604. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13605. // uvs are generated in a separate function.
  13606. // this makes it easy compute correct values for closed geometries
  13607. generateUVs();
  13608. // finally create faces
  13609. generateIndices();
  13610. }
  13611. function generateSegment( i ) {
  13612. // we use getPointAt to sample evenly distributed points from the given path
  13613. P = path.getPointAt( i / tubularSegments, P );
  13614. // retrieve corresponding normal and binormal
  13615. const N = frames.normals[ i ];
  13616. const B = frames.binormals[ i ];
  13617. // generate normals and vertices for the current segment
  13618. for ( let j = 0; j <= radialSegments; j ++ ) {
  13619. const v = j / radialSegments * Math.PI * 2;
  13620. const sin = Math.sin( v );
  13621. const cos = - Math.cos( v );
  13622. // normal
  13623. normal.x = ( cos * N.x + sin * B.x );
  13624. normal.y = ( cos * N.y + sin * B.y );
  13625. normal.z = ( cos * N.z + sin * B.z );
  13626. normal.normalize();
  13627. normals.push( normal.x, normal.y, normal.z );
  13628. // vertex
  13629. vertex.x = P.x + radius * normal.x;
  13630. vertex.y = P.y + radius * normal.y;
  13631. vertex.z = P.z + radius * normal.z;
  13632. vertices.push( vertex.x, vertex.y, vertex.z );
  13633. }
  13634. }
  13635. function generateIndices() {
  13636. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13637. for ( let i = 1; i <= radialSegments; i ++ ) {
  13638. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13639. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13640. const c = ( radialSegments + 1 ) * j + i;
  13641. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13642. // faces
  13643. indices.push( a, b, d );
  13644. indices.push( b, c, d );
  13645. }
  13646. }
  13647. }
  13648. function generateUVs() {
  13649. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13650. for ( let j = 0; j <= radialSegments; j ++ ) {
  13651. uv.x = i / tubularSegments;
  13652. uv.y = j / radialSegments;
  13653. uvs.push( uv.x, uv.y );
  13654. }
  13655. }
  13656. }
  13657. }
  13658. copy( source ) {
  13659. super.copy( source );
  13660. this.parameters = Object.assign( {}, source.parameters );
  13661. return this;
  13662. }
  13663. toJSON() {
  13664. const data = super.toJSON();
  13665. data.path = this.parameters.path.toJSON();
  13666. return data;
  13667. }
  13668. static fromJSON( data ) {
  13669. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13670. // User defined curves or instances of CurvePath will not be deserialized.
  13671. return new TubeGeometry(
  13672. new Curves[ data.path.type ]().fromJSON( data.path ),
  13673. data.tubularSegments,
  13674. data.radius,
  13675. data.radialSegments,
  13676. data.closed
  13677. );
  13678. }
  13679. }
  13680. class WireframeGeometry extends BufferGeometry {
  13681. constructor( geometry = null ) {
  13682. super();
  13683. this.type = 'WireframeGeometry';
  13684. this.parameters = {
  13685. geometry: geometry
  13686. };
  13687. if ( geometry !== null ) {
  13688. // buffer
  13689. const vertices = [];
  13690. const edges = new Set();
  13691. // helper variables
  13692. const start = new Vector3();
  13693. const end = new Vector3();
  13694. if ( geometry.index !== null ) {
  13695. // indexed BufferGeometry
  13696. const position = geometry.attributes.position;
  13697. const indices = geometry.index;
  13698. let groups = geometry.groups;
  13699. if ( groups.length === 0 ) {
  13700. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13701. }
  13702. // create a data structure that contains all edges without duplicates
  13703. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13704. const group = groups[ o ];
  13705. const groupStart = group.start;
  13706. const groupCount = group.count;
  13707. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13708. for ( let j = 0; j < 3; j ++ ) {
  13709. const index1 = indices.getX( i + j );
  13710. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13711. start.fromBufferAttribute( position, index1 );
  13712. end.fromBufferAttribute( position, index2 );
  13713. if ( isUniqueEdge( start, end, edges ) === true ) {
  13714. vertices.push( start.x, start.y, start.z );
  13715. vertices.push( end.x, end.y, end.z );
  13716. }
  13717. }
  13718. }
  13719. }
  13720. } else {
  13721. // non-indexed BufferGeometry
  13722. const position = geometry.attributes.position;
  13723. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13724. for ( let j = 0; j < 3; j ++ ) {
  13725. // three edges per triangle, an edge is represented as (index1, index2)
  13726. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13727. const index1 = 3 * i + j;
  13728. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13729. start.fromBufferAttribute( position, index1 );
  13730. end.fromBufferAttribute( position, index2 );
  13731. if ( isUniqueEdge( start, end, edges ) === true ) {
  13732. vertices.push( start.x, start.y, start.z );
  13733. vertices.push( end.x, end.y, end.z );
  13734. }
  13735. }
  13736. }
  13737. }
  13738. // build geometry
  13739. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13740. }
  13741. }
  13742. copy( source ) {
  13743. super.copy( source );
  13744. this.parameters = Object.assign( {}, source.parameters );
  13745. return this;
  13746. }
  13747. }
  13748. function isUniqueEdge( start, end, edges ) {
  13749. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13750. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13751. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13752. return false;
  13753. } else {
  13754. edges.add( hash1 );
  13755. edges.add( hash2 );
  13756. return true;
  13757. }
  13758. }
  13759. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13760. __proto__: null,
  13761. BoxGeometry: BoxGeometry,
  13762. CapsuleGeometry: CapsuleGeometry,
  13763. CircleGeometry: CircleGeometry,
  13764. ConeGeometry: ConeGeometry,
  13765. CylinderGeometry: CylinderGeometry,
  13766. DodecahedronGeometry: DodecahedronGeometry,
  13767. EdgesGeometry: EdgesGeometry,
  13768. ExtrudeGeometry: ExtrudeGeometry,
  13769. IcosahedronGeometry: IcosahedronGeometry,
  13770. LatheGeometry: LatheGeometry,
  13771. OctahedronGeometry: OctahedronGeometry,
  13772. PlaneGeometry: PlaneGeometry,
  13773. PolyhedronGeometry: PolyhedronGeometry,
  13774. RingGeometry: RingGeometry,
  13775. ShapeGeometry: ShapeGeometry,
  13776. SphereGeometry: SphereGeometry,
  13777. TetrahedronGeometry: TetrahedronGeometry,
  13778. TorusGeometry: TorusGeometry,
  13779. TorusKnotGeometry: TorusKnotGeometry,
  13780. TubeGeometry: TubeGeometry,
  13781. WireframeGeometry: WireframeGeometry
  13782. });
  13783. class ShadowMaterial extends Material {
  13784. constructor( parameters ) {
  13785. super();
  13786. this.isShadowMaterial = true;
  13787. this.type = 'ShadowMaterial';
  13788. this.color = new Color( 0x000000 );
  13789. this.transparent = true;
  13790. this.fog = true;
  13791. this.setValues( parameters );
  13792. }
  13793. copy( source ) {
  13794. super.copy( source );
  13795. this.color.copy( source.color );
  13796. this.fog = source.fog;
  13797. return this;
  13798. }
  13799. }
  13800. class RawShaderMaterial extends ShaderMaterial {
  13801. constructor( parameters ) {
  13802. super( parameters );
  13803. this.isRawShaderMaterial = true;
  13804. this.type = 'RawShaderMaterial';
  13805. }
  13806. }
  13807. class MeshStandardMaterial extends Material {
  13808. constructor( parameters ) {
  13809. super();
  13810. this.isMeshStandardMaterial = true;
  13811. this.defines = { 'STANDARD': '' };
  13812. this.type = 'MeshStandardMaterial';
  13813. this.color = new Color( 0xffffff ); // diffuse
  13814. this.roughness = 1.0;
  13815. this.metalness = 0.0;
  13816. this.map = null;
  13817. this.lightMap = null;
  13818. this.lightMapIntensity = 1.0;
  13819. this.aoMap = null;
  13820. this.aoMapIntensity = 1.0;
  13821. this.emissive = new Color( 0x000000 );
  13822. this.emissiveIntensity = 1.0;
  13823. this.emissiveMap = null;
  13824. this.bumpMap = null;
  13825. this.bumpScale = 1;
  13826. this.normalMap = null;
  13827. this.normalMapType = TangentSpaceNormalMap;
  13828. this.normalScale = new Vector2( 1, 1 );
  13829. this.displacementMap = null;
  13830. this.displacementScale = 1;
  13831. this.displacementBias = 0;
  13832. this.roughnessMap = null;
  13833. this.metalnessMap = null;
  13834. this.alphaMap = null;
  13835. this.envMap = null;
  13836. this.envMapRotation = new Euler();
  13837. this.envMapIntensity = 1.0;
  13838. this.wireframe = false;
  13839. this.wireframeLinewidth = 1;
  13840. this.wireframeLinecap = 'round';
  13841. this.wireframeLinejoin = 'round';
  13842. this.flatShading = false;
  13843. this.fog = true;
  13844. this.setValues( parameters );
  13845. }
  13846. copy( source ) {
  13847. super.copy( source );
  13848. this.defines = { 'STANDARD': '' };
  13849. this.color.copy( source.color );
  13850. this.roughness = source.roughness;
  13851. this.metalness = source.metalness;
  13852. this.map = source.map;
  13853. this.lightMap = source.lightMap;
  13854. this.lightMapIntensity = source.lightMapIntensity;
  13855. this.aoMap = source.aoMap;
  13856. this.aoMapIntensity = source.aoMapIntensity;
  13857. this.emissive.copy( source.emissive );
  13858. this.emissiveMap = source.emissiveMap;
  13859. this.emissiveIntensity = source.emissiveIntensity;
  13860. this.bumpMap = source.bumpMap;
  13861. this.bumpScale = source.bumpScale;
  13862. this.normalMap = source.normalMap;
  13863. this.normalMapType = source.normalMapType;
  13864. this.normalScale.copy( source.normalScale );
  13865. this.displacementMap = source.displacementMap;
  13866. this.displacementScale = source.displacementScale;
  13867. this.displacementBias = source.displacementBias;
  13868. this.roughnessMap = source.roughnessMap;
  13869. this.metalnessMap = source.metalnessMap;
  13870. this.alphaMap = source.alphaMap;
  13871. this.envMap = source.envMap;
  13872. this.envMapRotation.copy( source.envMapRotation );
  13873. this.envMapIntensity = source.envMapIntensity;
  13874. this.wireframe = source.wireframe;
  13875. this.wireframeLinewidth = source.wireframeLinewidth;
  13876. this.wireframeLinecap = source.wireframeLinecap;
  13877. this.wireframeLinejoin = source.wireframeLinejoin;
  13878. this.flatShading = source.flatShading;
  13879. this.fog = source.fog;
  13880. return this;
  13881. }
  13882. }
  13883. class MeshPhysicalMaterial extends MeshStandardMaterial {
  13884. constructor( parameters ) {
  13885. super();
  13886. this.isMeshPhysicalMaterial = true;
  13887. this.defines = {
  13888. 'STANDARD': '',
  13889. 'PHYSICAL': ''
  13890. };
  13891. this.type = 'MeshPhysicalMaterial';
  13892. this.anisotropyRotation = 0;
  13893. this.anisotropyMap = null;
  13894. this.clearcoatMap = null;
  13895. this.clearcoatRoughness = 0.0;
  13896. this.clearcoatRoughnessMap = null;
  13897. this.clearcoatNormalScale = new Vector2( 1, 1 );
  13898. this.clearcoatNormalMap = null;
  13899. this.ior = 1.5;
  13900. Object.defineProperty( this, 'reflectivity', {
  13901. get: function () {
  13902. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  13903. },
  13904. set: function ( reflectivity ) {
  13905. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  13906. }
  13907. } );
  13908. this.iridescenceMap = null;
  13909. this.iridescenceIOR = 1.3;
  13910. this.iridescenceThicknessRange = [ 100, 400 ];
  13911. this.iridescenceThicknessMap = null;
  13912. this.sheenColor = new Color( 0x000000 );
  13913. this.sheenColorMap = null;
  13914. this.sheenRoughness = 1.0;
  13915. this.sheenRoughnessMap = null;
  13916. this.transmissionMap = null;
  13917. this.thickness = 0;
  13918. this.thicknessMap = null;
  13919. this.attenuationDistance = Infinity;
  13920. this.attenuationColor = new Color( 1, 1, 1 );
  13921. this.specularIntensity = 1.0;
  13922. this.specularIntensityMap = null;
  13923. this.specularColor = new Color( 1, 1, 1 );
  13924. this.specularColorMap = null;
  13925. this._anisotropy = 0;
  13926. this._clearcoat = 0;
  13927. this._dispersion = 0;
  13928. this._iridescence = 0;
  13929. this._sheen = 0.0;
  13930. this._transmission = 0;
  13931. this.setValues( parameters );
  13932. }
  13933. get anisotropy() {
  13934. return this._anisotropy;
  13935. }
  13936. set anisotropy( value ) {
  13937. if ( this._anisotropy > 0 !== value > 0 ) {
  13938. this.version ++;
  13939. }
  13940. this._anisotropy = value;
  13941. }
  13942. get clearcoat() {
  13943. return this._clearcoat;
  13944. }
  13945. set clearcoat( value ) {
  13946. if ( this._clearcoat > 0 !== value > 0 ) {
  13947. this.version ++;
  13948. }
  13949. this._clearcoat = value;
  13950. }
  13951. get iridescence() {
  13952. return this._iridescence;
  13953. }
  13954. set iridescence( value ) {
  13955. if ( this._iridescence > 0 !== value > 0 ) {
  13956. this.version ++;
  13957. }
  13958. this._iridescence = value;
  13959. }
  13960. get dispersion() {
  13961. return this._dispersion;
  13962. }
  13963. set dispersion( value ) {
  13964. if ( this._dispersion > 0 !== value > 0 ) {
  13965. this.version ++;
  13966. }
  13967. this._dispersion = value;
  13968. }
  13969. get sheen() {
  13970. return this._sheen;
  13971. }
  13972. set sheen( value ) {
  13973. if ( this._sheen > 0 !== value > 0 ) {
  13974. this.version ++;
  13975. }
  13976. this._sheen = value;
  13977. }
  13978. get transmission() {
  13979. return this._transmission;
  13980. }
  13981. set transmission( value ) {
  13982. if ( this._transmission > 0 !== value > 0 ) {
  13983. this.version ++;
  13984. }
  13985. this._transmission = value;
  13986. }
  13987. copy( source ) {
  13988. super.copy( source );
  13989. this.defines = {
  13990. 'STANDARD': '',
  13991. 'PHYSICAL': ''
  13992. };
  13993. this.anisotropy = source.anisotropy;
  13994. this.anisotropyRotation = source.anisotropyRotation;
  13995. this.anisotropyMap = source.anisotropyMap;
  13996. this.clearcoat = source.clearcoat;
  13997. this.clearcoatMap = source.clearcoatMap;
  13998. this.clearcoatRoughness = source.clearcoatRoughness;
  13999. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14000. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14001. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14002. this.dispersion = source.dispersion;
  14003. this.ior = source.ior;
  14004. this.iridescence = source.iridescence;
  14005. this.iridescenceMap = source.iridescenceMap;
  14006. this.iridescenceIOR = source.iridescenceIOR;
  14007. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14008. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14009. this.sheen = source.sheen;
  14010. this.sheenColor.copy( source.sheenColor );
  14011. this.sheenColorMap = source.sheenColorMap;
  14012. this.sheenRoughness = source.sheenRoughness;
  14013. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14014. this.transmission = source.transmission;
  14015. this.transmissionMap = source.transmissionMap;
  14016. this.thickness = source.thickness;
  14017. this.thicknessMap = source.thicknessMap;
  14018. this.attenuationDistance = source.attenuationDistance;
  14019. this.attenuationColor.copy( source.attenuationColor );
  14020. this.specularIntensity = source.specularIntensity;
  14021. this.specularIntensityMap = source.specularIntensityMap;
  14022. this.specularColor.copy( source.specularColor );
  14023. this.specularColorMap = source.specularColorMap;
  14024. return this;
  14025. }
  14026. }
  14027. class MeshPhongMaterial extends Material {
  14028. constructor( parameters ) {
  14029. super();
  14030. this.isMeshPhongMaterial = true;
  14031. this.type = 'MeshPhongMaterial';
  14032. this.color = new Color( 0xffffff ); // diffuse
  14033. this.specular = new Color( 0x111111 );
  14034. this.shininess = 30;
  14035. this.map = null;
  14036. this.lightMap = null;
  14037. this.lightMapIntensity = 1.0;
  14038. this.aoMap = null;
  14039. this.aoMapIntensity = 1.0;
  14040. this.emissive = new Color( 0x000000 );
  14041. this.emissiveIntensity = 1.0;
  14042. this.emissiveMap = null;
  14043. this.bumpMap = null;
  14044. this.bumpScale = 1;
  14045. this.normalMap = null;
  14046. this.normalMapType = TangentSpaceNormalMap;
  14047. this.normalScale = new Vector2( 1, 1 );
  14048. this.displacementMap = null;
  14049. this.displacementScale = 1;
  14050. this.displacementBias = 0;
  14051. this.specularMap = null;
  14052. this.alphaMap = null;
  14053. this.envMap = null;
  14054. this.envMapRotation = new Euler();
  14055. this.combine = MultiplyOperation;
  14056. this.reflectivity = 1;
  14057. this.refractionRatio = 0.98;
  14058. this.wireframe = false;
  14059. this.wireframeLinewidth = 1;
  14060. this.wireframeLinecap = 'round';
  14061. this.wireframeLinejoin = 'round';
  14062. this.flatShading = false;
  14063. this.fog = true;
  14064. this.setValues( parameters );
  14065. }
  14066. copy( source ) {
  14067. super.copy( source );
  14068. this.color.copy( source.color );
  14069. this.specular.copy( source.specular );
  14070. this.shininess = source.shininess;
  14071. this.map = source.map;
  14072. this.lightMap = source.lightMap;
  14073. this.lightMapIntensity = source.lightMapIntensity;
  14074. this.aoMap = source.aoMap;
  14075. this.aoMapIntensity = source.aoMapIntensity;
  14076. this.emissive.copy( source.emissive );
  14077. this.emissiveMap = source.emissiveMap;
  14078. this.emissiveIntensity = source.emissiveIntensity;
  14079. this.bumpMap = source.bumpMap;
  14080. this.bumpScale = source.bumpScale;
  14081. this.normalMap = source.normalMap;
  14082. this.normalMapType = source.normalMapType;
  14083. this.normalScale.copy( source.normalScale );
  14084. this.displacementMap = source.displacementMap;
  14085. this.displacementScale = source.displacementScale;
  14086. this.displacementBias = source.displacementBias;
  14087. this.specularMap = source.specularMap;
  14088. this.alphaMap = source.alphaMap;
  14089. this.envMap = source.envMap;
  14090. this.envMapRotation.copy( source.envMapRotation );
  14091. this.combine = source.combine;
  14092. this.reflectivity = source.reflectivity;
  14093. this.refractionRatio = source.refractionRatio;
  14094. this.wireframe = source.wireframe;
  14095. this.wireframeLinewidth = source.wireframeLinewidth;
  14096. this.wireframeLinecap = source.wireframeLinecap;
  14097. this.wireframeLinejoin = source.wireframeLinejoin;
  14098. this.flatShading = source.flatShading;
  14099. this.fog = source.fog;
  14100. return this;
  14101. }
  14102. }
  14103. class MeshToonMaterial extends Material {
  14104. constructor( parameters ) {
  14105. super();
  14106. this.isMeshToonMaterial = true;
  14107. this.defines = { 'TOON': '' };
  14108. this.type = 'MeshToonMaterial';
  14109. this.color = new Color( 0xffffff );
  14110. this.map = null;
  14111. this.gradientMap = null;
  14112. this.lightMap = null;
  14113. this.lightMapIntensity = 1.0;
  14114. this.aoMap = null;
  14115. this.aoMapIntensity = 1.0;
  14116. this.emissive = new Color( 0x000000 );
  14117. this.emissiveIntensity = 1.0;
  14118. this.emissiveMap = null;
  14119. this.bumpMap = null;
  14120. this.bumpScale = 1;
  14121. this.normalMap = null;
  14122. this.normalMapType = TangentSpaceNormalMap;
  14123. this.normalScale = new Vector2( 1, 1 );
  14124. this.displacementMap = null;
  14125. this.displacementScale = 1;
  14126. this.displacementBias = 0;
  14127. this.alphaMap = null;
  14128. this.wireframe = false;
  14129. this.wireframeLinewidth = 1;
  14130. this.wireframeLinecap = 'round';
  14131. this.wireframeLinejoin = 'round';
  14132. this.fog = true;
  14133. this.setValues( parameters );
  14134. }
  14135. copy( source ) {
  14136. super.copy( source );
  14137. this.color.copy( source.color );
  14138. this.map = source.map;
  14139. this.gradientMap = source.gradientMap;
  14140. this.lightMap = source.lightMap;
  14141. this.lightMapIntensity = source.lightMapIntensity;
  14142. this.aoMap = source.aoMap;
  14143. this.aoMapIntensity = source.aoMapIntensity;
  14144. this.emissive.copy( source.emissive );
  14145. this.emissiveMap = source.emissiveMap;
  14146. this.emissiveIntensity = source.emissiveIntensity;
  14147. this.bumpMap = source.bumpMap;
  14148. this.bumpScale = source.bumpScale;
  14149. this.normalMap = source.normalMap;
  14150. this.normalMapType = source.normalMapType;
  14151. this.normalScale.copy( source.normalScale );
  14152. this.displacementMap = source.displacementMap;
  14153. this.displacementScale = source.displacementScale;
  14154. this.displacementBias = source.displacementBias;
  14155. this.alphaMap = source.alphaMap;
  14156. this.wireframe = source.wireframe;
  14157. this.wireframeLinewidth = source.wireframeLinewidth;
  14158. this.wireframeLinecap = source.wireframeLinecap;
  14159. this.wireframeLinejoin = source.wireframeLinejoin;
  14160. this.fog = source.fog;
  14161. return this;
  14162. }
  14163. }
  14164. class MeshNormalMaterial extends Material {
  14165. constructor( parameters ) {
  14166. super();
  14167. this.isMeshNormalMaterial = true;
  14168. this.type = 'MeshNormalMaterial';
  14169. this.bumpMap = null;
  14170. this.bumpScale = 1;
  14171. this.normalMap = null;
  14172. this.normalMapType = TangentSpaceNormalMap;
  14173. this.normalScale = new Vector2( 1, 1 );
  14174. this.displacementMap = null;
  14175. this.displacementScale = 1;
  14176. this.displacementBias = 0;
  14177. this.wireframe = false;
  14178. this.wireframeLinewidth = 1;
  14179. this.flatShading = false;
  14180. this.setValues( parameters );
  14181. }
  14182. copy( source ) {
  14183. super.copy( source );
  14184. this.bumpMap = source.bumpMap;
  14185. this.bumpScale = source.bumpScale;
  14186. this.normalMap = source.normalMap;
  14187. this.normalMapType = source.normalMapType;
  14188. this.normalScale.copy( source.normalScale );
  14189. this.displacementMap = source.displacementMap;
  14190. this.displacementScale = source.displacementScale;
  14191. this.displacementBias = source.displacementBias;
  14192. this.wireframe = source.wireframe;
  14193. this.wireframeLinewidth = source.wireframeLinewidth;
  14194. this.flatShading = source.flatShading;
  14195. return this;
  14196. }
  14197. }
  14198. class MeshLambertMaterial extends Material {
  14199. constructor( parameters ) {
  14200. super();
  14201. this.isMeshLambertMaterial = true;
  14202. this.type = 'MeshLambertMaterial';
  14203. this.color = new Color( 0xffffff ); // diffuse
  14204. this.map = null;
  14205. this.lightMap = null;
  14206. this.lightMapIntensity = 1.0;
  14207. this.aoMap = null;
  14208. this.aoMapIntensity = 1.0;
  14209. this.emissive = new Color( 0x000000 );
  14210. this.emissiveIntensity = 1.0;
  14211. this.emissiveMap = null;
  14212. this.bumpMap = null;
  14213. this.bumpScale = 1;
  14214. this.normalMap = null;
  14215. this.normalMapType = TangentSpaceNormalMap;
  14216. this.normalScale = new Vector2( 1, 1 );
  14217. this.displacementMap = null;
  14218. this.displacementScale = 1;
  14219. this.displacementBias = 0;
  14220. this.specularMap = null;
  14221. this.alphaMap = null;
  14222. this.envMap = null;
  14223. this.envMapRotation = new Euler();
  14224. this.combine = MultiplyOperation;
  14225. this.reflectivity = 1;
  14226. this.refractionRatio = 0.98;
  14227. this.wireframe = false;
  14228. this.wireframeLinewidth = 1;
  14229. this.wireframeLinecap = 'round';
  14230. this.wireframeLinejoin = 'round';
  14231. this.flatShading = false;
  14232. this.fog = true;
  14233. this.setValues( parameters );
  14234. }
  14235. copy( source ) {
  14236. super.copy( source );
  14237. this.color.copy( source.color );
  14238. this.map = source.map;
  14239. this.lightMap = source.lightMap;
  14240. this.lightMapIntensity = source.lightMapIntensity;
  14241. this.aoMap = source.aoMap;
  14242. this.aoMapIntensity = source.aoMapIntensity;
  14243. this.emissive.copy( source.emissive );
  14244. this.emissiveMap = source.emissiveMap;
  14245. this.emissiveIntensity = source.emissiveIntensity;
  14246. this.bumpMap = source.bumpMap;
  14247. this.bumpScale = source.bumpScale;
  14248. this.normalMap = source.normalMap;
  14249. this.normalMapType = source.normalMapType;
  14250. this.normalScale.copy( source.normalScale );
  14251. this.displacementMap = source.displacementMap;
  14252. this.displacementScale = source.displacementScale;
  14253. this.displacementBias = source.displacementBias;
  14254. this.specularMap = source.specularMap;
  14255. this.alphaMap = source.alphaMap;
  14256. this.envMap = source.envMap;
  14257. this.envMapRotation.copy( source.envMapRotation );
  14258. this.combine = source.combine;
  14259. this.reflectivity = source.reflectivity;
  14260. this.refractionRatio = source.refractionRatio;
  14261. this.wireframe = source.wireframe;
  14262. this.wireframeLinewidth = source.wireframeLinewidth;
  14263. this.wireframeLinecap = source.wireframeLinecap;
  14264. this.wireframeLinejoin = source.wireframeLinejoin;
  14265. this.flatShading = source.flatShading;
  14266. this.fog = source.fog;
  14267. return this;
  14268. }
  14269. }
  14270. class MeshDepthMaterial extends Material {
  14271. constructor( parameters ) {
  14272. super();
  14273. this.isMeshDepthMaterial = true;
  14274. this.type = 'MeshDepthMaterial';
  14275. this.depthPacking = BasicDepthPacking;
  14276. this.map = null;
  14277. this.alphaMap = null;
  14278. this.displacementMap = null;
  14279. this.displacementScale = 1;
  14280. this.displacementBias = 0;
  14281. this.wireframe = false;
  14282. this.wireframeLinewidth = 1;
  14283. this.setValues( parameters );
  14284. }
  14285. copy( source ) {
  14286. super.copy( source );
  14287. this.depthPacking = source.depthPacking;
  14288. this.map = source.map;
  14289. this.alphaMap = source.alphaMap;
  14290. this.displacementMap = source.displacementMap;
  14291. this.displacementScale = source.displacementScale;
  14292. this.displacementBias = source.displacementBias;
  14293. this.wireframe = source.wireframe;
  14294. this.wireframeLinewidth = source.wireframeLinewidth;
  14295. return this;
  14296. }
  14297. }
  14298. class MeshDistanceMaterial extends Material {
  14299. constructor( parameters ) {
  14300. super();
  14301. this.isMeshDistanceMaterial = true;
  14302. this.type = 'MeshDistanceMaterial';
  14303. this.map = null;
  14304. this.alphaMap = null;
  14305. this.displacementMap = null;
  14306. this.displacementScale = 1;
  14307. this.displacementBias = 0;
  14308. this.setValues( parameters );
  14309. }
  14310. copy( source ) {
  14311. super.copy( source );
  14312. this.map = source.map;
  14313. this.alphaMap = source.alphaMap;
  14314. this.displacementMap = source.displacementMap;
  14315. this.displacementScale = source.displacementScale;
  14316. this.displacementBias = source.displacementBias;
  14317. return this;
  14318. }
  14319. }
  14320. class MeshMatcapMaterial extends Material {
  14321. constructor( parameters ) {
  14322. super();
  14323. this.isMeshMatcapMaterial = true;
  14324. this.defines = { 'MATCAP': '' };
  14325. this.type = 'MeshMatcapMaterial';
  14326. this.color = new Color( 0xffffff ); // diffuse
  14327. this.matcap = null;
  14328. this.map = null;
  14329. this.bumpMap = null;
  14330. this.bumpScale = 1;
  14331. this.normalMap = null;
  14332. this.normalMapType = TangentSpaceNormalMap;
  14333. this.normalScale = new Vector2( 1, 1 );
  14334. this.displacementMap = null;
  14335. this.displacementScale = 1;
  14336. this.displacementBias = 0;
  14337. this.alphaMap = null;
  14338. this.flatShading = false;
  14339. this.fog = true;
  14340. this.setValues( parameters );
  14341. }
  14342. copy( source ) {
  14343. super.copy( source );
  14344. this.defines = { 'MATCAP': '' };
  14345. this.color.copy( source.color );
  14346. this.matcap = source.matcap;
  14347. this.map = source.map;
  14348. this.bumpMap = source.bumpMap;
  14349. this.bumpScale = source.bumpScale;
  14350. this.normalMap = source.normalMap;
  14351. this.normalMapType = source.normalMapType;
  14352. this.normalScale.copy( source.normalScale );
  14353. this.displacementMap = source.displacementMap;
  14354. this.displacementScale = source.displacementScale;
  14355. this.displacementBias = source.displacementBias;
  14356. this.alphaMap = source.alphaMap;
  14357. this.flatShading = source.flatShading;
  14358. this.fog = source.fog;
  14359. return this;
  14360. }
  14361. }
  14362. class LineDashedMaterial extends LineBasicMaterial {
  14363. constructor( parameters ) {
  14364. super();
  14365. this.isLineDashedMaterial = true;
  14366. this.type = 'LineDashedMaterial';
  14367. this.scale = 1;
  14368. this.dashSize = 3;
  14369. this.gapSize = 1;
  14370. this.setValues( parameters );
  14371. }
  14372. copy( source ) {
  14373. super.copy( source );
  14374. this.scale = source.scale;
  14375. this.dashSize = source.dashSize;
  14376. this.gapSize = source.gapSize;
  14377. return this;
  14378. }
  14379. }
  14380. // converts an array to a specific type
  14381. function convertArray( array, type, forceClone ) {
  14382. if ( ! array || // let 'undefined' and 'null' pass
  14383. ! forceClone && array.constructor === type ) return array;
  14384. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14385. return new type( array ); // create typed array
  14386. }
  14387. return Array.prototype.slice.call( array ); // create Array
  14388. }
  14389. function isTypedArray( object ) {
  14390. return ArrayBuffer.isView( object ) &&
  14391. ! ( object instanceof DataView );
  14392. }
  14393. // returns an array by which times and values can be sorted
  14394. function getKeyframeOrder( times ) {
  14395. function compareTime( i, j ) {
  14396. return times[ i ] - times[ j ];
  14397. }
  14398. const n = times.length;
  14399. const result = new Array( n );
  14400. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14401. result.sort( compareTime );
  14402. return result;
  14403. }
  14404. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14405. function sortedArray( values, stride, order ) {
  14406. const nValues = values.length;
  14407. const result = new values.constructor( nValues );
  14408. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14409. const srcOffset = order[ i ] * stride;
  14410. for ( let j = 0; j !== stride; ++ j ) {
  14411. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14412. }
  14413. }
  14414. return result;
  14415. }
  14416. // function for parsing AOS keyframe formats
  14417. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14418. let i = 1, key = jsonKeys[ 0 ];
  14419. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14420. key = jsonKeys[ i ++ ];
  14421. }
  14422. if ( key === undefined ) return; // no data
  14423. let value = key[ valuePropertyName ];
  14424. if ( value === undefined ) return; // no data
  14425. if ( Array.isArray( value ) ) {
  14426. do {
  14427. value = key[ valuePropertyName ];
  14428. if ( value !== undefined ) {
  14429. times.push( key.time );
  14430. values.push.apply( values, value ); // push all elements
  14431. }
  14432. key = jsonKeys[ i ++ ];
  14433. } while ( key !== undefined );
  14434. } else if ( value.toArray !== undefined ) {
  14435. // ...assume THREE.Math-ish
  14436. do {
  14437. value = key[ valuePropertyName ];
  14438. if ( value !== undefined ) {
  14439. times.push( key.time );
  14440. value.toArray( values, values.length );
  14441. }
  14442. key = jsonKeys[ i ++ ];
  14443. } while ( key !== undefined );
  14444. } else {
  14445. // otherwise push as-is
  14446. do {
  14447. value = key[ valuePropertyName ];
  14448. if ( value !== undefined ) {
  14449. times.push( key.time );
  14450. values.push( value );
  14451. }
  14452. key = jsonKeys[ i ++ ];
  14453. } while ( key !== undefined );
  14454. }
  14455. }
  14456. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14457. const clip = sourceClip.clone();
  14458. clip.name = name;
  14459. const tracks = [];
  14460. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14461. const track = clip.tracks[ i ];
  14462. const valueSize = track.getValueSize();
  14463. const times = [];
  14464. const values = [];
  14465. for ( let j = 0; j < track.times.length; ++ j ) {
  14466. const frame = track.times[ j ] * fps;
  14467. if ( frame < startFrame || frame >= endFrame ) continue;
  14468. times.push( track.times[ j ] );
  14469. for ( let k = 0; k < valueSize; ++ k ) {
  14470. values.push( track.values[ j * valueSize + k ] );
  14471. }
  14472. }
  14473. if ( times.length === 0 ) continue;
  14474. track.times = convertArray( times, track.times.constructor );
  14475. track.values = convertArray( values, track.values.constructor );
  14476. tracks.push( track );
  14477. }
  14478. clip.tracks = tracks;
  14479. // find minimum .times value across all tracks in the trimmed clip
  14480. let minStartTime = Infinity;
  14481. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14482. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14483. minStartTime = clip.tracks[ i ].times[ 0 ];
  14484. }
  14485. }
  14486. // shift all tracks such that clip begins at t=0
  14487. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14488. clip.tracks[ i ].shift( - 1 * minStartTime );
  14489. }
  14490. clip.resetDuration();
  14491. return clip;
  14492. }
  14493. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14494. if ( fps <= 0 ) fps = 30;
  14495. const numTracks = referenceClip.tracks.length;
  14496. const referenceTime = referenceFrame / fps;
  14497. // Make each track's values relative to the values at the reference frame
  14498. for ( let i = 0; i < numTracks; ++ i ) {
  14499. const referenceTrack = referenceClip.tracks[ i ];
  14500. const referenceTrackType = referenceTrack.ValueTypeName;
  14501. // Skip this track if it's non-numeric
  14502. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14503. // Find the track in the target clip whose name and type matches the reference track
  14504. const targetTrack = targetClip.tracks.find( function ( track ) {
  14505. return track.name === referenceTrack.name
  14506. && track.ValueTypeName === referenceTrackType;
  14507. } );
  14508. if ( targetTrack === undefined ) continue;
  14509. let referenceOffset = 0;
  14510. const referenceValueSize = referenceTrack.getValueSize();
  14511. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14512. referenceOffset = referenceValueSize / 3;
  14513. }
  14514. let targetOffset = 0;
  14515. const targetValueSize = targetTrack.getValueSize();
  14516. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14517. targetOffset = targetValueSize / 3;
  14518. }
  14519. const lastIndex = referenceTrack.times.length - 1;
  14520. let referenceValue;
  14521. // Find the value to subtract out of the track
  14522. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14523. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14524. const startIndex = referenceOffset;
  14525. const endIndex = referenceValueSize - referenceOffset;
  14526. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14527. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14528. // Reference frame is after the last keyframe, so just use the last keyframe
  14529. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14530. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14531. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14532. } else {
  14533. // Interpolate to the reference value
  14534. const interpolant = referenceTrack.createInterpolant();
  14535. const startIndex = referenceOffset;
  14536. const endIndex = referenceValueSize - referenceOffset;
  14537. interpolant.evaluate( referenceTime );
  14538. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14539. }
  14540. // Conjugate the quaternion
  14541. if ( referenceTrackType === 'quaternion' ) {
  14542. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14543. referenceQuat.toArray( referenceValue );
  14544. }
  14545. // Subtract the reference value from all of the track values
  14546. const numTimes = targetTrack.times.length;
  14547. for ( let j = 0; j < numTimes; ++ j ) {
  14548. const valueStart = j * targetValueSize + targetOffset;
  14549. if ( referenceTrackType === 'quaternion' ) {
  14550. // Multiply the conjugate for quaternion track types
  14551. Quaternion.multiplyQuaternionsFlat(
  14552. targetTrack.values,
  14553. valueStart,
  14554. referenceValue,
  14555. 0,
  14556. targetTrack.values,
  14557. valueStart
  14558. );
  14559. } else {
  14560. const valueEnd = targetValueSize - targetOffset * 2;
  14561. // Subtract each value for all other numeric track types
  14562. for ( let k = 0; k < valueEnd; ++ k ) {
  14563. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14564. }
  14565. }
  14566. }
  14567. }
  14568. targetClip.blendMode = AdditiveAnimationBlendMode;
  14569. return targetClip;
  14570. }
  14571. const AnimationUtils = {
  14572. convertArray: convertArray,
  14573. isTypedArray: isTypedArray,
  14574. getKeyframeOrder: getKeyframeOrder,
  14575. sortedArray: sortedArray,
  14576. flattenJSON: flattenJSON,
  14577. subclip: subclip,
  14578. makeClipAdditive: makeClipAdditive
  14579. };
  14580. /**
  14581. * Abstract base class of interpolants over parametric samples.
  14582. *
  14583. * The parameter domain is one dimensional, typically the time or a path
  14584. * along a curve defined by the data.
  14585. *
  14586. * The sample values can have any dimensionality and derived classes may
  14587. * apply special interpretations to the data.
  14588. *
  14589. * This class provides the interval seek in a Template Method, deferring
  14590. * the actual interpolation to derived classes.
  14591. *
  14592. * Time complexity is O(1) for linear access crossing at most two points
  14593. * and O(log N) for random access, where N is the number of positions.
  14594. *
  14595. * References:
  14596. *
  14597. * http://www.oodesign.com/template-method-pattern.html
  14598. *
  14599. */
  14600. class Interpolant {
  14601. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14602. this.parameterPositions = parameterPositions;
  14603. this._cachedIndex = 0;
  14604. this.resultBuffer = resultBuffer !== undefined ?
  14605. resultBuffer : new sampleValues.constructor( sampleSize );
  14606. this.sampleValues = sampleValues;
  14607. this.valueSize = sampleSize;
  14608. this.settings = null;
  14609. this.DefaultSettings_ = {};
  14610. }
  14611. evaluate( t ) {
  14612. const pp = this.parameterPositions;
  14613. let i1 = this._cachedIndex,
  14614. t1 = pp[ i1 ],
  14615. t0 = pp[ i1 - 1 ];
  14616. validate_interval: {
  14617. seek: {
  14618. let right;
  14619. linear_scan: {
  14620. //- See http://jsperf.com/comparison-to-undefined/3
  14621. //- slower code:
  14622. //-
  14623. //- if ( t >= t1 || t1 === undefined ) {
  14624. forward_scan: if ( ! ( t < t1 ) ) {
  14625. for ( let giveUpAt = i1 + 2; ; ) {
  14626. if ( t1 === undefined ) {
  14627. if ( t < t0 ) break forward_scan;
  14628. // after end
  14629. i1 = pp.length;
  14630. this._cachedIndex = i1;
  14631. return this.copySampleValue_( i1 - 1 );
  14632. }
  14633. if ( i1 === giveUpAt ) break; // this loop
  14634. t0 = t1;
  14635. t1 = pp[ ++ i1 ];
  14636. if ( t < t1 ) {
  14637. // we have arrived at the sought interval
  14638. break seek;
  14639. }
  14640. }
  14641. // prepare binary search on the right side of the index
  14642. right = pp.length;
  14643. break linear_scan;
  14644. }
  14645. //- slower code:
  14646. //- if ( t < t0 || t0 === undefined ) {
  14647. if ( ! ( t >= t0 ) ) {
  14648. // looping?
  14649. const t1global = pp[ 1 ];
  14650. if ( t < t1global ) {
  14651. i1 = 2; // + 1, using the scan for the details
  14652. t0 = t1global;
  14653. }
  14654. // linear reverse scan
  14655. for ( let giveUpAt = i1 - 2; ; ) {
  14656. if ( t0 === undefined ) {
  14657. // before start
  14658. this._cachedIndex = 0;
  14659. return this.copySampleValue_( 0 );
  14660. }
  14661. if ( i1 === giveUpAt ) break; // this loop
  14662. t1 = t0;
  14663. t0 = pp[ -- i1 - 1 ];
  14664. if ( t >= t0 ) {
  14665. // we have arrived at the sought interval
  14666. break seek;
  14667. }
  14668. }
  14669. // prepare binary search on the left side of the index
  14670. right = i1;
  14671. i1 = 0;
  14672. break linear_scan;
  14673. }
  14674. // the interval is valid
  14675. break validate_interval;
  14676. } // linear scan
  14677. // binary search
  14678. while ( i1 < right ) {
  14679. const mid = ( i1 + right ) >>> 1;
  14680. if ( t < pp[ mid ] ) {
  14681. right = mid;
  14682. } else {
  14683. i1 = mid + 1;
  14684. }
  14685. }
  14686. t1 = pp[ i1 ];
  14687. t0 = pp[ i1 - 1 ];
  14688. // check boundary cases, again
  14689. if ( t0 === undefined ) {
  14690. this._cachedIndex = 0;
  14691. return this.copySampleValue_( 0 );
  14692. }
  14693. if ( t1 === undefined ) {
  14694. i1 = pp.length;
  14695. this._cachedIndex = i1;
  14696. return this.copySampleValue_( i1 - 1 );
  14697. }
  14698. } // seek
  14699. this._cachedIndex = i1;
  14700. this.intervalChanged_( i1, t0, t1 );
  14701. } // validate_interval
  14702. return this.interpolate_( i1, t0, t, t1 );
  14703. }
  14704. getSettings_() {
  14705. return this.settings || this.DefaultSettings_;
  14706. }
  14707. copySampleValue_( index ) {
  14708. // copies a sample value to the result buffer
  14709. const result = this.resultBuffer,
  14710. values = this.sampleValues,
  14711. stride = this.valueSize,
  14712. offset = index * stride;
  14713. for ( let i = 0; i !== stride; ++ i ) {
  14714. result[ i ] = values[ offset + i ];
  14715. }
  14716. return result;
  14717. }
  14718. // Template methods for derived classes:
  14719. interpolate_( /* i1, t0, t, t1 */ ) {
  14720. throw new Error( 'call to abstract method' );
  14721. // implementations shall return this.resultBuffer
  14722. }
  14723. intervalChanged_( /* i1, t0, t1 */ ) {
  14724. // empty
  14725. }
  14726. }
  14727. /**
  14728. * Fast and simple cubic spline interpolant.
  14729. *
  14730. * It was derived from a Hermitian construction setting the first derivative
  14731. * at each sample position to the linear slope between neighboring positions
  14732. * over their parameter interval.
  14733. */
  14734. class CubicInterpolant extends Interpolant {
  14735. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14736. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14737. this._weightPrev = - 0;
  14738. this._offsetPrev = - 0;
  14739. this._weightNext = - 0;
  14740. this._offsetNext = - 0;
  14741. this.DefaultSettings_ = {
  14742. endingStart: ZeroCurvatureEnding,
  14743. endingEnd: ZeroCurvatureEnding
  14744. };
  14745. }
  14746. intervalChanged_( i1, t0, t1 ) {
  14747. const pp = this.parameterPositions;
  14748. let iPrev = i1 - 2,
  14749. iNext = i1 + 1,
  14750. tPrev = pp[ iPrev ],
  14751. tNext = pp[ iNext ];
  14752. if ( tPrev === undefined ) {
  14753. switch ( this.getSettings_().endingStart ) {
  14754. case ZeroSlopeEnding:
  14755. // f'(t0) = 0
  14756. iPrev = i1;
  14757. tPrev = 2 * t0 - t1;
  14758. break;
  14759. case WrapAroundEnding:
  14760. // use the other end of the curve
  14761. iPrev = pp.length - 2;
  14762. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  14763. break;
  14764. default: // ZeroCurvatureEnding
  14765. // f''(t0) = 0 a.k.a. Natural Spline
  14766. iPrev = i1;
  14767. tPrev = t1;
  14768. }
  14769. }
  14770. if ( tNext === undefined ) {
  14771. switch ( this.getSettings_().endingEnd ) {
  14772. case ZeroSlopeEnding:
  14773. // f'(tN) = 0
  14774. iNext = i1;
  14775. tNext = 2 * t1 - t0;
  14776. break;
  14777. case WrapAroundEnding:
  14778. // use the other end of the curve
  14779. iNext = 1;
  14780. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  14781. break;
  14782. default: // ZeroCurvatureEnding
  14783. // f''(tN) = 0, a.k.a. Natural Spline
  14784. iNext = i1 - 1;
  14785. tNext = t0;
  14786. }
  14787. }
  14788. const halfDt = ( t1 - t0 ) * 0.5,
  14789. stride = this.valueSize;
  14790. this._weightPrev = halfDt / ( t0 - tPrev );
  14791. this._weightNext = halfDt / ( tNext - t1 );
  14792. this._offsetPrev = iPrev * stride;
  14793. this._offsetNext = iNext * stride;
  14794. }
  14795. interpolate_( i1, t0, t, t1 ) {
  14796. const result = this.resultBuffer,
  14797. values = this.sampleValues,
  14798. stride = this.valueSize,
  14799. o1 = i1 * stride, o0 = o1 - stride,
  14800. oP = this._offsetPrev, oN = this._offsetNext,
  14801. wP = this._weightPrev, wN = this._weightNext,
  14802. p = ( t - t0 ) / ( t1 - t0 ),
  14803. pp = p * p,
  14804. ppp = pp * p;
  14805. // evaluate polynomials
  14806. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  14807. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  14808. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  14809. const sN = wN * ppp - wN * pp;
  14810. // combine data linearly
  14811. for ( let i = 0; i !== stride; ++ i ) {
  14812. result[ i ] =
  14813. sP * values[ oP + i ] +
  14814. s0 * values[ o0 + i ] +
  14815. s1 * values[ o1 + i ] +
  14816. sN * values[ oN + i ];
  14817. }
  14818. return result;
  14819. }
  14820. }
  14821. class LinearInterpolant extends Interpolant {
  14822. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14823. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14824. }
  14825. interpolate_( i1, t0, t, t1 ) {
  14826. const result = this.resultBuffer,
  14827. values = this.sampleValues,
  14828. stride = this.valueSize,
  14829. offset1 = i1 * stride,
  14830. offset0 = offset1 - stride,
  14831. weight1 = ( t - t0 ) / ( t1 - t0 ),
  14832. weight0 = 1 - weight1;
  14833. for ( let i = 0; i !== stride; ++ i ) {
  14834. result[ i ] =
  14835. values[ offset0 + i ] * weight0 +
  14836. values[ offset1 + i ] * weight1;
  14837. }
  14838. return result;
  14839. }
  14840. }
  14841. /**
  14842. *
  14843. * Interpolant that evaluates to the sample value at the position preceding
  14844. * the parameter.
  14845. */
  14846. class DiscreteInterpolant extends Interpolant {
  14847. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14848. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14849. }
  14850. interpolate_( i1 /*, t0, t, t1 */ ) {
  14851. return this.copySampleValue_( i1 - 1 );
  14852. }
  14853. }
  14854. class KeyframeTrack {
  14855. constructor( name, times, values, interpolation ) {
  14856. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  14857. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  14858. this.name = name;
  14859. this.times = convertArray( times, this.TimeBufferType );
  14860. this.values = convertArray( values, this.ValueBufferType );
  14861. this.setInterpolation( interpolation || this.DefaultInterpolation );
  14862. }
  14863. // Serialization (in static context, because of constructor invocation
  14864. // and automatic invocation of .toJSON):
  14865. static toJSON( track ) {
  14866. const trackType = track.constructor;
  14867. let json;
  14868. // derived classes can define a static toJSON method
  14869. if ( trackType.toJSON !== this.toJSON ) {
  14870. json = trackType.toJSON( track );
  14871. } else {
  14872. // by default, we assume the data can be serialized as-is
  14873. json = {
  14874. 'name': track.name,
  14875. 'times': convertArray( track.times, Array ),
  14876. 'values': convertArray( track.values, Array )
  14877. };
  14878. const interpolation = track.getInterpolation();
  14879. if ( interpolation !== track.DefaultInterpolation ) {
  14880. json.interpolation = interpolation;
  14881. }
  14882. }
  14883. json.type = track.ValueTypeName; // mandatory
  14884. return json;
  14885. }
  14886. InterpolantFactoryMethodDiscrete( result ) {
  14887. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  14888. }
  14889. InterpolantFactoryMethodLinear( result ) {
  14890. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  14891. }
  14892. InterpolantFactoryMethodSmooth( result ) {
  14893. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  14894. }
  14895. setInterpolation( interpolation ) {
  14896. let factoryMethod;
  14897. switch ( interpolation ) {
  14898. case InterpolateDiscrete:
  14899. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  14900. break;
  14901. case InterpolateLinear:
  14902. factoryMethod = this.InterpolantFactoryMethodLinear;
  14903. break;
  14904. case InterpolateSmooth:
  14905. factoryMethod = this.InterpolantFactoryMethodSmooth;
  14906. break;
  14907. }
  14908. if ( factoryMethod === undefined ) {
  14909. const message = 'unsupported interpolation for ' +
  14910. this.ValueTypeName + ' keyframe track named ' + this.name;
  14911. if ( this.createInterpolant === undefined ) {
  14912. // fall back to default, unless the default itself is messed up
  14913. if ( interpolation !== this.DefaultInterpolation ) {
  14914. this.setInterpolation( this.DefaultInterpolation );
  14915. } else {
  14916. throw new Error( message ); // fatal, in this case
  14917. }
  14918. }
  14919. console.warn( 'THREE.KeyframeTrack:', message );
  14920. return this;
  14921. }
  14922. this.createInterpolant = factoryMethod;
  14923. return this;
  14924. }
  14925. getInterpolation() {
  14926. switch ( this.createInterpolant ) {
  14927. case this.InterpolantFactoryMethodDiscrete:
  14928. return InterpolateDiscrete;
  14929. case this.InterpolantFactoryMethodLinear:
  14930. return InterpolateLinear;
  14931. case this.InterpolantFactoryMethodSmooth:
  14932. return InterpolateSmooth;
  14933. }
  14934. }
  14935. getValueSize() {
  14936. return this.values.length / this.times.length;
  14937. }
  14938. // move all keyframes either forwards or backwards in time
  14939. shift( timeOffset ) {
  14940. if ( timeOffset !== 0.0 ) {
  14941. const times = this.times;
  14942. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14943. times[ i ] += timeOffset;
  14944. }
  14945. }
  14946. return this;
  14947. }
  14948. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  14949. scale( timeScale ) {
  14950. if ( timeScale !== 1.0 ) {
  14951. const times = this.times;
  14952. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14953. times[ i ] *= timeScale;
  14954. }
  14955. }
  14956. return this;
  14957. }
  14958. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  14959. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  14960. trim( startTime, endTime ) {
  14961. const times = this.times,
  14962. nKeys = times.length;
  14963. let from = 0,
  14964. to = nKeys - 1;
  14965. while ( from !== nKeys && times[ from ] < startTime ) {
  14966. ++ from;
  14967. }
  14968. while ( to !== - 1 && times[ to ] > endTime ) {
  14969. -- to;
  14970. }
  14971. ++ to; // inclusive -> exclusive bound
  14972. if ( from !== 0 || to !== nKeys ) {
  14973. // empty tracks are forbidden, so keep at least one keyframe
  14974. if ( from >= to ) {
  14975. to = Math.max( to, 1 );
  14976. from = to - 1;
  14977. }
  14978. const stride = this.getValueSize();
  14979. this.times = times.slice( from, to );
  14980. this.values = this.values.slice( from * stride, to * stride );
  14981. }
  14982. return this;
  14983. }
  14984. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  14985. validate() {
  14986. let valid = true;
  14987. const valueSize = this.getValueSize();
  14988. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  14989. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  14990. valid = false;
  14991. }
  14992. const times = this.times,
  14993. values = this.values,
  14994. nKeys = times.length;
  14995. if ( nKeys === 0 ) {
  14996. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  14997. valid = false;
  14998. }
  14999. let prevTime = null;
  15000. for ( let i = 0; i !== nKeys; i ++ ) {
  15001. const currTime = times[ i ];
  15002. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15003. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15004. valid = false;
  15005. break;
  15006. }
  15007. if ( prevTime !== null && prevTime > currTime ) {
  15008. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15009. valid = false;
  15010. break;
  15011. }
  15012. prevTime = currTime;
  15013. }
  15014. if ( values !== undefined ) {
  15015. if ( isTypedArray( values ) ) {
  15016. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15017. const value = values[ i ];
  15018. if ( isNaN( value ) ) {
  15019. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15020. valid = false;
  15021. break;
  15022. }
  15023. }
  15024. }
  15025. }
  15026. return valid;
  15027. }
  15028. // removes equivalent sequential keys as common in morph target sequences
  15029. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15030. optimize() {
  15031. // times or values may be shared with other tracks, so overwriting is unsafe
  15032. const times = this.times.slice(),
  15033. values = this.values.slice(),
  15034. stride = this.getValueSize(),
  15035. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15036. lastIndex = times.length - 1;
  15037. let writeIndex = 1;
  15038. for ( let i = 1; i < lastIndex; ++ i ) {
  15039. let keep = false;
  15040. const time = times[ i ];
  15041. const timeNext = times[ i + 1 ];
  15042. // remove adjacent keyframes scheduled at the same time
  15043. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15044. if ( ! smoothInterpolation ) {
  15045. // remove unnecessary keyframes same as their neighbors
  15046. const offset = i * stride,
  15047. offsetP = offset - stride,
  15048. offsetN = offset + stride;
  15049. for ( let j = 0; j !== stride; ++ j ) {
  15050. const value = values[ offset + j ];
  15051. if ( value !== values[ offsetP + j ] ||
  15052. value !== values[ offsetN + j ] ) {
  15053. keep = true;
  15054. break;
  15055. }
  15056. }
  15057. } else {
  15058. keep = true;
  15059. }
  15060. }
  15061. // in-place compaction
  15062. if ( keep ) {
  15063. if ( i !== writeIndex ) {
  15064. times[ writeIndex ] = times[ i ];
  15065. const readOffset = i * stride,
  15066. writeOffset = writeIndex * stride;
  15067. for ( let j = 0; j !== stride; ++ j ) {
  15068. values[ writeOffset + j ] = values[ readOffset + j ];
  15069. }
  15070. }
  15071. ++ writeIndex;
  15072. }
  15073. }
  15074. // flush last keyframe (compaction looks ahead)
  15075. if ( lastIndex > 0 ) {
  15076. times[ writeIndex ] = times[ lastIndex ];
  15077. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15078. values[ writeOffset + j ] = values[ readOffset + j ];
  15079. }
  15080. ++ writeIndex;
  15081. }
  15082. if ( writeIndex !== times.length ) {
  15083. this.times = times.slice( 0, writeIndex );
  15084. this.values = values.slice( 0, writeIndex * stride );
  15085. } else {
  15086. this.times = times;
  15087. this.values = values;
  15088. }
  15089. return this;
  15090. }
  15091. clone() {
  15092. const times = this.times.slice();
  15093. const values = this.values.slice();
  15094. const TypedKeyframeTrack = this.constructor;
  15095. const track = new TypedKeyframeTrack( this.name, times, values );
  15096. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15097. track.createInterpolant = this.createInterpolant;
  15098. return track;
  15099. }
  15100. }
  15101. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15102. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15103. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15104. /**
  15105. * A Track of Boolean keyframe values.
  15106. */
  15107. class BooleanKeyframeTrack extends KeyframeTrack {
  15108. // No interpolation parameter because only InterpolateDiscrete is valid.
  15109. constructor( name, times, values ) {
  15110. super( name, times, values );
  15111. }
  15112. }
  15113. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15114. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15115. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15116. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15117. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15118. /**
  15119. * A Track of keyframe values that represent color.
  15120. */
  15121. class ColorKeyframeTrack extends KeyframeTrack {}
  15122. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15123. /**
  15124. * A Track of numeric keyframe values.
  15125. */
  15126. class NumberKeyframeTrack extends KeyframeTrack {}
  15127. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15128. /**
  15129. * Spherical linear unit quaternion interpolant.
  15130. */
  15131. class QuaternionLinearInterpolant extends Interpolant {
  15132. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15133. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15134. }
  15135. interpolate_( i1, t0, t, t1 ) {
  15136. const result = this.resultBuffer,
  15137. values = this.sampleValues,
  15138. stride = this.valueSize,
  15139. alpha = ( t - t0 ) / ( t1 - t0 );
  15140. let offset = i1 * stride;
  15141. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15142. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15143. }
  15144. return result;
  15145. }
  15146. }
  15147. /**
  15148. * A Track of quaternion keyframe values.
  15149. */
  15150. class QuaternionKeyframeTrack extends KeyframeTrack {
  15151. InterpolantFactoryMethodLinear( result ) {
  15152. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15153. }
  15154. }
  15155. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15156. // ValueBufferType is inherited
  15157. // DefaultInterpolation is inherited;
  15158. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15159. /**
  15160. * A Track that interpolates Strings
  15161. */
  15162. class StringKeyframeTrack extends KeyframeTrack {
  15163. // No interpolation parameter because only InterpolateDiscrete is valid.
  15164. constructor( name, times, values ) {
  15165. super( name, times, values );
  15166. }
  15167. }
  15168. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15169. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15170. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15171. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15172. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15173. /**
  15174. * A Track of vectored keyframe values.
  15175. */
  15176. class VectorKeyframeTrack extends KeyframeTrack {}
  15177. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15178. class AnimationClip {
  15179. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15180. this.name = name;
  15181. this.tracks = tracks;
  15182. this.duration = duration;
  15183. this.blendMode = blendMode;
  15184. this.uuid = generateUUID();
  15185. // this means it should figure out its duration by scanning the tracks
  15186. if ( this.duration < 0 ) {
  15187. this.resetDuration();
  15188. }
  15189. }
  15190. static parse( json ) {
  15191. const tracks = [],
  15192. jsonTracks = json.tracks,
  15193. frameTime = 1.0 / ( json.fps || 1.0 );
  15194. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15195. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15196. }
  15197. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15198. clip.uuid = json.uuid;
  15199. return clip;
  15200. }
  15201. static toJSON( clip ) {
  15202. const tracks = [],
  15203. clipTracks = clip.tracks;
  15204. const json = {
  15205. 'name': clip.name,
  15206. 'duration': clip.duration,
  15207. 'tracks': tracks,
  15208. 'uuid': clip.uuid,
  15209. 'blendMode': clip.blendMode
  15210. };
  15211. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15212. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15213. }
  15214. return json;
  15215. }
  15216. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15217. const numMorphTargets = morphTargetSequence.length;
  15218. const tracks = [];
  15219. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15220. let times = [];
  15221. let values = [];
  15222. times.push(
  15223. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15224. i,
  15225. ( i + 1 ) % numMorphTargets );
  15226. values.push( 0, 1, 0 );
  15227. const order = getKeyframeOrder( times );
  15228. times = sortedArray( times, 1, order );
  15229. values = sortedArray( values, 1, order );
  15230. // if there is a key at the first frame, duplicate it as the
  15231. // last frame as well for perfect loop.
  15232. if ( ! noLoop && times[ 0 ] === 0 ) {
  15233. times.push( numMorphTargets );
  15234. values.push( values[ 0 ] );
  15235. }
  15236. tracks.push(
  15237. new NumberKeyframeTrack(
  15238. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15239. times, values
  15240. ).scale( 1.0 / fps ) );
  15241. }
  15242. return new this( name, - 1, tracks );
  15243. }
  15244. static findByName( objectOrClipArray, name ) {
  15245. let clipArray = objectOrClipArray;
  15246. if ( ! Array.isArray( objectOrClipArray ) ) {
  15247. const o = objectOrClipArray;
  15248. clipArray = o.geometry && o.geometry.animations || o.animations;
  15249. }
  15250. for ( let i = 0; i < clipArray.length; i ++ ) {
  15251. if ( clipArray[ i ].name === name ) {
  15252. return clipArray[ i ];
  15253. }
  15254. }
  15255. return null;
  15256. }
  15257. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15258. const animationToMorphTargets = {};
  15259. // tested with https://regex101.com/ on trick sequences
  15260. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15261. const pattern = /^([\w-]*?)([\d]+)$/;
  15262. // sort morph target names into animation groups based
  15263. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15264. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15265. const morphTarget = morphTargets[ i ];
  15266. const parts = morphTarget.name.match( pattern );
  15267. if ( parts && parts.length > 1 ) {
  15268. const name = parts[ 1 ];
  15269. let animationMorphTargets = animationToMorphTargets[ name ];
  15270. if ( ! animationMorphTargets ) {
  15271. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15272. }
  15273. animationMorphTargets.push( morphTarget );
  15274. }
  15275. }
  15276. const clips = [];
  15277. for ( const name in animationToMorphTargets ) {
  15278. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15279. }
  15280. return clips;
  15281. }
  15282. // parse the animation.hierarchy format
  15283. static parseAnimation( animation, bones ) {
  15284. if ( ! animation ) {
  15285. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15286. return null;
  15287. }
  15288. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15289. // only return track if there are actually keys.
  15290. if ( animationKeys.length !== 0 ) {
  15291. const times = [];
  15292. const values = [];
  15293. flattenJSON( animationKeys, times, values, propertyName );
  15294. // empty keys are filtered out, so check again
  15295. if ( times.length !== 0 ) {
  15296. destTracks.push( new trackType( trackName, times, values ) );
  15297. }
  15298. }
  15299. };
  15300. const tracks = [];
  15301. const clipName = animation.name || 'default';
  15302. const fps = animation.fps || 30;
  15303. const blendMode = animation.blendMode;
  15304. // automatic length determination in AnimationClip.
  15305. let duration = animation.length || - 1;
  15306. const hierarchyTracks = animation.hierarchy || [];
  15307. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15308. const animationKeys = hierarchyTracks[ h ].keys;
  15309. // skip empty tracks
  15310. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15311. // process morph targets
  15312. if ( animationKeys[ 0 ].morphTargets ) {
  15313. // figure out all morph targets used in this track
  15314. const morphTargetNames = {};
  15315. let k;
  15316. for ( k = 0; k < animationKeys.length; k ++ ) {
  15317. if ( animationKeys[ k ].morphTargets ) {
  15318. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15319. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15320. }
  15321. }
  15322. }
  15323. // create a track for each morph target with all zero
  15324. // morphTargetInfluences except for the keys in which
  15325. // the morphTarget is named.
  15326. for ( const morphTargetName in morphTargetNames ) {
  15327. const times = [];
  15328. const values = [];
  15329. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15330. const animationKey = animationKeys[ k ];
  15331. times.push( animationKey.time );
  15332. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15333. }
  15334. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15335. }
  15336. duration = morphTargetNames.length * fps;
  15337. } else {
  15338. // ...assume skeletal animation
  15339. const boneName = '.bones[' + bones[ h ].name + ']';
  15340. addNonemptyTrack(
  15341. VectorKeyframeTrack, boneName + '.position',
  15342. animationKeys, 'pos', tracks );
  15343. addNonemptyTrack(
  15344. QuaternionKeyframeTrack, boneName + '.quaternion',
  15345. animationKeys, 'rot', tracks );
  15346. addNonemptyTrack(
  15347. VectorKeyframeTrack, boneName + '.scale',
  15348. animationKeys, 'scl', tracks );
  15349. }
  15350. }
  15351. if ( tracks.length === 0 ) {
  15352. return null;
  15353. }
  15354. const clip = new this( clipName, duration, tracks, blendMode );
  15355. return clip;
  15356. }
  15357. resetDuration() {
  15358. const tracks = this.tracks;
  15359. let duration = 0;
  15360. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15361. const track = this.tracks[ i ];
  15362. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15363. }
  15364. this.duration = duration;
  15365. return this;
  15366. }
  15367. trim() {
  15368. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15369. this.tracks[ i ].trim( 0, this.duration );
  15370. }
  15371. return this;
  15372. }
  15373. validate() {
  15374. let valid = true;
  15375. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15376. valid = valid && this.tracks[ i ].validate();
  15377. }
  15378. return valid;
  15379. }
  15380. optimize() {
  15381. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15382. this.tracks[ i ].optimize();
  15383. }
  15384. return this;
  15385. }
  15386. clone() {
  15387. const tracks = [];
  15388. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15389. tracks.push( this.tracks[ i ].clone() );
  15390. }
  15391. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15392. }
  15393. toJSON() {
  15394. return this.constructor.toJSON( this );
  15395. }
  15396. }
  15397. function getTrackTypeForValueTypeName( typeName ) {
  15398. switch ( typeName.toLowerCase() ) {
  15399. case 'scalar':
  15400. case 'double':
  15401. case 'float':
  15402. case 'number':
  15403. case 'integer':
  15404. return NumberKeyframeTrack;
  15405. case 'vector':
  15406. case 'vector2':
  15407. case 'vector3':
  15408. case 'vector4':
  15409. return VectorKeyframeTrack;
  15410. case 'color':
  15411. return ColorKeyframeTrack;
  15412. case 'quaternion':
  15413. return QuaternionKeyframeTrack;
  15414. case 'bool':
  15415. case 'boolean':
  15416. return BooleanKeyframeTrack;
  15417. case 'string':
  15418. return StringKeyframeTrack;
  15419. }
  15420. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15421. }
  15422. function parseKeyframeTrack( json ) {
  15423. if ( json.type === undefined ) {
  15424. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15425. }
  15426. const trackType = getTrackTypeForValueTypeName( json.type );
  15427. if ( json.times === undefined ) {
  15428. const times = [], values = [];
  15429. flattenJSON( json.keys, times, values, 'value' );
  15430. json.times = times;
  15431. json.values = values;
  15432. }
  15433. // derived classes can define a static parse method
  15434. if ( trackType.parse !== undefined ) {
  15435. return trackType.parse( json );
  15436. } else {
  15437. // by default, we assume a constructor compatible with the base
  15438. return new trackType( json.name, json.times, json.values, json.interpolation );
  15439. }
  15440. }
  15441. const Cache = {
  15442. enabled: false,
  15443. files: {},
  15444. add: function ( key, file ) {
  15445. if ( this.enabled === false ) return;
  15446. // console.log( 'THREE.Cache', 'Adding key:', key );
  15447. this.files[ key ] = file;
  15448. },
  15449. get: function ( key ) {
  15450. if ( this.enabled === false ) return;
  15451. // console.log( 'THREE.Cache', 'Checking key:', key );
  15452. return this.files[ key ];
  15453. },
  15454. remove: function ( key ) {
  15455. delete this.files[ key ];
  15456. },
  15457. clear: function () {
  15458. this.files = {};
  15459. }
  15460. };
  15461. class LoadingManager {
  15462. constructor( onLoad, onProgress, onError ) {
  15463. const scope = this;
  15464. let isLoading = false;
  15465. let itemsLoaded = 0;
  15466. let itemsTotal = 0;
  15467. let urlModifier = undefined;
  15468. const handlers = [];
  15469. // Refer to #5689 for the reason why we don't set .onStart
  15470. // in the constructor
  15471. this.onStart = undefined;
  15472. this.onLoad = onLoad;
  15473. this.onProgress = onProgress;
  15474. this.onError = onError;
  15475. this.itemStart = function ( url ) {
  15476. itemsTotal ++;
  15477. if ( isLoading === false ) {
  15478. if ( scope.onStart !== undefined ) {
  15479. scope.onStart( url, itemsLoaded, itemsTotal );
  15480. }
  15481. }
  15482. isLoading = true;
  15483. };
  15484. this.itemEnd = function ( url ) {
  15485. itemsLoaded ++;
  15486. if ( scope.onProgress !== undefined ) {
  15487. scope.onProgress( url, itemsLoaded, itemsTotal );
  15488. }
  15489. if ( itemsLoaded === itemsTotal ) {
  15490. isLoading = false;
  15491. if ( scope.onLoad !== undefined ) {
  15492. scope.onLoad();
  15493. }
  15494. }
  15495. };
  15496. this.itemError = function ( url ) {
  15497. if ( scope.onError !== undefined ) {
  15498. scope.onError( url );
  15499. }
  15500. };
  15501. this.resolveURL = function ( url ) {
  15502. if ( urlModifier ) {
  15503. return urlModifier( url );
  15504. }
  15505. return url;
  15506. };
  15507. this.setURLModifier = function ( transform ) {
  15508. urlModifier = transform;
  15509. return this;
  15510. };
  15511. this.addHandler = function ( regex, loader ) {
  15512. handlers.push( regex, loader );
  15513. return this;
  15514. };
  15515. this.removeHandler = function ( regex ) {
  15516. const index = handlers.indexOf( regex );
  15517. if ( index !== - 1 ) {
  15518. handlers.splice( index, 2 );
  15519. }
  15520. return this;
  15521. };
  15522. this.getHandler = function ( file ) {
  15523. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15524. const regex = handlers[ i ];
  15525. const loader = handlers[ i + 1 ];
  15526. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15527. if ( regex.test( file ) ) {
  15528. return loader;
  15529. }
  15530. }
  15531. return null;
  15532. };
  15533. }
  15534. }
  15535. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15536. class Loader {
  15537. constructor( manager ) {
  15538. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15539. this.crossOrigin = 'anonymous';
  15540. this.withCredentials = false;
  15541. this.path = '';
  15542. this.resourcePath = '';
  15543. this.requestHeader = {};
  15544. }
  15545. load( /* url, onLoad, onProgress, onError */ ) {}
  15546. loadAsync( url, onProgress ) {
  15547. const scope = this;
  15548. return new Promise( function ( resolve, reject ) {
  15549. scope.load( url, resolve, onProgress, reject );
  15550. } );
  15551. }
  15552. parse( /* data */ ) {}
  15553. setCrossOrigin( crossOrigin ) {
  15554. this.crossOrigin = crossOrigin;
  15555. return this;
  15556. }
  15557. setWithCredentials( value ) {
  15558. this.withCredentials = value;
  15559. return this;
  15560. }
  15561. setPath( path ) {
  15562. this.path = path;
  15563. return this;
  15564. }
  15565. setResourcePath( resourcePath ) {
  15566. this.resourcePath = resourcePath;
  15567. return this;
  15568. }
  15569. setRequestHeader( requestHeader ) {
  15570. this.requestHeader = requestHeader;
  15571. return this;
  15572. }
  15573. }
  15574. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15575. const loading = {};
  15576. class HttpError extends Error {
  15577. constructor( message, response ) {
  15578. super( message );
  15579. this.response = response;
  15580. }
  15581. }
  15582. class FileLoader extends Loader {
  15583. constructor( manager ) {
  15584. super( manager );
  15585. }
  15586. load( url, onLoad, onProgress, onError ) {
  15587. if ( url === undefined ) url = '';
  15588. if ( this.path !== undefined ) url = this.path + url;
  15589. url = this.manager.resolveURL( url );
  15590. const cached = Cache.get( url );
  15591. if ( cached !== undefined ) {
  15592. this.manager.itemStart( url );
  15593. setTimeout( () => {
  15594. if ( onLoad ) onLoad( cached );
  15595. this.manager.itemEnd( url );
  15596. }, 0 );
  15597. return cached;
  15598. }
  15599. // Check if request is duplicate
  15600. if ( loading[ url ] !== undefined ) {
  15601. loading[ url ].push( {
  15602. onLoad: onLoad,
  15603. onProgress: onProgress,
  15604. onError: onError
  15605. } );
  15606. return;
  15607. }
  15608. // Initialise array for duplicate requests
  15609. loading[ url ] = [];
  15610. loading[ url ].push( {
  15611. onLoad: onLoad,
  15612. onProgress: onProgress,
  15613. onError: onError,
  15614. } );
  15615. // create request
  15616. const req = new Request( url, {
  15617. headers: new Headers( this.requestHeader ),
  15618. credentials: this.withCredentials ? 'include' : 'same-origin',
  15619. // An abort controller could be added within a future PR
  15620. } );
  15621. // record states ( avoid data race )
  15622. const mimeType = this.mimeType;
  15623. const responseType = this.responseType;
  15624. // start the fetch
  15625. fetch( req )
  15626. .then( response => {
  15627. if ( response.status === 200 || response.status === 0 ) {
  15628. // Some browsers return HTTP Status 0 when using non-http protocol
  15629. // e.g. 'file://' or 'data://'. Handle as success.
  15630. if ( response.status === 0 ) {
  15631. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15632. }
  15633. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15634. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15635. return response;
  15636. }
  15637. const callbacks = loading[ url ];
  15638. const reader = response.body.getReader();
  15639. // Nginx needs X-File-Size check
  15640. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15641. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15642. const total = contentLength ? parseInt( contentLength ) : 0;
  15643. const lengthComputable = total !== 0;
  15644. let loaded = 0;
  15645. // periodically read data into the new stream tracking while download progress
  15646. const stream = new ReadableStream( {
  15647. start( controller ) {
  15648. readData();
  15649. function readData() {
  15650. reader.read().then( ( { done, value } ) => {
  15651. if ( done ) {
  15652. controller.close();
  15653. } else {
  15654. loaded += value.byteLength;
  15655. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15656. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15657. const callback = callbacks[ i ];
  15658. if ( callback.onProgress ) callback.onProgress( event );
  15659. }
  15660. controller.enqueue( value );
  15661. readData();
  15662. }
  15663. }, ( e ) => {
  15664. controller.error( e );
  15665. } );
  15666. }
  15667. }
  15668. } );
  15669. return new Response( stream );
  15670. } else {
  15671. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15672. }
  15673. } )
  15674. .then( response => {
  15675. switch ( responseType ) {
  15676. case 'arraybuffer':
  15677. return response.arrayBuffer();
  15678. case 'blob':
  15679. return response.blob();
  15680. case 'document':
  15681. return response.text()
  15682. .then( text => {
  15683. const parser = new DOMParser();
  15684. return parser.parseFromString( text, mimeType );
  15685. } );
  15686. case 'json':
  15687. return response.json();
  15688. default:
  15689. if ( mimeType === undefined ) {
  15690. return response.text();
  15691. } else {
  15692. // sniff encoding
  15693. const re = /charset="?([^;"\s]*)"?/i;
  15694. const exec = re.exec( mimeType );
  15695. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15696. const decoder = new TextDecoder( label );
  15697. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15698. }
  15699. }
  15700. } )
  15701. .then( data => {
  15702. // Add to cache only on HTTP success, so that we do not cache
  15703. // error response bodies as proper responses to requests.
  15704. Cache.add( url, data );
  15705. const callbacks = loading[ url ];
  15706. delete loading[ url ];
  15707. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15708. const callback = callbacks[ i ];
  15709. if ( callback.onLoad ) callback.onLoad( data );
  15710. }
  15711. } )
  15712. .catch( err => {
  15713. // Abort errors and other errors are handled the same
  15714. const callbacks = loading[ url ];
  15715. if ( callbacks === undefined ) {
  15716. // When onLoad was called and url was deleted in `loading`
  15717. this.manager.itemError( url );
  15718. throw err;
  15719. }
  15720. delete loading[ url ];
  15721. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15722. const callback = callbacks[ i ];
  15723. if ( callback.onError ) callback.onError( err );
  15724. }
  15725. this.manager.itemError( url );
  15726. } )
  15727. .finally( () => {
  15728. this.manager.itemEnd( url );
  15729. } );
  15730. this.manager.itemStart( url );
  15731. }
  15732. setResponseType( value ) {
  15733. this.responseType = value;
  15734. return this;
  15735. }
  15736. setMimeType( value ) {
  15737. this.mimeType = value;
  15738. return this;
  15739. }
  15740. }
  15741. class AnimationLoader extends Loader {
  15742. constructor( manager ) {
  15743. super( manager );
  15744. }
  15745. load( url, onLoad, onProgress, onError ) {
  15746. const scope = this;
  15747. const loader = new FileLoader( this.manager );
  15748. loader.setPath( this.path );
  15749. loader.setRequestHeader( this.requestHeader );
  15750. loader.setWithCredentials( this.withCredentials );
  15751. loader.load( url, function ( text ) {
  15752. try {
  15753. onLoad( scope.parse( JSON.parse( text ) ) );
  15754. } catch ( e ) {
  15755. if ( onError ) {
  15756. onError( e );
  15757. } else {
  15758. console.error( e );
  15759. }
  15760. scope.manager.itemError( url );
  15761. }
  15762. }, onProgress, onError );
  15763. }
  15764. parse( json ) {
  15765. const animations = [];
  15766. for ( let i = 0; i < json.length; i ++ ) {
  15767. const clip = AnimationClip.parse( json[ i ] );
  15768. animations.push( clip );
  15769. }
  15770. return animations;
  15771. }
  15772. }
  15773. /**
  15774. * Abstract Base class to block based textures loader (dds, pvr, ...)
  15775. *
  15776. * Sub classes have to implement the parse() method which will be used in load().
  15777. */
  15778. class CompressedTextureLoader extends Loader {
  15779. constructor( manager ) {
  15780. super( manager );
  15781. }
  15782. load( url, onLoad, onProgress, onError ) {
  15783. const scope = this;
  15784. const images = [];
  15785. const texture = new CompressedTexture();
  15786. const loader = new FileLoader( this.manager );
  15787. loader.setPath( this.path );
  15788. loader.setResponseType( 'arraybuffer' );
  15789. loader.setRequestHeader( this.requestHeader );
  15790. loader.setWithCredentials( scope.withCredentials );
  15791. let loaded = 0;
  15792. function loadTexture( i ) {
  15793. loader.load( url[ i ], function ( buffer ) {
  15794. const texDatas = scope.parse( buffer, true );
  15795. images[ i ] = {
  15796. width: texDatas.width,
  15797. height: texDatas.height,
  15798. format: texDatas.format,
  15799. mipmaps: texDatas.mipmaps
  15800. };
  15801. loaded += 1;
  15802. if ( loaded === 6 ) {
  15803. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  15804. texture.image = images;
  15805. texture.format = texDatas.format;
  15806. texture.needsUpdate = true;
  15807. if ( onLoad ) onLoad( texture );
  15808. }
  15809. }, onProgress, onError );
  15810. }
  15811. if ( Array.isArray( url ) ) {
  15812. for ( let i = 0, il = url.length; i < il; ++ i ) {
  15813. loadTexture( i );
  15814. }
  15815. } else {
  15816. // compressed cubemap texture stored in a single DDS file
  15817. loader.load( url, function ( buffer ) {
  15818. const texDatas = scope.parse( buffer, true );
  15819. if ( texDatas.isCubemap ) {
  15820. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  15821. for ( let f = 0; f < faces; f ++ ) {
  15822. images[ f ] = { mipmaps: [] };
  15823. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  15824. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  15825. images[ f ].format = texDatas.format;
  15826. images[ f ].width = texDatas.width;
  15827. images[ f ].height = texDatas.height;
  15828. }
  15829. }
  15830. texture.image = images;
  15831. } else {
  15832. texture.image.width = texDatas.width;
  15833. texture.image.height = texDatas.height;
  15834. texture.mipmaps = texDatas.mipmaps;
  15835. }
  15836. if ( texDatas.mipmapCount === 1 ) {
  15837. texture.minFilter = LinearFilter;
  15838. }
  15839. texture.format = texDatas.format;
  15840. texture.needsUpdate = true;
  15841. if ( onLoad ) onLoad( texture );
  15842. }, onProgress, onError );
  15843. }
  15844. return texture;
  15845. }
  15846. }
  15847. class ImageLoader extends Loader {
  15848. constructor( manager ) {
  15849. super( manager );
  15850. }
  15851. load( url, onLoad, onProgress, onError ) {
  15852. if ( this.path !== undefined ) url = this.path + url;
  15853. url = this.manager.resolveURL( url );
  15854. const scope = this;
  15855. const cached = Cache.get( url );
  15856. if ( cached !== undefined ) {
  15857. scope.manager.itemStart( url );
  15858. setTimeout( function () {
  15859. if ( onLoad ) onLoad( cached );
  15860. scope.manager.itemEnd( url );
  15861. }, 0 );
  15862. return cached;
  15863. }
  15864. const image = createElementNS( 'img' );
  15865. function onImageLoad() {
  15866. removeEventListeners();
  15867. Cache.add( url, this );
  15868. if ( onLoad ) onLoad( this );
  15869. scope.manager.itemEnd( url );
  15870. }
  15871. function onImageError( event ) {
  15872. removeEventListeners();
  15873. if ( onError ) onError( event );
  15874. scope.manager.itemError( url );
  15875. scope.manager.itemEnd( url );
  15876. }
  15877. function removeEventListeners() {
  15878. image.removeEventListener( 'load', onImageLoad, false );
  15879. image.removeEventListener( 'error', onImageError, false );
  15880. }
  15881. image.addEventListener( 'load', onImageLoad, false );
  15882. image.addEventListener( 'error', onImageError, false );
  15883. if ( url.slice( 0, 5 ) !== 'data:' ) {
  15884. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  15885. }
  15886. scope.manager.itemStart( url );
  15887. image.src = url;
  15888. return image;
  15889. }
  15890. }
  15891. class CubeTextureLoader extends Loader {
  15892. constructor( manager ) {
  15893. super( manager );
  15894. }
  15895. load( urls, onLoad, onProgress, onError ) {
  15896. const texture = new CubeTexture();
  15897. texture.colorSpace = SRGBColorSpace;
  15898. const loader = new ImageLoader( this.manager );
  15899. loader.setCrossOrigin( this.crossOrigin );
  15900. loader.setPath( this.path );
  15901. let loaded = 0;
  15902. function loadTexture( i ) {
  15903. loader.load( urls[ i ], function ( image ) {
  15904. texture.images[ i ] = image;
  15905. loaded ++;
  15906. if ( loaded === 6 ) {
  15907. texture.needsUpdate = true;
  15908. if ( onLoad ) onLoad( texture );
  15909. }
  15910. }, undefined, onError );
  15911. }
  15912. for ( let i = 0; i < urls.length; ++ i ) {
  15913. loadTexture( i );
  15914. }
  15915. return texture;
  15916. }
  15917. }
  15918. /**
  15919. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  15920. *
  15921. * Sub classes have to implement the parse() method which will be used in load().
  15922. */
  15923. class DataTextureLoader extends Loader {
  15924. constructor( manager ) {
  15925. super( manager );
  15926. }
  15927. load( url, onLoad, onProgress, onError ) {
  15928. const scope = this;
  15929. const texture = new DataTexture();
  15930. const loader = new FileLoader( this.manager );
  15931. loader.setResponseType( 'arraybuffer' );
  15932. loader.setRequestHeader( this.requestHeader );
  15933. loader.setPath( this.path );
  15934. loader.setWithCredentials( scope.withCredentials );
  15935. loader.load( url, function ( buffer ) {
  15936. let texData;
  15937. try {
  15938. texData = scope.parse( buffer );
  15939. } catch ( error ) {
  15940. if ( onError !== undefined ) {
  15941. onError( error );
  15942. } else {
  15943. console.error( error );
  15944. return;
  15945. }
  15946. }
  15947. if ( texData.image !== undefined ) {
  15948. texture.image = texData.image;
  15949. } else if ( texData.data !== undefined ) {
  15950. texture.image.width = texData.width;
  15951. texture.image.height = texData.height;
  15952. texture.image.data = texData.data;
  15953. }
  15954. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  15955. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  15956. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  15957. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  15958. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  15959. if ( texData.colorSpace !== undefined ) {
  15960. texture.colorSpace = texData.colorSpace;
  15961. }
  15962. if ( texData.flipY !== undefined ) {
  15963. texture.flipY = texData.flipY;
  15964. }
  15965. if ( texData.format !== undefined ) {
  15966. texture.format = texData.format;
  15967. }
  15968. if ( texData.type !== undefined ) {
  15969. texture.type = texData.type;
  15970. }
  15971. if ( texData.mipmaps !== undefined ) {
  15972. texture.mipmaps = texData.mipmaps;
  15973. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  15974. }
  15975. if ( texData.mipmapCount === 1 ) {
  15976. texture.minFilter = LinearFilter;
  15977. }
  15978. if ( texData.generateMipmaps !== undefined ) {
  15979. texture.generateMipmaps = texData.generateMipmaps;
  15980. }
  15981. texture.needsUpdate = true;
  15982. if ( onLoad ) onLoad( texture, texData );
  15983. }, onProgress, onError );
  15984. return texture;
  15985. }
  15986. }
  15987. class TextureLoader extends Loader {
  15988. constructor( manager ) {
  15989. super( manager );
  15990. }
  15991. load( url, onLoad, onProgress, onError ) {
  15992. const texture = new Texture();
  15993. const loader = new ImageLoader( this.manager );
  15994. loader.setCrossOrigin( this.crossOrigin );
  15995. loader.setPath( this.path );
  15996. loader.load( url, function ( image ) {
  15997. texture.image = image;
  15998. texture.needsUpdate = true;
  15999. if ( onLoad !== undefined ) {
  16000. onLoad( texture );
  16001. }
  16002. }, onProgress, onError );
  16003. return texture;
  16004. }
  16005. }
  16006. class Light extends Object3D {
  16007. constructor( color, intensity = 1 ) {
  16008. super();
  16009. this.isLight = true;
  16010. this.type = 'Light';
  16011. this.color = new Color( color );
  16012. this.intensity = intensity;
  16013. }
  16014. dispose() {
  16015. // Empty here in base class; some subclasses override.
  16016. }
  16017. copy( source, recursive ) {
  16018. super.copy( source, recursive );
  16019. this.color.copy( source.color );
  16020. this.intensity = source.intensity;
  16021. return this;
  16022. }
  16023. toJSON( meta ) {
  16024. const data = super.toJSON( meta );
  16025. data.object.color = this.color.getHex();
  16026. data.object.intensity = this.intensity;
  16027. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16028. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16029. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16030. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16031. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16032. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16033. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16034. return data;
  16035. }
  16036. }
  16037. class HemisphereLight extends Light {
  16038. constructor( skyColor, groundColor, intensity ) {
  16039. super( skyColor, intensity );
  16040. this.isHemisphereLight = true;
  16041. this.type = 'HemisphereLight';
  16042. this.position.copy( Object3D.DEFAULT_UP );
  16043. this.updateMatrix();
  16044. this.groundColor = new Color( groundColor );
  16045. }
  16046. copy( source, recursive ) {
  16047. super.copy( source, recursive );
  16048. this.groundColor.copy( source.groundColor );
  16049. return this;
  16050. }
  16051. }
  16052. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16053. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16054. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16055. class LightShadow {
  16056. constructor( camera ) {
  16057. this.camera = camera;
  16058. this.intensity = 1;
  16059. this.bias = 0;
  16060. this.normalBias = 0;
  16061. this.radius = 1;
  16062. this.blurSamples = 8;
  16063. this.mapSize = new Vector2( 512, 512 );
  16064. this.map = null;
  16065. this.mapPass = null;
  16066. this.matrix = new Matrix4();
  16067. this.autoUpdate = true;
  16068. this.needsUpdate = false;
  16069. this._frustum = new Frustum();
  16070. this._frameExtents = new Vector2( 1, 1 );
  16071. this._viewportCount = 1;
  16072. this._viewports = [
  16073. new Vector4( 0, 0, 1, 1 )
  16074. ];
  16075. }
  16076. getViewportCount() {
  16077. return this._viewportCount;
  16078. }
  16079. getFrustum() {
  16080. return this._frustum;
  16081. }
  16082. updateMatrices( light ) {
  16083. const shadowCamera = this.camera;
  16084. const shadowMatrix = this.matrix;
  16085. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16086. shadowCamera.position.copy( _lightPositionWorld$1 );
  16087. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16088. shadowCamera.lookAt( _lookTarget$1 );
  16089. shadowCamera.updateMatrixWorld();
  16090. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16091. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16092. shadowMatrix.set(
  16093. 0.5, 0.0, 0.0, 0.5,
  16094. 0.0, 0.5, 0.0, 0.5,
  16095. 0.0, 0.0, 0.5, 0.5,
  16096. 0.0, 0.0, 0.0, 1.0
  16097. );
  16098. shadowMatrix.multiply( _projScreenMatrix$2 );
  16099. }
  16100. getViewport( viewportIndex ) {
  16101. return this._viewports[ viewportIndex ];
  16102. }
  16103. getFrameExtents() {
  16104. return this._frameExtents;
  16105. }
  16106. dispose() {
  16107. if ( this.map ) {
  16108. this.map.dispose();
  16109. }
  16110. if ( this.mapPass ) {
  16111. this.mapPass.dispose();
  16112. }
  16113. }
  16114. copy( source ) {
  16115. this.camera = source.camera.clone();
  16116. this.intensity = source.intensity;
  16117. this.bias = source.bias;
  16118. this.radius = source.radius;
  16119. this.mapSize.copy( source.mapSize );
  16120. return this;
  16121. }
  16122. clone() {
  16123. return new this.constructor().copy( this );
  16124. }
  16125. toJSON() {
  16126. const object = {};
  16127. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16128. if ( this.bias !== 0 ) object.bias = this.bias;
  16129. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16130. if ( this.radius !== 1 ) object.radius = this.radius;
  16131. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16132. object.camera = this.camera.toJSON( false ).object;
  16133. delete object.camera.matrix;
  16134. return object;
  16135. }
  16136. }
  16137. class SpotLightShadow extends LightShadow {
  16138. constructor() {
  16139. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16140. this.isSpotLightShadow = true;
  16141. this.focus = 1;
  16142. }
  16143. updateMatrices( light ) {
  16144. const camera = this.camera;
  16145. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16146. const aspect = this.mapSize.width / this.mapSize.height;
  16147. const far = light.distance || camera.far;
  16148. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16149. camera.fov = fov;
  16150. camera.aspect = aspect;
  16151. camera.far = far;
  16152. camera.updateProjectionMatrix();
  16153. }
  16154. super.updateMatrices( light );
  16155. }
  16156. copy( source ) {
  16157. super.copy( source );
  16158. this.focus = source.focus;
  16159. return this;
  16160. }
  16161. }
  16162. class SpotLight extends Light {
  16163. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16164. super( color, intensity );
  16165. this.isSpotLight = true;
  16166. this.type = 'SpotLight';
  16167. this.position.copy( Object3D.DEFAULT_UP );
  16168. this.updateMatrix();
  16169. this.target = new Object3D();
  16170. this.distance = distance;
  16171. this.angle = angle;
  16172. this.penumbra = penumbra;
  16173. this.decay = decay;
  16174. this.map = null;
  16175. this.shadow = new SpotLightShadow();
  16176. }
  16177. get power() {
  16178. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16179. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16180. return this.intensity * Math.PI;
  16181. }
  16182. set power( power ) {
  16183. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16184. this.intensity = power / Math.PI;
  16185. }
  16186. dispose() {
  16187. this.shadow.dispose();
  16188. }
  16189. copy( source, recursive ) {
  16190. super.copy( source, recursive );
  16191. this.distance = source.distance;
  16192. this.angle = source.angle;
  16193. this.penumbra = source.penumbra;
  16194. this.decay = source.decay;
  16195. this.target = source.target.clone();
  16196. this.shadow = source.shadow.clone();
  16197. return this;
  16198. }
  16199. }
  16200. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16201. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16202. const _lookTarget = /*@__PURE__*/ new Vector3();
  16203. class PointLightShadow extends LightShadow {
  16204. constructor() {
  16205. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16206. this.isPointLightShadow = true;
  16207. this._frameExtents = new Vector2( 4, 2 );
  16208. this._viewportCount = 6;
  16209. this._viewports = [
  16210. // These viewports map a cube-map onto a 2D texture with the
  16211. // following orientation:
  16212. //
  16213. // xzXZ
  16214. // y Y
  16215. //
  16216. // X - Positive x direction
  16217. // x - Negative x direction
  16218. // Y - Positive y direction
  16219. // y - Negative y direction
  16220. // Z - Positive z direction
  16221. // z - Negative z direction
  16222. // positive X
  16223. new Vector4( 2, 1, 1, 1 ),
  16224. // negative X
  16225. new Vector4( 0, 1, 1, 1 ),
  16226. // positive Z
  16227. new Vector4( 3, 1, 1, 1 ),
  16228. // negative Z
  16229. new Vector4( 1, 1, 1, 1 ),
  16230. // positive Y
  16231. new Vector4( 3, 0, 1, 1 ),
  16232. // negative Y
  16233. new Vector4( 1, 0, 1, 1 )
  16234. ];
  16235. this._cubeDirections = [
  16236. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16237. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16238. ];
  16239. this._cubeUps = [
  16240. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16241. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16242. ];
  16243. }
  16244. updateMatrices( light, viewportIndex = 0 ) {
  16245. const camera = this.camera;
  16246. const shadowMatrix = this.matrix;
  16247. const far = light.distance || camera.far;
  16248. if ( far !== camera.far ) {
  16249. camera.far = far;
  16250. camera.updateProjectionMatrix();
  16251. }
  16252. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16253. camera.position.copy( _lightPositionWorld );
  16254. _lookTarget.copy( camera.position );
  16255. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16256. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16257. camera.lookAt( _lookTarget );
  16258. camera.updateMatrixWorld();
  16259. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16260. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16261. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16262. }
  16263. }
  16264. class PointLight extends Light {
  16265. constructor( color, intensity, distance = 0, decay = 2 ) {
  16266. super( color, intensity );
  16267. this.isPointLight = true;
  16268. this.type = 'PointLight';
  16269. this.distance = distance;
  16270. this.decay = decay;
  16271. this.shadow = new PointLightShadow();
  16272. }
  16273. get power() {
  16274. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16275. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16276. return this.intensity * 4 * Math.PI;
  16277. }
  16278. set power( power ) {
  16279. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16280. this.intensity = power / ( 4 * Math.PI );
  16281. }
  16282. dispose() {
  16283. this.shadow.dispose();
  16284. }
  16285. copy( source, recursive ) {
  16286. super.copy( source, recursive );
  16287. this.distance = source.distance;
  16288. this.decay = source.decay;
  16289. this.shadow = source.shadow.clone();
  16290. return this;
  16291. }
  16292. }
  16293. class OrthographicCamera extends Camera {
  16294. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16295. super();
  16296. this.isOrthographicCamera = true;
  16297. this.type = 'OrthographicCamera';
  16298. this.zoom = 1;
  16299. this.view = null;
  16300. this.left = left;
  16301. this.right = right;
  16302. this.top = top;
  16303. this.bottom = bottom;
  16304. this.near = near;
  16305. this.far = far;
  16306. this.updateProjectionMatrix();
  16307. }
  16308. copy( source, recursive ) {
  16309. super.copy( source, recursive );
  16310. this.left = source.left;
  16311. this.right = source.right;
  16312. this.top = source.top;
  16313. this.bottom = source.bottom;
  16314. this.near = source.near;
  16315. this.far = source.far;
  16316. this.zoom = source.zoom;
  16317. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16318. return this;
  16319. }
  16320. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16321. if ( this.view === null ) {
  16322. this.view = {
  16323. enabled: true,
  16324. fullWidth: 1,
  16325. fullHeight: 1,
  16326. offsetX: 0,
  16327. offsetY: 0,
  16328. width: 1,
  16329. height: 1
  16330. };
  16331. }
  16332. this.view.enabled = true;
  16333. this.view.fullWidth = fullWidth;
  16334. this.view.fullHeight = fullHeight;
  16335. this.view.offsetX = x;
  16336. this.view.offsetY = y;
  16337. this.view.width = width;
  16338. this.view.height = height;
  16339. this.updateProjectionMatrix();
  16340. }
  16341. clearViewOffset() {
  16342. if ( this.view !== null ) {
  16343. this.view.enabled = false;
  16344. }
  16345. this.updateProjectionMatrix();
  16346. }
  16347. updateProjectionMatrix() {
  16348. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16349. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16350. const cx = ( this.right + this.left ) / 2;
  16351. const cy = ( this.top + this.bottom ) / 2;
  16352. let left = cx - dx;
  16353. let right = cx + dx;
  16354. let top = cy + dy;
  16355. let bottom = cy - dy;
  16356. if ( this.view !== null && this.view.enabled ) {
  16357. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16358. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16359. left += scaleW * this.view.offsetX;
  16360. right = left + scaleW * this.view.width;
  16361. top -= scaleH * this.view.offsetY;
  16362. bottom = top - scaleH * this.view.height;
  16363. }
  16364. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16365. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16366. }
  16367. toJSON( meta ) {
  16368. const data = super.toJSON( meta );
  16369. data.object.zoom = this.zoom;
  16370. data.object.left = this.left;
  16371. data.object.right = this.right;
  16372. data.object.top = this.top;
  16373. data.object.bottom = this.bottom;
  16374. data.object.near = this.near;
  16375. data.object.far = this.far;
  16376. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16377. return data;
  16378. }
  16379. }
  16380. class DirectionalLightShadow extends LightShadow {
  16381. constructor() {
  16382. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16383. this.isDirectionalLightShadow = true;
  16384. }
  16385. }
  16386. class DirectionalLight extends Light {
  16387. constructor( color, intensity ) {
  16388. super( color, intensity );
  16389. this.isDirectionalLight = true;
  16390. this.type = 'DirectionalLight';
  16391. this.position.copy( Object3D.DEFAULT_UP );
  16392. this.updateMatrix();
  16393. this.target = new Object3D();
  16394. this.shadow = new DirectionalLightShadow();
  16395. }
  16396. dispose() {
  16397. this.shadow.dispose();
  16398. }
  16399. copy( source ) {
  16400. super.copy( source );
  16401. this.target = source.target.clone();
  16402. this.shadow = source.shadow.clone();
  16403. return this;
  16404. }
  16405. }
  16406. class AmbientLight extends Light {
  16407. constructor( color, intensity ) {
  16408. super( color, intensity );
  16409. this.isAmbientLight = true;
  16410. this.type = 'AmbientLight';
  16411. }
  16412. }
  16413. class RectAreaLight extends Light {
  16414. constructor( color, intensity, width = 10, height = 10 ) {
  16415. super( color, intensity );
  16416. this.isRectAreaLight = true;
  16417. this.type = 'RectAreaLight';
  16418. this.width = width;
  16419. this.height = height;
  16420. }
  16421. get power() {
  16422. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16423. return this.intensity * this.width * this.height * Math.PI;
  16424. }
  16425. set power( power ) {
  16426. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16427. this.intensity = power / ( this.width * this.height * Math.PI );
  16428. }
  16429. copy( source ) {
  16430. super.copy( source );
  16431. this.width = source.width;
  16432. this.height = source.height;
  16433. return this;
  16434. }
  16435. toJSON( meta ) {
  16436. const data = super.toJSON( meta );
  16437. data.object.width = this.width;
  16438. data.object.height = this.height;
  16439. return data;
  16440. }
  16441. }
  16442. /**
  16443. * Primary reference:
  16444. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16445. *
  16446. * Secondary reference:
  16447. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16448. */
  16449. // 3-band SH defined by 9 coefficients
  16450. class SphericalHarmonics3 {
  16451. constructor() {
  16452. this.isSphericalHarmonics3 = true;
  16453. this.coefficients = [];
  16454. for ( let i = 0; i < 9; i ++ ) {
  16455. this.coefficients.push( new Vector3() );
  16456. }
  16457. }
  16458. set( coefficients ) {
  16459. for ( let i = 0; i < 9; i ++ ) {
  16460. this.coefficients[ i ].copy( coefficients[ i ] );
  16461. }
  16462. return this;
  16463. }
  16464. zero() {
  16465. for ( let i = 0; i < 9; i ++ ) {
  16466. this.coefficients[ i ].set( 0, 0, 0 );
  16467. }
  16468. return this;
  16469. }
  16470. // get the radiance in the direction of the normal
  16471. // target is a Vector3
  16472. getAt( normal, target ) {
  16473. // normal is assumed to be unit length
  16474. const x = normal.x, y = normal.y, z = normal.z;
  16475. const coeff = this.coefficients;
  16476. // band 0
  16477. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16478. // band 1
  16479. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16480. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16481. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16482. // band 2
  16483. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16484. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16485. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16486. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16487. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16488. return target;
  16489. }
  16490. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16491. // target is a Vector3
  16492. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16493. getIrradianceAt( normal, target ) {
  16494. // normal is assumed to be unit length
  16495. const x = normal.x, y = normal.y, z = normal.z;
  16496. const coeff = this.coefficients;
  16497. // band 0
  16498. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16499. // band 1
  16500. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16501. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16502. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16503. // band 2
  16504. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16505. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16506. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16507. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16508. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16509. return target;
  16510. }
  16511. add( sh ) {
  16512. for ( let i = 0; i < 9; i ++ ) {
  16513. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16514. }
  16515. return this;
  16516. }
  16517. addScaledSH( sh, s ) {
  16518. for ( let i = 0; i < 9; i ++ ) {
  16519. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16520. }
  16521. return this;
  16522. }
  16523. scale( s ) {
  16524. for ( let i = 0; i < 9; i ++ ) {
  16525. this.coefficients[ i ].multiplyScalar( s );
  16526. }
  16527. return this;
  16528. }
  16529. lerp( sh, alpha ) {
  16530. for ( let i = 0; i < 9; i ++ ) {
  16531. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16532. }
  16533. return this;
  16534. }
  16535. equals( sh ) {
  16536. for ( let i = 0; i < 9; i ++ ) {
  16537. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16538. return false;
  16539. }
  16540. }
  16541. return true;
  16542. }
  16543. copy( sh ) {
  16544. return this.set( sh.coefficients );
  16545. }
  16546. clone() {
  16547. return new this.constructor().copy( this );
  16548. }
  16549. fromArray( array, offset = 0 ) {
  16550. const coefficients = this.coefficients;
  16551. for ( let i = 0; i < 9; i ++ ) {
  16552. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16553. }
  16554. return this;
  16555. }
  16556. toArray( array = [], offset = 0 ) {
  16557. const coefficients = this.coefficients;
  16558. for ( let i = 0; i < 9; i ++ ) {
  16559. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16560. }
  16561. return array;
  16562. }
  16563. // evaluate the basis functions
  16564. // shBasis is an Array[ 9 ]
  16565. static getBasisAt( normal, shBasis ) {
  16566. // normal is assumed to be unit length
  16567. const x = normal.x, y = normal.y, z = normal.z;
  16568. // band 0
  16569. shBasis[ 0 ] = 0.282095;
  16570. // band 1
  16571. shBasis[ 1 ] = 0.488603 * y;
  16572. shBasis[ 2 ] = 0.488603 * z;
  16573. shBasis[ 3 ] = 0.488603 * x;
  16574. // band 2
  16575. shBasis[ 4 ] = 1.092548 * x * y;
  16576. shBasis[ 5 ] = 1.092548 * y * z;
  16577. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16578. shBasis[ 7 ] = 1.092548 * x * z;
  16579. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16580. }
  16581. }
  16582. class LightProbe extends Light {
  16583. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16584. super( undefined, intensity );
  16585. this.isLightProbe = true;
  16586. this.sh = sh;
  16587. }
  16588. copy( source ) {
  16589. super.copy( source );
  16590. this.sh.copy( source.sh );
  16591. return this;
  16592. }
  16593. fromJSON( json ) {
  16594. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16595. this.sh.fromArray( json.sh );
  16596. return this;
  16597. }
  16598. toJSON( meta ) {
  16599. const data = super.toJSON( meta );
  16600. data.object.sh = this.sh.toArray();
  16601. return data;
  16602. }
  16603. }
  16604. class MaterialLoader extends Loader {
  16605. constructor( manager ) {
  16606. super( manager );
  16607. this.textures = {};
  16608. }
  16609. load( url, onLoad, onProgress, onError ) {
  16610. const scope = this;
  16611. const loader = new FileLoader( scope.manager );
  16612. loader.setPath( scope.path );
  16613. loader.setRequestHeader( scope.requestHeader );
  16614. loader.setWithCredentials( scope.withCredentials );
  16615. loader.load( url, function ( text ) {
  16616. try {
  16617. onLoad( scope.parse( JSON.parse( text ) ) );
  16618. } catch ( e ) {
  16619. if ( onError ) {
  16620. onError( e );
  16621. } else {
  16622. console.error( e );
  16623. }
  16624. scope.manager.itemError( url );
  16625. }
  16626. }, onProgress, onError );
  16627. }
  16628. parse( json ) {
  16629. const textures = this.textures;
  16630. function getTexture( name ) {
  16631. if ( textures[ name ] === undefined ) {
  16632. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16633. }
  16634. return textures[ name ];
  16635. }
  16636. const material = MaterialLoader.createMaterialFromType( json.type );
  16637. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16638. if ( json.name !== undefined ) material.name = json.name;
  16639. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16640. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16641. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16642. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16643. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16644. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16645. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16646. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16647. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16648. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16649. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16650. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16651. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16652. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16653. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16654. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16655. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16656. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16657. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16658. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16659. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16660. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16661. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16662. if ( json.fog !== undefined ) material.fog = json.fog;
  16663. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16664. if ( json.blending !== undefined ) material.blending = json.blending;
  16665. if ( json.combine !== undefined ) material.combine = json.combine;
  16666. if ( json.side !== undefined ) material.side = json.side;
  16667. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16668. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16669. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16670. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16671. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16672. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16673. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16674. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16675. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16676. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16677. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16678. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16679. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16680. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16681. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16682. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16683. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16684. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16685. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16686. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16687. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16688. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16689. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16690. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16691. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16692. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16693. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16694. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16695. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16696. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16697. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16698. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16699. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16700. if ( json.scale !== undefined ) material.scale = json.scale;
  16701. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16702. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16703. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16704. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16705. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16706. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16707. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16708. if ( json.visible !== undefined ) material.visible = json.visible;
  16709. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16710. if ( json.userData !== undefined ) material.userData = json.userData;
  16711. if ( json.vertexColors !== undefined ) {
  16712. if ( typeof json.vertexColors === 'number' ) {
  16713. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16714. } else {
  16715. material.vertexColors = json.vertexColors;
  16716. }
  16717. }
  16718. // Shader Material
  16719. if ( json.uniforms !== undefined ) {
  16720. for ( const name in json.uniforms ) {
  16721. const uniform = json.uniforms[ name ];
  16722. material.uniforms[ name ] = {};
  16723. switch ( uniform.type ) {
  16724. case 't':
  16725. material.uniforms[ name ].value = getTexture( uniform.value );
  16726. break;
  16727. case 'c':
  16728. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16729. break;
  16730. case 'v2':
  16731. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16732. break;
  16733. case 'v3':
  16734. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16735. break;
  16736. case 'v4':
  16737. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  16738. break;
  16739. case 'm3':
  16740. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  16741. break;
  16742. case 'm4':
  16743. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  16744. break;
  16745. default:
  16746. material.uniforms[ name ].value = uniform.value;
  16747. }
  16748. }
  16749. }
  16750. if ( json.defines !== undefined ) material.defines = json.defines;
  16751. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16752. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16753. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  16754. if ( json.extensions !== undefined ) {
  16755. for ( const key in json.extensions ) {
  16756. material.extensions[ key ] = json.extensions[ key ];
  16757. }
  16758. }
  16759. if ( json.lights !== undefined ) material.lights = json.lights;
  16760. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  16761. // for PointsMaterial
  16762. if ( json.size !== undefined ) material.size = json.size;
  16763. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16764. // maps
  16765. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16766. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  16767. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  16768. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16769. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16770. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16771. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  16772. if ( json.normalScale !== undefined ) {
  16773. let normalScale = json.normalScale;
  16774. if ( Array.isArray( normalScale ) === false ) {
  16775. // Blender exporter used to export a scalar. See #7459
  16776. normalScale = [ normalScale, normalScale ];
  16777. }
  16778. material.normalScale = new Vector2().fromArray( normalScale );
  16779. }
  16780. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16781. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16782. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16783. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16784. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16785. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16786. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16787. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16788. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  16789. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  16790. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16791. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  16792. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  16793. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16794. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  16795. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16796. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16797. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16798. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16799. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  16800. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  16801. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  16802. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  16803. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16804. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  16805. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  16806. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  16807. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  16808. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  16809. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  16810. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  16811. return material;
  16812. }
  16813. setTextures( value ) {
  16814. this.textures = value;
  16815. return this;
  16816. }
  16817. static createMaterialFromType( type ) {
  16818. const materialLib = {
  16819. ShadowMaterial,
  16820. SpriteMaterial,
  16821. RawShaderMaterial,
  16822. ShaderMaterial,
  16823. PointsMaterial,
  16824. MeshPhysicalMaterial,
  16825. MeshStandardMaterial,
  16826. MeshPhongMaterial,
  16827. MeshToonMaterial,
  16828. MeshNormalMaterial,
  16829. MeshLambertMaterial,
  16830. MeshDepthMaterial,
  16831. MeshDistanceMaterial,
  16832. MeshBasicMaterial,
  16833. MeshMatcapMaterial,
  16834. LineDashedMaterial,
  16835. LineBasicMaterial,
  16836. Material
  16837. };
  16838. return new materialLib[ type ]();
  16839. }
  16840. }
  16841. class LoaderUtils {
  16842. static decodeText( array ) { // @deprecated, r165
  16843. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  16844. if ( typeof TextDecoder !== 'undefined' ) {
  16845. return new TextDecoder().decode( array );
  16846. }
  16847. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  16848. // throws a "maximum call stack size exceeded" error for large arrays.
  16849. let s = '';
  16850. for ( let i = 0, il = array.length; i < il; i ++ ) {
  16851. // Implicitly assumes little-endian.
  16852. s += String.fromCharCode( array[ i ] );
  16853. }
  16854. try {
  16855. // merges multi-byte utf-8 characters.
  16856. return decodeURIComponent( escape( s ) );
  16857. } catch ( e ) { // see #16358
  16858. return s;
  16859. }
  16860. }
  16861. static extractUrlBase( url ) {
  16862. const index = url.lastIndexOf( '/' );
  16863. if ( index === - 1 ) return './';
  16864. return url.slice( 0, index + 1 );
  16865. }
  16866. static resolveURL( url, path ) {
  16867. // Invalid URL
  16868. if ( typeof url !== 'string' || url === '' ) return '';
  16869. // Host Relative URL
  16870. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  16871. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  16872. }
  16873. // Absolute URL http://,https://,//
  16874. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  16875. // Data URI
  16876. if ( /^data:.*,.*$/i.test( url ) ) return url;
  16877. // Blob URL
  16878. if ( /^blob:.*$/i.test( url ) ) return url;
  16879. // Relative URL
  16880. return path + url;
  16881. }
  16882. }
  16883. class InstancedBufferGeometry extends BufferGeometry {
  16884. constructor() {
  16885. super();
  16886. this.isInstancedBufferGeometry = true;
  16887. this.type = 'InstancedBufferGeometry';
  16888. this.instanceCount = Infinity;
  16889. }
  16890. copy( source ) {
  16891. super.copy( source );
  16892. this.instanceCount = source.instanceCount;
  16893. return this;
  16894. }
  16895. toJSON() {
  16896. const data = super.toJSON();
  16897. data.instanceCount = this.instanceCount;
  16898. data.isInstancedBufferGeometry = true;
  16899. return data;
  16900. }
  16901. }
  16902. class BufferGeometryLoader extends Loader {
  16903. constructor( manager ) {
  16904. super( manager );
  16905. }
  16906. load( url, onLoad, onProgress, onError ) {
  16907. const scope = this;
  16908. const loader = new FileLoader( scope.manager );
  16909. loader.setPath( scope.path );
  16910. loader.setRequestHeader( scope.requestHeader );
  16911. loader.setWithCredentials( scope.withCredentials );
  16912. loader.load( url, function ( text ) {
  16913. try {
  16914. onLoad( scope.parse( JSON.parse( text ) ) );
  16915. } catch ( e ) {
  16916. if ( onError ) {
  16917. onError( e );
  16918. } else {
  16919. console.error( e );
  16920. }
  16921. scope.manager.itemError( url );
  16922. }
  16923. }, onProgress, onError );
  16924. }
  16925. parse( json ) {
  16926. const interleavedBufferMap = {};
  16927. const arrayBufferMap = {};
  16928. function getInterleavedBuffer( json, uuid ) {
  16929. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  16930. const interleavedBuffers = json.interleavedBuffers;
  16931. const interleavedBuffer = interleavedBuffers[ uuid ];
  16932. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  16933. const array = getTypedArray( interleavedBuffer.type, buffer );
  16934. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  16935. ib.uuid = interleavedBuffer.uuid;
  16936. interleavedBufferMap[ uuid ] = ib;
  16937. return ib;
  16938. }
  16939. function getArrayBuffer( json, uuid ) {
  16940. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  16941. const arrayBuffers = json.arrayBuffers;
  16942. const arrayBuffer = arrayBuffers[ uuid ];
  16943. const ab = new Uint32Array( arrayBuffer ).buffer;
  16944. arrayBufferMap[ uuid ] = ab;
  16945. return ab;
  16946. }
  16947. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  16948. const index = json.data.index;
  16949. if ( index !== undefined ) {
  16950. const typedArray = getTypedArray( index.type, index.array );
  16951. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16952. }
  16953. const attributes = json.data.attributes;
  16954. for ( const key in attributes ) {
  16955. const attribute = attributes[ key ];
  16956. let bufferAttribute;
  16957. if ( attribute.isInterleavedBufferAttribute ) {
  16958. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16959. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16960. } else {
  16961. const typedArray = getTypedArray( attribute.type, attribute.array );
  16962. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  16963. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  16964. }
  16965. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16966. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  16967. geometry.setAttribute( key, bufferAttribute );
  16968. }
  16969. const morphAttributes = json.data.morphAttributes;
  16970. if ( morphAttributes ) {
  16971. for ( const key in morphAttributes ) {
  16972. const attributeArray = morphAttributes[ key ];
  16973. const array = [];
  16974. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  16975. const attribute = attributeArray[ i ];
  16976. let bufferAttribute;
  16977. if ( attribute.isInterleavedBufferAttribute ) {
  16978. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16979. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16980. } else {
  16981. const typedArray = getTypedArray( attribute.type, attribute.array );
  16982. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  16983. }
  16984. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16985. array.push( bufferAttribute );
  16986. }
  16987. geometry.morphAttributes[ key ] = array;
  16988. }
  16989. }
  16990. const morphTargetsRelative = json.data.morphTargetsRelative;
  16991. if ( morphTargetsRelative ) {
  16992. geometry.morphTargetsRelative = true;
  16993. }
  16994. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  16995. if ( groups !== undefined ) {
  16996. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  16997. const group = groups[ i ];
  16998. geometry.addGroup( group.start, group.count, group.materialIndex );
  16999. }
  17000. }
  17001. const boundingSphere = json.data.boundingSphere;
  17002. if ( boundingSphere !== undefined ) {
  17003. const center = new Vector3();
  17004. if ( boundingSphere.center !== undefined ) {
  17005. center.fromArray( boundingSphere.center );
  17006. }
  17007. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17008. }
  17009. if ( json.name ) geometry.name = json.name;
  17010. if ( json.userData ) geometry.userData = json.userData;
  17011. return geometry;
  17012. }
  17013. }
  17014. class ObjectLoader extends Loader {
  17015. constructor( manager ) {
  17016. super( manager );
  17017. }
  17018. load( url, onLoad, onProgress, onError ) {
  17019. const scope = this;
  17020. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17021. this.resourcePath = this.resourcePath || path;
  17022. const loader = new FileLoader( this.manager );
  17023. loader.setPath( this.path );
  17024. loader.setRequestHeader( this.requestHeader );
  17025. loader.setWithCredentials( this.withCredentials );
  17026. loader.load( url, function ( text ) {
  17027. let json = null;
  17028. try {
  17029. json = JSON.parse( text );
  17030. } catch ( error ) {
  17031. if ( onError !== undefined ) onError( error );
  17032. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17033. return;
  17034. }
  17035. const metadata = json.metadata;
  17036. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17037. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17038. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17039. return;
  17040. }
  17041. scope.parse( json, onLoad );
  17042. }, onProgress, onError );
  17043. }
  17044. async loadAsync( url, onProgress ) {
  17045. const scope = this;
  17046. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17047. this.resourcePath = this.resourcePath || path;
  17048. const loader = new FileLoader( this.manager );
  17049. loader.setPath( this.path );
  17050. loader.setRequestHeader( this.requestHeader );
  17051. loader.setWithCredentials( this.withCredentials );
  17052. const text = await loader.loadAsync( url, onProgress );
  17053. const json = JSON.parse( text );
  17054. const metadata = json.metadata;
  17055. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17056. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17057. }
  17058. return await scope.parseAsync( json );
  17059. }
  17060. parse( json, onLoad ) {
  17061. const animations = this.parseAnimations( json.animations );
  17062. const shapes = this.parseShapes( json.shapes );
  17063. const geometries = this.parseGeometries( json.geometries, shapes );
  17064. const images = this.parseImages( json.images, function () {
  17065. if ( onLoad !== undefined ) onLoad( object );
  17066. } );
  17067. const textures = this.parseTextures( json.textures, images );
  17068. const materials = this.parseMaterials( json.materials, textures );
  17069. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17070. const skeletons = this.parseSkeletons( json.skeletons, object );
  17071. this.bindSkeletons( object, skeletons );
  17072. this.bindLightTargets( object );
  17073. //
  17074. if ( onLoad !== undefined ) {
  17075. let hasImages = false;
  17076. for ( const uuid in images ) {
  17077. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17078. hasImages = true;
  17079. break;
  17080. }
  17081. }
  17082. if ( hasImages === false ) onLoad( object );
  17083. }
  17084. return object;
  17085. }
  17086. async parseAsync( json ) {
  17087. const animations = this.parseAnimations( json.animations );
  17088. const shapes = this.parseShapes( json.shapes );
  17089. const geometries = this.parseGeometries( json.geometries, shapes );
  17090. const images = await this.parseImagesAsync( json.images );
  17091. const textures = this.parseTextures( json.textures, images );
  17092. const materials = this.parseMaterials( json.materials, textures );
  17093. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17094. const skeletons = this.parseSkeletons( json.skeletons, object );
  17095. this.bindSkeletons( object, skeletons );
  17096. this.bindLightTargets( object );
  17097. return object;
  17098. }
  17099. parseShapes( json ) {
  17100. const shapes = {};
  17101. if ( json !== undefined ) {
  17102. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17103. const shape = new Shape().fromJSON( json[ i ] );
  17104. shapes[ shape.uuid ] = shape;
  17105. }
  17106. }
  17107. return shapes;
  17108. }
  17109. parseSkeletons( json, object ) {
  17110. const skeletons = {};
  17111. const bones = {};
  17112. // generate bone lookup table
  17113. object.traverse( function ( child ) {
  17114. if ( child.isBone ) bones[ child.uuid ] = child;
  17115. } );
  17116. // create skeletons
  17117. if ( json !== undefined ) {
  17118. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17119. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17120. skeletons[ skeleton.uuid ] = skeleton;
  17121. }
  17122. }
  17123. return skeletons;
  17124. }
  17125. parseGeometries( json, shapes ) {
  17126. const geometries = {};
  17127. if ( json !== undefined ) {
  17128. const bufferGeometryLoader = new BufferGeometryLoader();
  17129. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17130. let geometry;
  17131. const data = json[ i ];
  17132. switch ( data.type ) {
  17133. case 'BufferGeometry':
  17134. case 'InstancedBufferGeometry':
  17135. geometry = bufferGeometryLoader.parse( data );
  17136. break;
  17137. default:
  17138. if ( data.type in Geometries$1 ) {
  17139. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17140. } else {
  17141. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17142. }
  17143. }
  17144. geometry.uuid = data.uuid;
  17145. if ( data.name !== undefined ) geometry.name = data.name;
  17146. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17147. geometries[ data.uuid ] = geometry;
  17148. }
  17149. }
  17150. return geometries;
  17151. }
  17152. parseMaterials( json, textures ) {
  17153. const cache = {}; // MultiMaterial
  17154. const materials = {};
  17155. if ( json !== undefined ) {
  17156. const loader = new MaterialLoader();
  17157. loader.setTextures( textures );
  17158. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17159. const data = json[ i ];
  17160. if ( cache[ data.uuid ] === undefined ) {
  17161. cache[ data.uuid ] = loader.parse( data );
  17162. }
  17163. materials[ data.uuid ] = cache[ data.uuid ];
  17164. }
  17165. }
  17166. return materials;
  17167. }
  17168. parseAnimations( json ) {
  17169. const animations = {};
  17170. if ( json !== undefined ) {
  17171. for ( let i = 0; i < json.length; i ++ ) {
  17172. const data = json[ i ];
  17173. const clip = AnimationClip.parse( data );
  17174. animations[ clip.uuid ] = clip;
  17175. }
  17176. }
  17177. return animations;
  17178. }
  17179. parseImages( json, onLoad ) {
  17180. const scope = this;
  17181. const images = {};
  17182. let loader;
  17183. function loadImage( url ) {
  17184. scope.manager.itemStart( url );
  17185. return loader.load( url, function () {
  17186. scope.manager.itemEnd( url );
  17187. }, undefined, function () {
  17188. scope.manager.itemError( url );
  17189. scope.manager.itemEnd( url );
  17190. } );
  17191. }
  17192. function deserializeImage( image ) {
  17193. if ( typeof image === 'string' ) {
  17194. const url = image;
  17195. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17196. return loadImage( path );
  17197. } else {
  17198. if ( image.data ) {
  17199. return {
  17200. data: getTypedArray( image.type, image.data ),
  17201. width: image.width,
  17202. height: image.height
  17203. };
  17204. } else {
  17205. return null;
  17206. }
  17207. }
  17208. }
  17209. if ( json !== undefined && json.length > 0 ) {
  17210. const manager = new LoadingManager( onLoad );
  17211. loader = new ImageLoader( manager );
  17212. loader.setCrossOrigin( this.crossOrigin );
  17213. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17214. const image = json[ i ];
  17215. const url = image.url;
  17216. if ( Array.isArray( url ) ) {
  17217. // load array of images e.g CubeTexture
  17218. const imageArray = [];
  17219. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17220. const currentUrl = url[ j ];
  17221. const deserializedImage = deserializeImage( currentUrl );
  17222. if ( deserializedImage !== null ) {
  17223. if ( deserializedImage instanceof HTMLImageElement ) {
  17224. imageArray.push( deserializedImage );
  17225. } else {
  17226. // special case: handle array of data textures for cube textures
  17227. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17228. }
  17229. }
  17230. }
  17231. images[ image.uuid ] = new Source( imageArray );
  17232. } else {
  17233. // load single image
  17234. const deserializedImage = deserializeImage( image.url );
  17235. images[ image.uuid ] = new Source( deserializedImage );
  17236. }
  17237. }
  17238. }
  17239. return images;
  17240. }
  17241. async parseImagesAsync( json ) {
  17242. const scope = this;
  17243. const images = {};
  17244. let loader;
  17245. async function deserializeImage( image ) {
  17246. if ( typeof image === 'string' ) {
  17247. const url = image;
  17248. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17249. return await loader.loadAsync( path );
  17250. } else {
  17251. if ( image.data ) {
  17252. return {
  17253. data: getTypedArray( image.type, image.data ),
  17254. width: image.width,
  17255. height: image.height
  17256. };
  17257. } else {
  17258. return null;
  17259. }
  17260. }
  17261. }
  17262. if ( json !== undefined && json.length > 0 ) {
  17263. loader = new ImageLoader( this.manager );
  17264. loader.setCrossOrigin( this.crossOrigin );
  17265. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17266. const image = json[ i ];
  17267. const url = image.url;
  17268. if ( Array.isArray( url ) ) {
  17269. // load array of images e.g CubeTexture
  17270. const imageArray = [];
  17271. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17272. const currentUrl = url[ j ];
  17273. const deserializedImage = await deserializeImage( currentUrl );
  17274. if ( deserializedImage !== null ) {
  17275. if ( deserializedImage instanceof HTMLImageElement ) {
  17276. imageArray.push( deserializedImage );
  17277. } else {
  17278. // special case: handle array of data textures for cube textures
  17279. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17280. }
  17281. }
  17282. }
  17283. images[ image.uuid ] = new Source( imageArray );
  17284. } else {
  17285. // load single image
  17286. const deserializedImage = await deserializeImage( image.url );
  17287. images[ image.uuid ] = new Source( deserializedImage );
  17288. }
  17289. }
  17290. }
  17291. return images;
  17292. }
  17293. parseTextures( json, images ) {
  17294. function parseConstant( value, type ) {
  17295. if ( typeof value === 'number' ) return value;
  17296. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17297. return type[ value ];
  17298. }
  17299. const textures = {};
  17300. if ( json !== undefined ) {
  17301. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17302. const data = json[ i ];
  17303. if ( data.image === undefined ) {
  17304. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17305. }
  17306. if ( images[ data.image ] === undefined ) {
  17307. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17308. }
  17309. const source = images[ data.image ];
  17310. const image = source.data;
  17311. let texture;
  17312. if ( Array.isArray( image ) ) {
  17313. texture = new CubeTexture();
  17314. if ( image.length === 6 ) texture.needsUpdate = true;
  17315. } else {
  17316. if ( image && image.data ) {
  17317. texture = new DataTexture();
  17318. } else {
  17319. texture = new Texture();
  17320. }
  17321. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17322. }
  17323. texture.source = source;
  17324. texture.uuid = data.uuid;
  17325. if ( data.name !== undefined ) texture.name = data.name;
  17326. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17327. if ( data.channel !== undefined ) texture.channel = data.channel;
  17328. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17329. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17330. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17331. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17332. if ( data.wrap !== undefined ) {
  17333. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17334. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17335. }
  17336. if ( data.format !== undefined ) texture.format = data.format;
  17337. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17338. if ( data.type !== undefined ) texture.type = data.type;
  17339. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17340. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17341. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17342. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17343. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17344. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17345. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17346. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17347. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17348. if ( data.userData !== undefined ) texture.userData = data.userData;
  17349. textures[ data.uuid ] = texture;
  17350. }
  17351. }
  17352. return textures;
  17353. }
  17354. parseObject( data, geometries, materials, textures, animations ) {
  17355. let object;
  17356. function getGeometry( name ) {
  17357. if ( geometries[ name ] === undefined ) {
  17358. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17359. }
  17360. return geometries[ name ];
  17361. }
  17362. function getMaterial( name ) {
  17363. if ( name === undefined ) return undefined;
  17364. if ( Array.isArray( name ) ) {
  17365. const array = [];
  17366. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17367. const uuid = name[ i ];
  17368. if ( materials[ uuid ] === undefined ) {
  17369. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17370. }
  17371. array.push( materials[ uuid ] );
  17372. }
  17373. return array;
  17374. }
  17375. if ( materials[ name ] === undefined ) {
  17376. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17377. }
  17378. return materials[ name ];
  17379. }
  17380. function getTexture( uuid ) {
  17381. if ( textures[ uuid ] === undefined ) {
  17382. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17383. }
  17384. return textures[ uuid ];
  17385. }
  17386. let geometry, material;
  17387. switch ( data.type ) {
  17388. case 'Scene':
  17389. object = new Scene();
  17390. if ( data.background !== undefined ) {
  17391. if ( Number.isInteger( data.background ) ) {
  17392. object.background = new Color( data.background );
  17393. } else {
  17394. object.background = getTexture( data.background );
  17395. }
  17396. }
  17397. if ( data.environment !== undefined ) {
  17398. object.environment = getTexture( data.environment );
  17399. }
  17400. if ( data.fog !== undefined ) {
  17401. if ( data.fog.type === 'Fog' ) {
  17402. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17403. } else if ( data.fog.type === 'FogExp2' ) {
  17404. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17405. }
  17406. if ( data.fog.name !== '' ) {
  17407. object.fog.name = data.fog.name;
  17408. }
  17409. }
  17410. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17411. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17412. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17413. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17414. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17415. break;
  17416. case 'PerspectiveCamera':
  17417. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17418. if ( data.focus !== undefined ) object.focus = data.focus;
  17419. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17420. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17421. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17422. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17423. break;
  17424. case 'OrthographicCamera':
  17425. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17426. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17427. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17428. break;
  17429. case 'AmbientLight':
  17430. object = new AmbientLight( data.color, data.intensity );
  17431. break;
  17432. case 'DirectionalLight':
  17433. object = new DirectionalLight( data.color, data.intensity );
  17434. object.target = data.target || '';
  17435. break;
  17436. case 'PointLight':
  17437. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17438. break;
  17439. case 'RectAreaLight':
  17440. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17441. break;
  17442. case 'SpotLight':
  17443. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17444. object.target = data.target || '';
  17445. break;
  17446. case 'HemisphereLight':
  17447. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17448. break;
  17449. case 'LightProbe':
  17450. object = new LightProbe().fromJSON( data );
  17451. break;
  17452. case 'SkinnedMesh':
  17453. geometry = getGeometry( data.geometry );
  17454. material = getMaterial( data.material );
  17455. object = new SkinnedMesh( geometry, material );
  17456. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17457. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17458. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17459. break;
  17460. case 'Mesh':
  17461. geometry = getGeometry( data.geometry );
  17462. material = getMaterial( data.material );
  17463. object = new Mesh( geometry, material );
  17464. break;
  17465. case 'InstancedMesh':
  17466. geometry = getGeometry( data.geometry );
  17467. material = getMaterial( data.material );
  17468. const count = data.count;
  17469. const instanceMatrix = data.instanceMatrix;
  17470. const instanceColor = data.instanceColor;
  17471. object = new InstancedMesh( geometry, material, count );
  17472. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17473. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17474. break;
  17475. case 'BatchedMesh':
  17476. geometry = getGeometry( data.geometry );
  17477. material = getMaterial( data.material );
  17478. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17479. object.geometry = geometry;
  17480. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17481. object.sortObjects = data.sortObjects;
  17482. object._drawRanges = data.drawRanges;
  17483. object._reservedRanges = data.reservedRanges;
  17484. object._visibility = data.visibility;
  17485. object._active = data.active;
  17486. object._bounds = data.bounds.map( bound => {
  17487. const box = new Box3();
  17488. box.min.fromArray( bound.boxMin );
  17489. box.max.fromArray( bound.boxMax );
  17490. const sphere = new Sphere();
  17491. sphere.radius = bound.sphereRadius;
  17492. sphere.center.fromArray( bound.sphereCenter );
  17493. return {
  17494. boxInitialized: bound.boxInitialized,
  17495. box: box,
  17496. sphereInitialized: bound.sphereInitialized,
  17497. sphere: sphere
  17498. };
  17499. } );
  17500. object._maxInstanceCount = data.maxInstanceCount;
  17501. object._maxVertexCount = data.maxVertexCount;
  17502. object._maxIndexCount = data.maxIndexCount;
  17503. object._geometryInitialized = data.geometryInitialized;
  17504. object._geometryCount = data.geometryCount;
  17505. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17506. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17507. break;
  17508. case 'LOD':
  17509. object = new LOD();
  17510. break;
  17511. case 'Line':
  17512. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17513. break;
  17514. case 'LineLoop':
  17515. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17516. break;
  17517. case 'LineSegments':
  17518. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17519. break;
  17520. case 'PointCloud':
  17521. case 'Points':
  17522. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17523. break;
  17524. case 'Sprite':
  17525. object = new Sprite( getMaterial( data.material ) );
  17526. break;
  17527. case 'Group':
  17528. object = new Group();
  17529. break;
  17530. case 'Bone':
  17531. object = new Bone();
  17532. break;
  17533. default:
  17534. object = new Object3D();
  17535. }
  17536. object.uuid = data.uuid;
  17537. if ( data.name !== undefined ) object.name = data.name;
  17538. if ( data.matrix !== undefined ) {
  17539. object.matrix.fromArray( data.matrix );
  17540. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17541. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17542. } else {
  17543. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17544. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17545. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17546. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17547. }
  17548. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17549. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17550. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17551. if ( data.shadow ) {
  17552. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17553. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17554. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17555. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17556. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17557. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17558. }
  17559. if ( data.visible !== undefined ) object.visible = data.visible;
  17560. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17561. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17562. if ( data.userData !== undefined ) object.userData = data.userData;
  17563. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17564. if ( data.children !== undefined ) {
  17565. const children = data.children;
  17566. for ( let i = 0; i < children.length; i ++ ) {
  17567. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17568. }
  17569. }
  17570. if ( data.animations !== undefined ) {
  17571. const objectAnimations = data.animations;
  17572. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17573. const uuid = objectAnimations[ i ];
  17574. object.animations.push( animations[ uuid ] );
  17575. }
  17576. }
  17577. if ( data.type === 'LOD' ) {
  17578. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17579. const levels = data.levels;
  17580. for ( let l = 0; l < levels.length; l ++ ) {
  17581. const level = levels[ l ];
  17582. const child = object.getObjectByProperty( 'uuid', level.object );
  17583. if ( child !== undefined ) {
  17584. object.addLevel( child, level.distance, level.hysteresis );
  17585. }
  17586. }
  17587. }
  17588. return object;
  17589. }
  17590. bindSkeletons( object, skeletons ) {
  17591. if ( Object.keys( skeletons ).length === 0 ) return;
  17592. object.traverse( function ( child ) {
  17593. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17594. const skeleton = skeletons[ child.skeleton ];
  17595. if ( skeleton === undefined ) {
  17596. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17597. } else {
  17598. child.bind( skeleton, child.bindMatrix );
  17599. }
  17600. }
  17601. } );
  17602. }
  17603. bindLightTargets( object ) {
  17604. object.traverse( function ( child ) {
  17605. if ( child.isDirectionalLight || child.isSpotLight ) {
  17606. const uuid = child.target;
  17607. const target = object.getObjectByProperty( 'uuid', uuid );
  17608. if ( target !== undefined ) {
  17609. child.target = target;
  17610. } else {
  17611. child.target = new Object3D();
  17612. }
  17613. }
  17614. } );
  17615. }
  17616. }
  17617. const TEXTURE_MAPPING = {
  17618. UVMapping: UVMapping,
  17619. CubeReflectionMapping: CubeReflectionMapping,
  17620. CubeRefractionMapping: CubeRefractionMapping,
  17621. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17622. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17623. CubeUVReflectionMapping: CubeUVReflectionMapping
  17624. };
  17625. const TEXTURE_WRAPPING = {
  17626. RepeatWrapping: RepeatWrapping,
  17627. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17628. MirroredRepeatWrapping: MirroredRepeatWrapping
  17629. };
  17630. const TEXTURE_FILTER = {
  17631. NearestFilter: NearestFilter,
  17632. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17633. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17634. LinearFilter: LinearFilter,
  17635. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17636. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17637. };
  17638. class ImageBitmapLoader extends Loader {
  17639. constructor( manager ) {
  17640. super( manager );
  17641. this.isImageBitmapLoader = true;
  17642. if ( typeof createImageBitmap === 'undefined' ) {
  17643. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17644. }
  17645. if ( typeof fetch === 'undefined' ) {
  17646. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17647. }
  17648. this.options = { premultiplyAlpha: 'none' };
  17649. }
  17650. setOptions( options ) {
  17651. this.options = options;
  17652. return this;
  17653. }
  17654. load( url, onLoad, onProgress, onError ) {
  17655. if ( url === undefined ) url = '';
  17656. if ( this.path !== undefined ) url = this.path + url;
  17657. url = this.manager.resolveURL( url );
  17658. const scope = this;
  17659. const cached = Cache.get( url );
  17660. if ( cached !== undefined ) {
  17661. scope.manager.itemStart( url );
  17662. // If cached is a promise, wait for it to resolve
  17663. if ( cached.then ) {
  17664. cached.then( imageBitmap => {
  17665. if ( onLoad ) onLoad( imageBitmap );
  17666. scope.manager.itemEnd( url );
  17667. } ).catch( e => {
  17668. if ( onError ) onError( e );
  17669. } );
  17670. return;
  17671. }
  17672. // If cached is not a promise (i.e., it's already an imageBitmap)
  17673. setTimeout( function () {
  17674. if ( onLoad ) onLoad( cached );
  17675. scope.manager.itemEnd( url );
  17676. }, 0 );
  17677. return cached;
  17678. }
  17679. const fetchOptions = {};
  17680. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17681. fetchOptions.headers = this.requestHeader;
  17682. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17683. return res.blob();
  17684. } ).then( function ( blob ) {
  17685. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17686. } ).then( function ( imageBitmap ) {
  17687. Cache.add( url, imageBitmap );
  17688. if ( onLoad ) onLoad( imageBitmap );
  17689. scope.manager.itemEnd( url );
  17690. return imageBitmap;
  17691. } ).catch( function ( e ) {
  17692. if ( onError ) onError( e );
  17693. Cache.remove( url );
  17694. scope.manager.itemError( url );
  17695. scope.manager.itemEnd( url );
  17696. } );
  17697. Cache.add( url, promise );
  17698. scope.manager.itemStart( url );
  17699. }
  17700. }
  17701. let _context;
  17702. class AudioContext {
  17703. static getContext() {
  17704. if ( _context === undefined ) {
  17705. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17706. }
  17707. return _context;
  17708. }
  17709. static setContext( value ) {
  17710. _context = value;
  17711. }
  17712. }
  17713. class AudioLoader extends Loader {
  17714. constructor( manager ) {
  17715. super( manager );
  17716. }
  17717. load( url, onLoad, onProgress, onError ) {
  17718. const scope = this;
  17719. const loader = new FileLoader( this.manager );
  17720. loader.setResponseType( 'arraybuffer' );
  17721. loader.setPath( this.path );
  17722. loader.setRequestHeader( this.requestHeader );
  17723. loader.setWithCredentials( this.withCredentials );
  17724. loader.load( url, function ( buffer ) {
  17725. try {
  17726. // Create a copy of the buffer. The `decodeAudioData` method
  17727. // detaches the buffer when complete, preventing reuse.
  17728. const bufferCopy = buffer.slice( 0 );
  17729. const context = AudioContext.getContext();
  17730. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17731. onLoad( audioBuffer );
  17732. } ).catch( handleError );
  17733. } catch ( e ) {
  17734. handleError( e );
  17735. }
  17736. }, onProgress, onError );
  17737. function handleError( e ) {
  17738. if ( onError ) {
  17739. onError( e );
  17740. } else {
  17741. console.error( e );
  17742. }
  17743. scope.manager.itemError( url );
  17744. }
  17745. }
  17746. }
  17747. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17748. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17749. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17750. class StereoCamera {
  17751. constructor() {
  17752. this.type = 'StereoCamera';
  17753. this.aspect = 1;
  17754. this.eyeSep = 0.064;
  17755. this.cameraL = new PerspectiveCamera();
  17756. this.cameraL.layers.enable( 1 );
  17757. this.cameraL.matrixAutoUpdate = false;
  17758. this.cameraR = new PerspectiveCamera();
  17759. this.cameraR.layers.enable( 2 );
  17760. this.cameraR.matrixAutoUpdate = false;
  17761. this._cache = {
  17762. focus: null,
  17763. fov: null,
  17764. aspect: null,
  17765. near: null,
  17766. far: null,
  17767. zoom: null,
  17768. eyeSep: null
  17769. };
  17770. }
  17771. update( camera ) {
  17772. const cache = this._cache;
  17773. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17774. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17775. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17776. if ( needsUpdate ) {
  17777. cache.focus = camera.focus;
  17778. cache.fov = camera.fov;
  17779. cache.aspect = camera.aspect * this.aspect;
  17780. cache.near = camera.near;
  17781. cache.far = camera.far;
  17782. cache.zoom = camera.zoom;
  17783. cache.eyeSep = this.eyeSep;
  17784. // Off-axis stereoscopic effect based on
  17785. // http://paulbourke.net/stereographics/stereorender/
  17786. _projectionMatrix.copy( camera.projectionMatrix );
  17787. const eyeSepHalf = cache.eyeSep / 2;
  17788. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17789. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  17790. let xmin, xmax;
  17791. // translate xOffset
  17792. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  17793. _eyeRight.elements[ 12 ] = eyeSepHalf;
  17794. // for left eye
  17795. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  17796. xmax = ymax * cache.aspect + eyeSepOnProjection;
  17797. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17798. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17799. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  17800. // for right eye
  17801. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  17802. xmax = ymax * cache.aspect - eyeSepOnProjection;
  17803. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17804. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17805. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  17806. }
  17807. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  17808. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  17809. }
  17810. }
  17811. class ArrayCamera extends PerspectiveCamera {
  17812. constructor( array = [] ) {
  17813. super();
  17814. this.isArrayCamera = true;
  17815. this.cameras = array;
  17816. }
  17817. }
  17818. class Clock {
  17819. constructor( autoStart = true ) {
  17820. this.autoStart = autoStart;
  17821. this.startTime = 0;
  17822. this.oldTime = 0;
  17823. this.elapsedTime = 0;
  17824. this.running = false;
  17825. }
  17826. start() {
  17827. this.startTime = now();
  17828. this.oldTime = this.startTime;
  17829. this.elapsedTime = 0;
  17830. this.running = true;
  17831. }
  17832. stop() {
  17833. this.getElapsedTime();
  17834. this.running = false;
  17835. this.autoStart = false;
  17836. }
  17837. getElapsedTime() {
  17838. this.getDelta();
  17839. return this.elapsedTime;
  17840. }
  17841. getDelta() {
  17842. let diff = 0;
  17843. if ( this.autoStart && ! this.running ) {
  17844. this.start();
  17845. return 0;
  17846. }
  17847. if ( this.running ) {
  17848. const newTime = now();
  17849. diff = ( newTime - this.oldTime ) / 1000;
  17850. this.oldTime = newTime;
  17851. this.elapsedTime += diff;
  17852. }
  17853. return diff;
  17854. }
  17855. }
  17856. function now() {
  17857. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  17858. }
  17859. const _position$1 = /*@__PURE__*/ new Vector3();
  17860. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  17861. const _scale$1 = /*@__PURE__*/ new Vector3();
  17862. const _orientation$1 = /*@__PURE__*/ new Vector3();
  17863. class AudioListener extends Object3D {
  17864. constructor() {
  17865. super();
  17866. this.type = 'AudioListener';
  17867. this.context = AudioContext.getContext();
  17868. this.gain = this.context.createGain();
  17869. this.gain.connect( this.context.destination );
  17870. this.filter = null;
  17871. this.timeDelta = 0;
  17872. // private
  17873. this._clock = new Clock();
  17874. }
  17875. getInput() {
  17876. return this.gain;
  17877. }
  17878. removeFilter() {
  17879. if ( this.filter !== null ) {
  17880. this.gain.disconnect( this.filter );
  17881. this.filter.disconnect( this.context.destination );
  17882. this.gain.connect( this.context.destination );
  17883. this.filter = null;
  17884. }
  17885. return this;
  17886. }
  17887. getFilter() {
  17888. return this.filter;
  17889. }
  17890. setFilter( value ) {
  17891. if ( this.filter !== null ) {
  17892. this.gain.disconnect( this.filter );
  17893. this.filter.disconnect( this.context.destination );
  17894. } else {
  17895. this.gain.disconnect( this.context.destination );
  17896. }
  17897. this.filter = value;
  17898. this.gain.connect( this.filter );
  17899. this.filter.connect( this.context.destination );
  17900. return this;
  17901. }
  17902. getMasterVolume() {
  17903. return this.gain.gain.value;
  17904. }
  17905. setMasterVolume( value ) {
  17906. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  17907. return this;
  17908. }
  17909. updateMatrixWorld( force ) {
  17910. super.updateMatrixWorld( force );
  17911. const listener = this.context.listener;
  17912. const up = this.up;
  17913. this.timeDelta = this._clock.getDelta();
  17914. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  17915. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  17916. if ( listener.positionX ) {
  17917. // code path for Chrome (see #14393)
  17918. const endTime = this.context.currentTime + this.timeDelta;
  17919. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  17920. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  17921. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  17922. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  17923. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  17924. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  17925. listener.upX.linearRampToValueAtTime( up.x, endTime );
  17926. listener.upY.linearRampToValueAtTime( up.y, endTime );
  17927. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  17928. } else {
  17929. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  17930. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  17931. }
  17932. }
  17933. }
  17934. class Audio extends Object3D {
  17935. constructor( listener ) {
  17936. super();
  17937. this.type = 'Audio';
  17938. this.listener = listener;
  17939. this.context = listener.context;
  17940. this.gain = this.context.createGain();
  17941. this.gain.connect( listener.getInput() );
  17942. this.autoplay = false;
  17943. this.buffer = null;
  17944. this.detune = 0;
  17945. this.loop = false;
  17946. this.loopStart = 0;
  17947. this.loopEnd = 0;
  17948. this.offset = 0;
  17949. this.duration = undefined;
  17950. this.playbackRate = 1;
  17951. this.isPlaying = false;
  17952. this.hasPlaybackControl = true;
  17953. this.source = null;
  17954. this.sourceType = 'empty';
  17955. this._startedAt = 0;
  17956. this._progress = 0;
  17957. this._connected = false;
  17958. this.filters = [];
  17959. }
  17960. getOutput() {
  17961. return this.gain;
  17962. }
  17963. setNodeSource( audioNode ) {
  17964. this.hasPlaybackControl = false;
  17965. this.sourceType = 'audioNode';
  17966. this.source = audioNode;
  17967. this.connect();
  17968. return this;
  17969. }
  17970. setMediaElementSource( mediaElement ) {
  17971. this.hasPlaybackControl = false;
  17972. this.sourceType = 'mediaNode';
  17973. this.source = this.context.createMediaElementSource( mediaElement );
  17974. this.connect();
  17975. return this;
  17976. }
  17977. setMediaStreamSource( mediaStream ) {
  17978. this.hasPlaybackControl = false;
  17979. this.sourceType = 'mediaStreamNode';
  17980. this.source = this.context.createMediaStreamSource( mediaStream );
  17981. this.connect();
  17982. return this;
  17983. }
  17984. setBuffer( audioBuffer ) {
  17985. this.buffer = audioBuffer;
  17986. this.sourceType = 'buffer';
  17987. if ( this.autoplay ) this.play();
  17988. return this;
  17989. }
  17990. play( delay = 0 ) {
  17991. if ( this.isPlaying === true ) {
  17992. console.warn( 'THREE.Audio: Audio is already playing.' );
  17993. return;
  17994. }
  17995. if ( this.hasPlaybackControl === false ) {
  17996. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  17997. return;
  17998. }
  17999. this._startedAt = this.context.currentTime + delay;
  18000. const source = this.context.createBufferSource();
  18001. source.buffer = this.buffer;
  18002. source.loop = this.loop;
  18003. source.loopStart = this.loopStart;
  18004. source.loopEnd = this.loopEnd;
  18005. source.onended = this.onEnded.bind( this );
  18006. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18007. this.isPlaying = true;
  18008. this.source = source;
  18009. this.setDetune( this.detune );
  18010. this.setPlaybackRate( this.playbackRate );
  18011. return this.connect();
  18012. }
  18013. pause() {
  18014. if ( this.hasPlaybackControl === false ) {
  18015. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18016. return;
  18017. }
  18018. if ( this.isPlaying === true ) {
  18019. // update current progress
  18020. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18021. if ( this.loop === true ) {
  18022. // ensure _progress does not exceed duration with looped audios
  18023. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18024. }
  18025. this.source.stop();
  18026. this.source.onended = null;
  18027. this.isPlaying = false;
  18028. }
  18029. return this;
  18030. }
  18031. stop() {
  18032. if ( this.hasPlaybackControl === false ) {
  18033. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18034. return;
  18035. }
  18036. this._progress = 0;
  18037. if ( this.source !== null ) {
  18038. this.source.stop();
  18039. this.source.onended = null;
  18040. }
  18041. this.isPlaying = false;
  18042. return this;
  18043. }
  18044. connect() {
  18045. if ( this.filters.length > 0 ) {
  18046. this.source.connect( this.filters[ 0 ] );
  18047. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18048. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18049. }
  18050. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18051. } else {
  18052. this.source.connect( this.getOutput() );
  18053. }
  18054. this._connected = true;
  18055. return this;
  18056. }
  18057. disconnect() {
  18058. if ( this._connected === false ) {
  18059. return;
  18060. }
  18061. if ( this.filters.length > 0 ) {
  18062. this.source.disconnect( this.filters[ 0 ] );
  18063. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18064. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18065. }
  18066. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18067. } else {
  18068. this.source.disconnect( this.getOutput() );
  18069. }
  18070. this._connected = false;
  18071. return this;
  18072. }
  18073. getFilters() {
  18074. return this.filters;
  18075. }
  18076. setFilters( value ) {
  18077. if ( ! value ) value = [];
  18078. if ( this._connected === true ) {
  18079. this.disconnect();
  18080. this.filters = value.slice();
  18081. this.connect();
  18082. } else {
  18083. this.filters = value.slice();
  18084. }
  18085. return this;
  18086. }
  18087. setDetune( value ) {
  18088. this.detune = value;
  18089. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18090. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18091. }
  18092. return this;
  18093. }
  18094. getDetune() {
  18095. return this.detune;
  18096. }
  18097. getFilter() {
  18098. return this.getFilters()[ 0 ];
  18099. }
  18100. setFilter( filter ) {
  18101. return this.setFilters( filter ? [ filter ] : [] );
  18102. }
  18103. setPlaybackRate( value ) {
  18104. if ( this.hasPlaybackControl === false ) {
  18105. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18106. return;
  18107. }
  18108. this.playbackRate = value;
  18109. if ( this.isPlaying === true ) {
  18110. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18111. }
  18112. return this;
  18113. }
  18114. getPlaybackRate() {
  18115. return this.playbackRate;
  18116. }
  18117. onEnded() {
  18118. this.isPlaying = false;
  18119. }
  18120. getLoop() {
  18121. if ( this.hasPlaybackControl === false ) {
  18122. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18123. return false;
  18124. }
  18125. return this.loop;
  18126. }
  18127. setLoop( value ) {
  18128. if ( this.hasPlaybackControl === false ) {
  18129. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18130. return;
  18131. }
  18132. this.loop = value;
  18133. if ( this.isPlaying === true ) {
  18134. this.source.loop = this.loop;
  18135. }
  18136. return this;
  18137. }
  18138. setLoopStart( value ) {
  18139. this.loopStart = value;
  18140. return this;
  18141. }
  18142. setLoopEnd( value ) {
  18143. this.loopEnd = value;
  18144. return this;
  18145. }
  18146. getVolume() {
  18147. return this.gain.gain.value;
  18148. }
  18149. setVolume( value ) {
  18150. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18151. return this;
  18152. }
  18153. }
  18154. const _position = /*@__PURE__*/ new Vector3();
  18155. const _quaternion = /*@__PURE__*/ new Quaternion();
  18156. const _scale = /*@__PURE__*/ new Vector3();
  18157. const _orientation = /*@__PURE__*/ new Vector3();
  18158. class PositionalAudio extends Audio {
  18159. constructor( listener ) {
  18160. super( listener );
  18161. this.panner = this.context.createPanner();
  18162. this.panner.panningModel = 'HRTF';
  18163. this.panner.connect( this.gain );
  18164. }
  18165. connect() {
  18166. super.connect();
  18167. this.panner.connect( this.gain );
  18168. }
  18169. disconnect() {
  18170. super.disconnect();
  18171. this.panner.disconnect( this.gain );
  18172. }
  18173. getOutput() {
  18174. return this.panner;
  18175. }
  18176. getRefDistance() {
  18177. return this.panner.refDistance;
  18178. }
  18179. setRefDistance( value ) {
  18180. this.panner.refDistance = value;
  18181. return this;
  18182. }
  18183. getRolloffFactor() {
  18184. return this.panner.rolloffFactor;
  18185. }
  18186. setRolloffFactor( value ) {
  18187. this.panner.rolloffFactor = value;
  18188. return this;
  18189. }
  18190. getDistanceModel() {
  18191. return this.panner.distanceModel;
  18192. }
  18193. setDistanceModel( value ) {
  18194. this.panner.distanceModel = value;
  18195. return this;
  18196. }
  18197. getMaxDistance() {
  18198. return this.panner.maxDistance;
  18199. }
  18200. setMaxDistance( value ) {
  18201. this.panner.maxDistance = value;
  18202. return this;
  18203. }
  18204. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18205. this.panner.coneInnerAngle = coneInnerAngle;
  18206. this.panner.coneOuterAngle = coneOuterAngle;
  18207. this.panner.coneOuterGain = coneOuterGain;
  18208. return this;
  18209. }
  18210. updateMatrixWorld( force ) {
  18211. super.updateMatrixWorld( force );
  18212. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18213. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18214. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18215. const panner = this.panner;
  18216. if ( panner.positionX ) {
  18217. // code path for Chrome and Firefox (see #14393)
  18218. const endTime = this.context.currentTime + this.listener.timeDelta;
  18219. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18220. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18221. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18222. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18223. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18224. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18225. } else {
  18226. panner.setPosition( _position.x, _position.y, _position.z );
  18227. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18228. }
  18229. }
  18230. }
  18231. class AudioAnalyser {
  18232. constructor( audio, fftSize = 2048 ) {
  18233. this.analyser = audio.context.createAnalyser();
  18234. this.analyser.fftSize = fftSize;
  18235. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18236. audio.getOutput().connect( this.analyser );
  18237. }
  18238. getFrequencyData() {
  18239. this.analyser.getByteFrequencyData( this.data );
  18240. return this.data;
  18241. }
  18242. getAverageFrequency() {
  18243. let value = 0;
  18244. const data = this.getFrequencyData();
  18245. for ( let i = 0; i < data.length; i ++ ) {
  18246. value += data[ i ];
  18247. }
  18248. return value / data.length;
  18249. }
  18250. }
  18251. class PropertyMixer {
  18252. constructor( binding, typeName, valueSize ) {
  18253. this.binding = binding;
  18254. this.valueSize = valueSize;
  18255. let mixFunction,
  18256. mixFunctionAdditive,
  18257. setIdentity;
  18258. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18259. //
  18260. // interpolators can use .buffer as their .result
  18261. // the data then goes to 'incoming'
  18262. //
  18263. // 'accu0' and 'accu1' are used frame-interleaved for
  18264. // the cumulative result and are compared to detect
  18265. // changes
  18266. //
  18267. // 'orig' stores the original state of the property
  18268. //
  18269. // 'add' is used for additive cumulative results
  18270. //
  18271. // 'work' is optional and is only present for quaternion types. It is used
  18272. // to store intermediate quaternion multiplication results
  18273. switch ( typeName ) {
  18274. case 'quaternion':
  18275. mixFunction = this._slerp;
  18276. mixFunctionAdditive = this._slerpAdditive;
  18277. setIdentity = this._setAdditiveIdentityQuaternion;
  18278. this.buffer = new Float64Array( valueSize * 6 );
  18279. this._workIndex = 5;
  18280. break;
  18281. case 'string':
  18282. case 'bool':
  18283. mixFunction = this._select;
  18284. // Use the regular mix function and for additive on these types,
  18285. // additive is not relevant for non-numeric types
  18286. mixFunctionAdditive = this._select;
  18287. setIdentity = this._setAdditiveIdentityOther;
  18288. this.buffer = new Array( valueSize * 5 );
  18289. break;
  18290. default:
  18291. mixFunction = this._lerp;
  18292. mixFunctionAdditive = this._lerpAdditive;
  18293. setIdentity = this._setAdditiveIdentityNumeric;
  18294. this.buffer = new Float64Array( valueSize * 5 );
  18295. }
  18296. this._mixBufferRegion = mixFunction;
  18297. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18298. this._setIdentity = setIdentity;
  18299. this._origIndex = 3;
  18300. this._addIndex = 4;
  18301. this.cumulativeWeight = 0;
  18302. this.cumulativeWeightAdditive = 0;
  18303. this.useCount = 0;
  18304. this.referenceCount = 0;
  18305. }
  18306. // accumulate data in the 'incoming' region into 'accu<i>'
  18307. accumulate( accuIndex, weight ) {
  18308. // note: happily accumulating nothing when weight = 0, the caller knows
  18309. // the weight and shouldn't have made the call in the first place
  18310. const buffer = this.buffer,
  18311. stride = this.valueSize,
  18312. offset = accuIndex * stride + stride;
  18313. let currentWeight = this.cumulativeWeight;
  18314. if ( currentWeight === 0 ) {
  18315. // accuN := incoming * weight
  18316. for ( let i = 0; i !== stride; ++ i ) {
  18317. buffer[ offset + i ] = buffer[ i ];
  18318. }
  18319. currentWeight = weight;
  18320. } else {
  18321. // accuN := accuN + incoming * weight
  18322. currentWeight += weight;
  18323. const mix = weight / currentWeight;
  18324. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18325. }
  18326. this.cumulativeWeight = currentWeight;
  18327. }
  18328. // accumulate data in the 'incoming' region into 'add'
  18329. accumulateAdditive( weight ) {
  18330. const buffer = this.buffer,
  18331. stride = this.valueSize,
  18332. offset = stride * this._addIndex;
  18333. if ( this.cumulativeWeightAdditive === 0 ) {
  18334. // add = identity
  18335. this._setIdentity();
  18336. }
  18337. // add := add + incoming * weight
  18338. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18339. this.cumulativeWeightAdditive += weight;
  18340. }
  18341. // apply the state of 'accu<i>' to the binding when accus differ
  18342. apply( accuIndex ) {
  18343. const stride = this.valueSize,
  18344. buffer = this.buffer,
  18345. offset = accuIndex * stride + stride,
  18346. weight = this.cumulativeWeight,
  18347. weightAdditive = this.cumulativeWeightAdditive,
  18348. binding = this.binding;
  18349. this.cumulativeWeight = 0;
  18350. this.cumulativeWeightAdditive = 0;
  18351. if ( weight < 1 ) {
  18352. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18353. const originalValueOffset = stride * this._origIndex;
  18354. this._mixBufferRegion(
  18355. buffer, offset, originalValueOffset, 1 - weight, stride );
  18356. }
  18357. if ( weightAdditive > 0 ) {
  18358. // accuN := accuN + additive accuN
  18359. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18360. }
  18361. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18362. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18363. // value has changed -> update scene graph
  18364. binding.setValue( buffer, offset );
  18365. break;
  18366. }
  18367. }
  18368. }
  18369. // remember the state of the bound property and copy it to both accus
  18370. saveOriginalState() {
  18371. const binding = this.binding;
  18372. const buffer = this.buffer,
  18373. stride = this.valueSize,
  18374. originalValueOffset = stride * this._origIndex;
  18375. binding.getValue( buffer, originalValueOffset );
  18376. // accu[0..1] := orig -- initially detect changes against the original
  18377. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18378. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18379. }
  18380. // Add to identity for additive
  18381. this._setIdentity();
  18382. this.cumulativeWeight = 0;
  18383. this.cumulativeWeightAdditive = 0;
  18384. }
  18385. // apply the state previously taken via 'saveOriginalState' to the binding
  18386. restoreOriginalState() {
  18387. const originalValueOffset = this.valueSize * 3;
  18388. this.binding.setValue( this.buffer, originalValueOffset );
  18389. }
  18390. _setAdditiveIdentityNumeric() {
  18391. const startIndex = this._addIndex * this.valueSize;
  18392. const endIndex = startIndex + this.valueSize;
  18393. for ( let i = startIndex; i < endIndex; i ++ ) {
  18394. this.buffer[ i ] = 0;
  18395. }
  18396. }
  18397. _setAdditiveIdentityQuaternion() {
  18398. this._setAdditiveIdentityNumeric();
  18399. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18400. }
  18401. _setAdditiveIdentityOther() {
  18402. const startIndex = this._origIndex * this.valueSize;
  18403. const targetIndex = this._addIndex * this.valueSize;
  18404. for ( let i = 0; i < this.valueSize; i ++ ) {
  18405. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18406. }
  18407. }
  18408. // mix functions
  18409. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18410. if ( t >= 0.5 ) {
  18411. for ( let i = 0; i !== stride; ++ i ) {
  18412. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18413. }
  18414. }
  18415. }
  18416. _slerp( buffer, dstOffset, srcOffset, t ) {
  18417. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18418. }
  18419. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18420. const workOffset = this._workIndex * stride;
  18421. // Store result in intermediate buffer offset
  18422. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18423. // Slerp to the intermediate result
  18424. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18425. }
  18426. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18427. const s = 1 - t;
  18428. for ( let i = 0; i !== stride; ++ i ) {
  18429. const j = dstOffset + i;
  18430. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18431. }
  18432. }
  18433. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18434. for ( let i = 0; i !== stride; ++ i ) {
  18435. const j = dstOffset + i;
  18436. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18437. }
  18438. }
  18439. }
  18440. // Characters [].:/ are reserved for track binding syntax.
  18441. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18442. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18443. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18444. // only latin characters, and the unicode \p{L} is not yet supported. So
  18445. // instead, we exclude reserved characters and match everything else.
  18446. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18447. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18448. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18449. // be matched to parse the rest of the track name.
  18450. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18451. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18452. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18453. // Object on target node, and accessor. May not contain reserved
  18454. // characters. Accessor may contain any character except closing bracket.
  18455. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18456. // Property and accessor. May not contain reserved characters. Accessor may
  18457. // contain any non-bracket characters.
  18458. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18459. const _trackRe = new RegExp( ''
  18460. + '^'
  18461. + _directoryRe
  18462. + _nodeRe
  18463. + _objectRe
  18464. + _propertyRe
  18465. + '$'
  18466. );
  18467. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18468. class Composite {
  18469. constructor( targetGroup, path, optionalParsedPath ) {
  18470. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18471. this._targetGroup = targetGroup;
  18472. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18473. }
  18474. getValue( array, offset ) {
  18475. this.bind(); // bind all binding
  18476. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18477. binding = this._bindings[ firstValidIndex ];
  18478. // and only call .getValue on the first
  18479. if ( binding !== undefined ) binding.getValue( array, offset );
  18480. }
  18481. setValue( array, offset ) {
  18482. const bindings = this._bindings;
  18483. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18484. bindings[ i ].setValue( array, offset );
  18485. }
  18486. }
  18487. bind() {
  18488. const bindings = this._bindings;
  18489. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18490. bindings[ i ].bind();
  18491. }
  18492. }
  18493. unbind() {
  18494. const bindings = this._bindings;
  18495. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18496. bindings[ i ].unbind();
  18497. }
  18498. }
  18499. }
  18500. // Note: This class uses a State pattern on a per-method basis:
  18501. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18502. // prototype version of these methods with one that represents
  18503. // the bound state. When the property is not found, the methods
  18504. // become no-ops.
  18505. class PropertyBinding {
  18506. constructor( rootNode, path, parsedPath ) {
  18507. this.path = path;
  18508. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18509. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18510. this.rootNode = rootNode;
  18511. // initial state of these methods that calls 'bind'
  18512. this.getValue = this._getValue_unbound;
  18513. this.setValue = this._setValue_unbound;
  18514. }
  18515. static create( root, path, parsedPath ) {
  18516. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18517. return new PropertyBinding( root, path, parsedPath );
  18518. } else {
  18519. return new PropertyBinding.Composite( root, path, parsedPath );
  18520. }
  18521. }
  18522. /**
  18523. * Replaces spaces with underscores and removes unsupported characters from
  18524. * node names, to ensure compatibility with parseTrackName().
  18525. *
  18526. * @param {string} name Node name to be sanitized.
  18527. * @return {string}
  18528. */
  18529. static sanitizeNodeName( name ) {
  18530. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18531. }
  18532. static parseTrackName( trackName ) {
  18533. const matches = _trackRe.exec( trackName );
  18534. if ( matches === null ) {
  18535. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18536. }
  18537. const results = {
  18538. // directoryName: matches[ 1 ], // (tschw) currently unused
  18539. nodeName: matches[ 2 ],
  18540. objectName: matches[ 3 ],
  18541. objectIndex: matches[ 4 ],
  18542. propertyName: matches[ 5 ], // required
  18543. propertyIndex: matches[ 6 ]
  18544. };
  18545. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18546. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18547. const objectName = results.nodeName.substring( lastDot + 1 );
  18548. // Object names must be checked against an allowlist. Otherwise, there
  18549. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18550. // 'bar' could be the objectName, or part of a nodeName (which can
  18551. // include '.' characters).
  18552. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18553. results.nodeName = results.nodeName.substring( 0, lastDot );
  18554. results.objectName = objectName;
  18555. }
  18556. }
  18557. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18558. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18559. }
  18560. return results;
  18561. }
  18562. static findNode( root, nodeName ) {
  18563. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18564. return root;
  18565. }
  18566. // search into skeleton bones.
  18567. if ( root.skeleton ) {
  18568. const bone = root.skeleton.getBoneByName( nodeName );
  18569. if ( bone !== undefined ) {
  18570. return bone;
  18571. }
  18572. }
  18573. // search into node subtree.
  18574. if ( root.children ) {
  18575. const searchNodeSubtree = function ( children ) {
  18576. for ( let i = 0; i < children.length; i ++ ) {
  18577. const childNode = children[ i ];
  18578. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18579. return childNode;
  18580. }
  18581. const result = searchNodeSubtree( childNode.children );
  18582. if ( result ) return result;
  18583. }
  18584. return null;
  18585. };
  18586. const subTreeNode = searchNodeSubtree( root.children );
  18587. if ( subTreeNode ) {
  18588. return subTreeNode;
  18589. }
  18590. }
  18591. return null;
  18592. }
  18593. // these are used to "bind" a nonexistent property
  18594. _getValue_unavailable() {}
  18595. _setValue_unavailable() {}
  18596. // Getters
  18597. _getValue_direct( buffer, offset ) {
  18598. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18599. }
  18600. _getValue_array( buffer, offset ) {
  18601. const source = this.resolvedProperty;
  18602. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18603. buffer[ offset ++ ] = source[ i ];
  18604. }
  18605. }
  18606. _getValue_arrayElement( buffer, offset ) {
  18607. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18608. }
  18609. _getValue_toArray( buffer, offset ) {
  18610. this.resolvedProperty.toArray( buffer, offset );
  18611. }
  18612. // Direct
  18613. _setValue_direct( buffer, offset ) {
  18614. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18615. }
  18616. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18617. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18618. this.targetObject.needsUpdate = true;
  18619. }
  18620. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18621. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18622. this.targetObject.matrixWorldNeedsUpdate = true;
  18623. }
  18624. // EntireArray
  18625. _setValue_array( buffer, offset ) {
  18626. const dest = this.resolvedProperty;
  18627. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18628. dest[ i ] = buffer[ offset ++ ];
  18629. }
  18630. }
  18631. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18632. const dest = this.resolvedProperty;
  18633. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18634. dest[ i ] = buffer[ offset ++ ];
  18635. }
  18636. this.targetObject.needsUpdate = true;
  18637. }
  18638. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18639. const dest = this.resolvedProperty;
  18640. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18641. dest[ i ] = buffer[ offset ++ ];
  18642. }
  18643. this.targetObject.matrixWorldNeedsUpdate = true;
  18644. }
  18645. // ArrayElement
  18646. _setValue_arrayElement( buffer, offset ) {
  18647. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18648. }
  18649. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18650. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18651. this.targetObject.needsUpdate = true;
  18652. }
  18653. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18654. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18655. this.targetObject.matrixWorldNeedsUpdate = true;
  18656. }
  18657. // HasToFromArray
  18658. _setValue_fromArray( buffer, offset ) {
  18659. this.resolvedProperty.fromArray( buffer, offset );
  18660. }
  18661. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18662. this.resolvedProperty.fromArray( buffer, offset );
  18663. this.targetObject.needsUpdate = true;
  18664. }
  18665. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18666. this.resolvedProperty.fromArray( buffer, offset );
  18667. this.targetObject.matrixWorldNeedsUpdate = true;
  18668. }
  18669. _getValue_unbound( targetArray, offset ) {
  18670. this.bind();
  18671. this.getValue( targetArray, offset );
  18672. }
  18673. _setValue_unbound( sourceArray, offset ) {
  18674. this.bind();
  18675. this.setValue( sourceArray, offset );
  18676. }
  18677. // create getter / setter pair for a property in the scene graph
  18678. bind() {
  18679. let targetObject = this.node;
  18680. const parsedPath = this.parsedPath;
  18681. const objectName = parsedPath.objectName;
  18682. const propertyName = parsedPath.propertyName;
  18683. let propertyIndex = parsedPath.propertyIndex;
  18684. if ( ! targetObject ) {
  18685. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18686. this.node = targetObject;
  18687. }
  18688. // set fail state so we can just 'return' on error
  18689. this.getValue = this._getValue_unavailable;
  18690. this.setValue = this._setValue_unavailable;
  18691. // ensure there is a value node
  18692. if ( ! targetObject ) {
  18693. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18694. return;
  18695. }
  18696. if ( objectName ) {
  18697. let objectIndex = parsedPath.objectIndex;
  18698. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18699. switch ( objectName ) {
  18700. case 'materials':
  18701. if ( ! targetObject.material ) {
  18702. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18703. return;
  18704. }
  18705. if ( ! targetObject.material.materials ) {
  18706. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18707. return;
  18708. }
  18709. targetObject = targetObject.material.materials;
  18710. break;
  18711. case 'bones':
  18712. if ( ! targetObject.skeleton ) {
  18713. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18714. return;
  18715. }
  18716. // potential future optimization: skip this if propertyIndex is already an integer
  18717. // and convert the integer string to a true integer.
  18718. targetObject = targetObject.skeleton.bones;
  18719. // support resolving morphTarget names into indices.
  18720. for ( let i = 0; i < targetObject.length; i ++ ) {
  18721. if ( targetObject[ i ].name === objectIndex ) {
  18722. objectIndex = i;
  18723. break;
  18724. }
  18725. }
  18726. break;
  18727. case 'map':
  18728. if ( 'map' in targetObject ) {
  18729. targetObject = targetObject.map;
  18730. break;
  18731. }
  18732. if ( ! targetObject.material ) {
  18733. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18734. return;
  18735. }
  18736. if ( ! targetObject.material.map ) {
  18737. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18738. return;
  18739. }
  18740. targetObject = targetObject.material.map;
  18741. break;
  18742. default:
  18743. if ( targetObject[ objectName ] === undefined ) {
  18744. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18745. return;
  18746. }
  18747. targetObject = targetObject[ objectName ];
  18748. }
  18749. if ( objectIndex !== undefined ) {
  18750. if ( targetObject[ objectIndex ] === undefined ) {
  18751. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18752. return;
  18753. }
  18754. targetObject = targetObject[ objectIndex ];
  18755. }
  18756. }
  18757. // resolve property
  18758. const nodeProperty = targetObject[ propertyName ];
  18759. if ( nodeProperty === undefined ) {
  18760. const nodeName = parsedPath.nodeName;
  18761. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18762. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18763. return;
  18764. }
  18765. // determine versioning scheme
  18766. let versioning = this.Versioning.None;
  18767. this.targetObject = targetObject;
  18768. if ( targetObject.needsUpdate !== undefined ) { // material
  18769. versioning = this.Versioning.NeedsUpdate;
  18770. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18771. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18772. }
  18773. // determine how the property gets bound
  18774. let bindingType = this.BindingType.Direct;
  18775. if ( propertyIndex !== undefined ) {
  18776. // access a sub element of the property array (only primitives are supported right now)
  18777. if ( propertyName === 'morphTargetInfluences' ) {
  18778. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18779. // support resolving morphTarget names into indices.
  18780. if ( ! targetObject.geometry ) {
  18781. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18782. return;
  18783. }
  18784. if ( ! targetObject.geometry.morphAttributes ) {
  18785. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18786. return;
  18787. }
  18788. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18789. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  18790. }
  18791. }
  18792. bindingType = this.BindingType.ArrayElement;
  18793. this.resolvedProperty = nodeProperty;
  18794. this.propertyIndex = propertyIndex;
  18795. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  18796. // must use copy for Object3D.Euler/Quaternion
  18797. bindingType = this.BindingType.HasFromToArray;
  18798. this.resolvedProperty = nodeProperty;
  18799. } else if ( Array.isArray( nodeProperty ) ) {
  18800. bindingType = this.BindingType.EntireArray;
  18801. this.resolvedProperty = nodeProperty;
  18802. } else {
  18803. this.propertyName = propertyName;
  18804. }
  18805. // select getter / setter
  18806. this.getValue = this.GetterByBindingType[ bindingType ];
  18807. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  18808. }
  18809. unbind() {
  18810. this.node = null;
  18811. // back to the prototype version of getValue / setValue
  18812. // note: avoiding to mutate the shape of 'this' via 'delete'
  18813. this.getValue = this._getValue_unbound;
  18814. this.setValue = this._setValue_unbound;
  18815. }
  18816. }
  18817. PropertyBinding.Composite = Composite;
  18818. PropertyBinding.prototype.BindingType = {
  18819. Direct: 0,
  18820. EntireArray: 1,
  18821. ArrayElement: 2,
  18822. HasFromToArray: 3
  18823. };
  18824. PropertyBinding.prototype.Versioning = {
  18825. None: 0,
  18826. NeedsUpdate: 1,
  18827. MatrixWorldNeedsUpdate: 2
  18828. };
  18829. PropertyBinding.prototype.GetterByBindingType = [
  18830. PropertyBinding.prototype._getValue_direct,
  18831. PropertyBinding.prototype._getValue_array,
  18832. PropertyBinding.prototype._getValue_arrayElement,
  18833. PropertyBinding.prototype._getValue_toArray,
  18834. ];
  18835. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  18836. [
  18837. // Direct
  18838. PropertyBinding.prototype._setValue_direct,
  18839. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  18840. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  18841. ], [
  18842. // EntireArray
  18843. PropertyBinding.prototype._setValue_array,
  18844. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  18845. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  18846. ], [
  18847. // ArrayElement
  18848. PropertyBinding.prototype._setValue_arrayElement,
  18849. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  18850. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  18851. ], [
  18852. // HasToFromArray
  18853. PropertyBinding.prototype._setValue_fromArray,
  18854. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  18855. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  18856. ]
  18857. ];
  18858. /**
  18859. *
  18860. * A group of objects that receives a shared animation state.
  18861. *
  18862. * Usage:
  18863. *
  18864. * - Add objects you would otherwise pass as 'root' to the
  18865. * constructor or the .clipAction method of AnimationMixer.
  18866. *
  18867. * - Instead pass this object as 'root'.
  18868. *
  18869. * - You can also add and remove objects later when the mixer
  18870. * is running.
  18871. *
  18872. * Note:
  18873. *
  18874. * Objects of this class appear as one object to the mixer,
  18875. * so cache control of the individual objects must be done
  18876. * on the group.
  18877. *
  18878. * Limitation:
  18879. *
  18880. * - The animated properties must be compatible among the
  18881. * all objects in the group.
  18882. *
  18883. * - A single property can either be controlled through a
  18884. * target group or directly, but not both.
  18885. */
  18886. class AnimationObjectGroup {
  18887. constructor() {
  18888. this.isAnimationObjectGroup = true;
  18889. this.uuid = generateUUID();
  18890. // cached objects followed by the active ones
  18891. this._objects = Array.prototype.slice.call( arguments );
  18892. this.nCachedObjects_ = 0; // threshold
  18893. // note: read by PropertyBinding.Composite
  18894. const indices = {};
  18895. this._indicesByUUID = indices; // for bookkeeping
  18896. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18897. indices[ arguments[ i ].uuid ] = i;
  18898. }
  18899. this._paths = []; // inside: string
  18900. this._parsedPaths = []; // inside: { we don't care, here }
  18901. this._bindings = []; // inside: Array< PropertyBinding >
  18902. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  18903. const scope = this;
  18904. this.stats = {
  18905. objects: {
  18906. get total() {
  18907. return scope._objects.length;
  18908. },
  18909. get inUse() {
  18910. return this.total - scope.nCachedObjects_;
  18911. }
  18912. },
  18913. get bindingsPerObject() {
  18914. return scope._bindings.length;
  18915. }
  18916. };
  18917. }
  18918. add() {
  18919. const objects = this._objects,
  18920. indicesByUUID = this._indicesByUUID,
  18921. paths = this._paths,
  18922. parsedPaths = this._parsedPaths,
  18923. bindings = this._bindings,
  18924. nBindings = bindings.length;
  18925. let knownObject = undefined,
  18926. nObjects = objects.length,
  18927. nCachedObjects = this.nCachedObjects_;
  18928. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18929. const object = arguments[ i ],
  18930. uuid = object.uuid;
  18931. let index = indicesByUUID[ uuid ];
  18932. if ( index === undefined ) {
  18933. // unknown object -> add it to the ACTIVE region
  18934. index = nObjects ++;
  18935. indicesByUUID[ uuid ] = index;
  18936. objects.push( object );
  18937. // accounting is done, now do the same for all bindings
  18938. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18939. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  18940. }
  18941. } else if ( index < nCachedObjects ) {
  18942. knownObject = objects[ index ];
  18943. // move existing object to the ACTIVE region
  18944. const firstActiveIndex = -- nCachedObjects,
  18945. lastCachedObject = objects[ firstActiveIndex ];
  18946. indicesByUUID[ lastCachedObject.uuid ] = index;
  18947. objects[ index ] = lastCachedObject;
  18948. indicesByUUID[ uuid ] = firstActiveIndex;
  18949. objects[ firstActiveIndex ] = object;
  18950. // accounting is done, now do the same for all bindings
  18951. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18952. const bindingsForPath = bindings[ j ],
  18953. lastCached = bindingsForPath[ firstActiveIndex ];
  18954. let binding = bindingsForPath[ index ];
  18955. bindingsForPath[ index ] = lastCached;
  18956. if ( binding === undefined ) {
  18957. // since we do not bother to create new bindings
  18958. // for objects that are cached, the binding may
  18959. // or may not exist
  18960. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  18961. }
  18962. bindingsForPath[ firstActiveIndex ] = binding;
  18963. }
  18964. } else if ( objects[ index ] !== knownObject ) {
  18965. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  18966. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  18967. } // else the object is already where we want it to be
  18968. } // for arguments
  18969. this.nCachedObjects_ = nCachedObjects;
  18970. }
  18971. remove() {
  18972. const objects = this._objects,
  18973. indicesByUUID = this._indicesByUUID,
  18974. bindings = this._bindings,
  18975. nBindings = bindings.length;
  18976. let nCachedObjects = this.nCachedObjects_;
  18977. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18978. const object = arguments[ i ],
  18979. uuid = object.uuid,
  18980. index = indicesByUUID[ uuid ];
  18981. if ( index !== undefined && index >= nCachedObjects ) {
  18982. // move existing object into the CACHED region
  18983. const lastCachedIndex = nCachedObjects ++,
  18984. firstActiveObject = objects[ lastCachedIndex ];
  18985. indicesByUUID[ firstActiveObject.uuid ] = index;
  18986. objects[ index ] = firstActiveObject;
  18987. indicesByUUID[ uuid ] = lastCachedIndex;
  18988. objects[ lastCachedIndex ] = object;
  18989. // accounting is done, now do the same for all bindings
  18990. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18991. const bindingsForPath = bindings[ j ],
  18992. firstActive = bindingsForPath[ lastCachedIndex ],
  18993. binding = bindingsForPath[ index ];
  18994. bindingsForPath[ index ] = firstActive;
  18995. bindingsForPath[ lastCachedIndex ] = binding;
  18996. }
  18997. }
  18998. } // for arguments
  18999. this.nCachedObjects_ = nCachedObjects;
  19000. }
  19001. // remove & forget
  19002. uncache() {
  19003. const objects = this._objects,
  19004. indicesByUUID = this._indicesByUUID,
  19005. bindings = this._bindings,
  19006. nBindings = bindings.length;
  19007. let nCachedObjects = this.nCachedObjects_,
  19008. nObjects = objects.length;
  19009. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19010. const object = arguments[ i ],
  19011. uuid = object.uuid,
  19012. index = indicesByUUID[ uuid ];
  19013. if ( index !== undefined ) {
  19014. delete indicesByUUID[ uuid ];
  19015. if ( index < nCachedObjects ) {
  19016. // object is cached, shrink the CACHED region
  19017. const firstActiveIndex = -- nCachedObjects,
  19018. lastCachedObject = objects[ firstActiveIndex ],
  19019. lastIndex = -- nObjects,
  19020. lastObject = objects[ lastIndex ];
  19021. // last cached object takes this object's place
  19022. indicesByUUID[ lastCachedObject.uuid ] = index;
  19023. objects[ index ] = lastCachedObject;
  19024. // last object goes to the activated slot and pop
  19025. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19026. objects[ firstActiveIndex ] = lastObject;
  19027. objects.pop();
  19028. // accounting is done, now do the same for all bindings
  19029. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19030. const bindingsForPath = bindings[ j ],
  19031. lastCached = bindingsForPath[ firstActiveIndex ],
  19032. last = bindingsForPath[ lastIndex ];
  19033. bindingsForPath[ index ] = lastCached;
  19034. bindingsForPath[ firstActiveIndex ] = last;
  19035. bindingsForPath.pop();
  19036. }
  19037. } else {
  19038. // object is active, just swap with the last and pop
  19039. const lastIndex = -- nObjects,
  19040. lastObject = objects[ lastIndex ];
  19041. if ( lastIndex > 0 ) {
  19042. indicesByUUID[ lastObject.uuid ] = index;
  19043. }
  19044. objects[ index ] = lastObject;
  19045. objects.pop();
  19046. // accounting is done, now do the same for all bindings
  19047. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19048. const bindingsForPath = bindings[ j ];
  19049. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19050. bindingsForPath.pop();
  19051. }
  19052. } // cached or active
  19053. } // if object is known
  19054. } // for arguments
  19055. this.nCachedObjects_ = nCachedObjects;
  19056. }
  19057. // Internal interface used by befriended PropertyBinding.Composite:
  19058. subscribe_( path, parsedPath ) {
  19059. // returns an array of bindings for the given path that is changed
  19060. // according to the contained objects in the group
  19061. const indicesByPath = this._bindingsIndicesByPath;
  19062. let index = indicesByPath[ path ];
  19063. const bindings = this._bindings;
  19064. if ( index !== undefined ) return bindings[ index ];
  19065. const paths = this._paths,
  19066. parsedPaths = this._parsedPaths,
  19067. objects = this._objects,
  19068. nObjects = objects.length,
  19069. nCachedObjects = this.nCachedObjects_,
  19070. bindingsForPath = new Array( nObjects );
  19071. index = bindings.length;
  19072. indicesByPath[ path ] = index;
  19073. paths.push( path );
  19074. parsedPaths.push( parsedPath );
  19075. bindings.push( bindingsForPath );
  19076. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19077. const object = objects[ i ];
  19078. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19079. }
  19080. return bindingsForPath;
  19081. }
  19082. unsubscribe_( path ) {
  19083. // tells the group to forget about a property path and no longer
  19084. // update the array previously obtained with 'subscribe_'
  19085. const indicesByPath = this._bindingsIndicesByPath,
  19086. index = indicesByPath[ path ];
  19087. if ( index !== undefined ) {
  19088. const paths = this._paths,
  19089. parsedPaths = this._parsedPaths,
  19090. bindings = this._bindings,
  19091. lastBindingsIndex = bindings.length - 1,
  19092. lastBindings = bindings[ lastBindingsIndex ],
  19093. lastBindingsPath = path[ lastBindingsIndex ];
  19094. indicesByPath[ lastBindingsPath ] = index;
  19095. bindings[ index ] = lastBindings;
  19096. bindings.pop();
  19097. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19098. parsedPaths.pop();
  19099. paths[ index ] = paths[ lastBindingsIndex ];
  19100. paths.pop();
  19101. }
  19102. }
  19103. }
  19104. class AnimationAction {
  19105. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19106. this._mixer = mixer;
  19107. this._clip = clip;
  19108. this._localRoot = localRoot;
  19109. this.blendMode = blendMode;
  19110. const tracks = clip.tracks,
  19111. nTracks = tracks.length,
  19112. interpolants = new Array( nTracks );
  19113. const interpolantSettings = {
  19114. endingStart: ZeroCurvatureEnding,
  19115. endingEnd: ZeroCurvatureEnding
  19116. };
  19117. for ( let i = 0; i !== nTracks; ++ i ) {
  19118. const interpolant = tracks[ i ].createInterpolant( null );
  19119. interpolants[ i ] = interpolant;
  19120. interpolant.settings = interpolantSettings;
  19121. }
  19122. this._interpolantSettings = interpolantSettings;
  19123. this._interpolants = interpolants; // bound by the mixer
  19124. // inside: PropertyMixer (managed by the mixer)
  19125. this._propertyBindings = new Array( nTracks );
  19126. this._cacheIndex = null; // for the memory manager
  19127. this._byClipCacheIndex = null; // for the memory manager
  19128. this._timeScaleInterpolant = null;
  19129. this._weightInterpolant = null;
  19130. this.loop = LoopRepeat;
  19131. this._loopCount = - 1;
  19132. // global mixer time when the action is to be started
  19133. // it's set back to 'null' upon start of the action
  19134. this._startTime = null;
  19135. // scaled local time of the action
  19136. // gets clamped or wrapped to 0..clip.duration according to loop
  19137. this.time = 0;
  19138. this.timeScale = 1;
  19139. this._effectiveTimeScale = 1;
  19140. this.weight = 1;
  19141. this._effectiveWeight = 1;
  19142. this.repetitions = Infinity; // no. of repetitions when looping
  19143. this.paused = false; // true -> zero effective time scale
  19144. this.enabled = true; // false -> zero effective weight
  19145. this.clampWhenFinished = false;// keep feeding the last frame?
  19146. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19147. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19148. }
  19149. // State & Scheduling
  19150. play() {
  19151. this._mixer._activateAction( this );
  19152. return this;
  19153. }
  19154. stop() {
  19155. this._mixer._deactivateAction( this );
  19156. return this.reset();
  19157. }
  19158. reset() {
  19159. this.paused = false;
  19160. this.enabled = true;
  19161. this.time = 0; // restart clip
  19162. this._loopCount = - 1;// forget previous loops
  19163. this._startTime = null;// forget scheduling
  19164. return this.stopFading().stopWarping();
  19165. }
  19166. isRunning() {
  19167. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19168. this._startTime === null && this._mixer._isActiveAction( this );
  19169. }
  19170. // return true when play has been called
  19171. isScheduled() {
  19172. return this._mixer._isActiveAction( this );
  19173. }
  19174. startAt( time ) {
  19175. this._startTime = time;
  19176. return this;
  19177. }
  19178. setLoop( mode, repetitions ) {
  19179. this.loop = mode;
  19180. this.repetitions = repetitions;
  19181. return this;
  19182. }
  19183. // Weight
  19184. // set the weight stopping any scheduled fading
  19185. // although .enabled = false yields an effective weight of zero, this
  19186. // method does *not* change .enabled, because it would be confusing
  19187. setEffectiveWeight( weight ) {
  19188. this.weight = weight;
  19189. // note: same logic as when updated at runtime
  19190. this._effectiveWeight = this.enabled ? weight : 0;
  19191. return this.stopFading();
  19192. }
  19193. // return the weight considering fading and .enabled
  19194. getEffectiveWeight() {
  19195. return this._effectiveWeight;
  19196. }
  19197. fadeIn( duration ) {
  19198. return this._scheduleFading( duration, 0, 1 );
  19199. }
  19200. fadeOut( duration ) {
  19201. return this._scheduleFading( duration, 1, 0 );
  19202. }
  19203. crossFadeFrom( fadeOutAction, duration, warp ) {
  19204. fadeOutAction.fadeOut( duration );
  19205. this.fadeIn( duration );
  19206. if ( warp ) {
  19207. const fadeInDuration = this._clip.duration,
  19208. fadeOutDuration = fadeOutAction._clip.duration,
  19209. startEndRatio = fadeOutDuration / fadeInDuration,
  19210. endStartRatio = fadeInDuration / fadeOutDuration;
  19211. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19212. this.warp( endStartRatio, 1.0, duration );
  19213. }
  19214. return this;
  19215. }
  19216. crossFadeTo( fadeInAction, duration, warp ) {
  19217. return fadeInAction.crossFadeFrom( this, duration, warp );
  19218. }
  19219. stopFading() {
  19220. const weightInterpolant = this._weightInterpolant;
  19221. if ( weightInterpolant !== null ) {
  19222. this._weightInterpolant = null;
  19223. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19224. }
  19225. return this;
  19226. }
  19227. // Time Scale Control
  19228. // set the time scale stopping any scheduled warping
  19229. // although .paused = true yields an effective time scale of zero, this
  19230. // method does *not* change .paused, because it would be confusing
  19231. setEffectiveTimeScale( timeScale ) {
  19232. this.timeScale = timeScale;
  19233. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19234. return this.stopWarping();
  19235. }
  19236. // return the time scale considering warping and .paused
  19237. getEffectiveTimeScale() {
  19238. return this._effectiveTimeScale;
  19239. }
  19240. setDuration( duration ) {
  19241. this.timeScale = this._clip.duration / duration;
  19242. return this.stopWarping();
  19243. }
  19244. syncWith( action ) {
  19245. this.time = action.time;
  19246. this.timeScale = action.timeScale;
  19247. return this.stopWarping();
  19248. }
  19249. halt( duration ) {
  19250. return this.warp( this._effectiveTimeScale, 0, duration );
  19251. }
  19252. warp( startTimeScale, endTimeScale, duration ) {
  19253. const mixer = this._mixer,
  19254. now = mixer.time,
  19255. timeScale = this.timeScale;
  19256. let interpolant = this._timeScaleInterpolant;
  19257. if ( interpolant === null ) {
  19258. interpolant = mixer._lendControlInterpolant();
  19259. this._timeScaleInterpolant = interpolant;
  19260. }
  19261. const times = interpolant.parameterPositions,
  19262. values = interpolant.sampleValues;
  19263. times[ 0 ] = now;
  19264. times[ 1 ] = now + duration;
  19265. values[ 0 ] = startTimeScale / timeScale;
  19266. values[ 1 ] = endTimeScale / timeScale;
  19267. return this;
  19268. }
  19269. stopWarping() {
  19270. const timeScaleInterpolant = this._timeScaleInterpolant;
  19271. if ( timeScaleInterpolant !== null ) {
  19272. this._timeScaleInterpolant = null;
  19273. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19274. }
  19275. return this;
  19276. }
  19277. // Object Accessors
  19278. getMixer() {
  19279. return this._mixer;
  19280. }
  19281. getClip() {
  19282. return this._clip;
  19283. }
  19284. getRoot() {
  19285. return this._localRoot || this._mixer._root;
  19286. }
  19287. // Interna
  19288. _update( time, deltaTime, timeDirection, accuIndex ) {
  19289. // called by the mixer
  19290. if ( ! this.enabled ) {
  19291. // call ._updateWeight() to update ._effectiveWeight
  19292. this._updateWeight( time );
  19293. return;
  19294. }
  19295. const startTime = this._startTime;
  19296. if ( startTime !== null ) {
  19297. // check for scheduled start of action
  19298. const timeRunning = ( time - startTime ) * timeDirection;
  19299. if ( timeRunning < 0 || timeDirection === 0 ) {
  19300. deltaTime = 0;
  19301. } else {
  19302. this._startTime = null; // unschedule
  19303. deltaTime = timeDirection * timeRunning;
  19304. }
  19305. }
  19306. // apply time scale and advance time
  19307. deltaTime *= this._updateTimeScale( time );
  19308. const clipTime = this._updateTime( deltaTime );
  19309. // note: _updateTime may disable the action resulting in
  19310. // an effective weight of 0
  19311. const weight = this._updateWeight( time );
  19312. if ( weight > 0 ) {
  19313. const interpolants = this._interpolants;
  19314. const propertyMixers = this._propertyBindings;
  19315. switch ( this.blendMode ) {
  19316. case AdditiveAnimationBlendMode:
  19317. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19318. interpolants[ j ].evaluate( clipTime );
  19319. propertyMixers[ j ].accumulateAdditive( weight );
  19320. }
  19321. break;
  19322. case NormalAnimationBlendMode:
  19323. default:
  19324. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19325. interpolants[ j ].evaluate( clipTime );
  19326. propertyMixers[ j ].accumulate( accuIndex, weight );
  19327. }
  19328. }
  19329. }
  19330. }
  19331. _updateWeight( time ) {
  19332. let weight = 0;
  19333. if ( this.enabled ) {
  19334. weight = this.weight;
  19335. const interpolant = this._weightInterpolant;
  19336. if ( interpolant !== null ) {
  19337. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19338. weight *= interpolantValue;
  19339. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19340. this.stopFading();
  19341. if ( interpolantValue === 0 ) {
  19342. // faded out, disable
  19343. this.enabled = false;
  19344. }
  19345. }
  19346. }
  19347. }
  19348. this._effectiveWeight = weight;
  19349. return weight;
  19350. }
  19351. _updateTimeScale( time ) {
  19352. let timeScale = 0;
  19353. if ( ! this.paused ) {
  19354. timeScale = this.timeScale;
  19355. const interpolant = this._timeScaleInterpolant;
  19356. if ( interpolant !== null ) {
  19357. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19358. timeScale *= interpolantValue;
  19359. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19360. this.stopWarping();
  19361. if ( timeScale === 0 ) {
  19362. // motion has halted, pause
  19363. this.paused = true;
  19364. } else {
  19365. // warp done - apply final time scale
  19366. this.timeScale = timeScale;
  19367. }
  19368. }
  19369. }
  19370. }
  19371. this._effectiveTimeScale = timeScale;
  19372. return timeScale;
  19373. }
  19374. _updateTime( deltaTime ) {
  19375. const duration = this._clip.duration;
  19376. const loop = this.loop;
  19377. let time = this.time + deltaTime;
  19378. let loopCount = this._loopCount;
  19379. const pingPong = ( loop === LoopPingPong );
  19380. if ( deltaTime === 0 ) {
  19381. if ( loopCount === - 1 ) return time;
  19382. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19383. }
  19384. if ( loop === LoopOnce ) {
  19385. if ( loopCount === - 1 ) {
  19386. // just started
  19387. this._loopCount = 0;
  19388. this._setEndings( true, true, false );
  19389. }
  19390. handle_stop: {
  19391. if ( time >= duration ) {
  19392. time = duration;
  19393. } else if ( time < 0 ) {
  19394. time = 0;
  19395. } else {
  19396. this.time = time;
  19397. break handle_stop;
  19398. }
  19399. if ( this.clampWhenFinished ) this.paused = true;
  19400. else this.enabled = false;
  19401. this.time = time;
  19402. this._mixer.dispatchEvent( {
  19403. type: 'finished', action: this,
  19404. direction: deltaTime < 0 ? - 1 : 1
  19405. } );
  19406. }
  19407. } else { // repetitive Repeat or PingPong
  19408. if ( loopCount === - 1 ) {
  19409. // just started
  19410. if ( deltaTime >= 0 ) {
  19411. loopCount = 0;
  19412. this._setEndings( true, this.repetitions === 0, pingPong );
  19413. } else {
  19414. // when looping in reverse direction, the initial
  19415. // transition through zero counts as a repetition,
  19416. // so leave loopCount at -1
  19417. this._setEndings( this.repetitions === 0, true, pingPong );
  19418. }
  19419. }
  19420. if ( time >= duration || time < 0 ) {
  19421. // wrap around
  19422. const loopDelta = Math.floor( time / duration ); // signed
  19423. time -= duration * loopDelta;
  19424. loopCount += Math.abs( loopDelta );
  19425. const pending = this.repetitions - loopCount;
  19426. if ( pending <= 0 ) {
  19427. // have to stop (switch state, clamp time, fire event)
  19428. if ( this.clampWhenFinished ) this.paused = true;
  19429. else this.enabled = false;
  19430. time = deltaTime > 0 ? duration : 0;
  19431. this.time = time;
  19432. this._mixer.dispatchEvent( {
  19433. type: 'finished', action: this,
  19434. direction: deltaTime > 0 ? 1 : - 1
  19435. } );
  19436. } else {
  19437. // keep running
  19438. if ( pending === 1 ) {
  19439. // entering the last round
  19440. const atStart = deltaTime < 0;
  19441. this._setEndings( atStart, ! atStart, pingPong );
  19442. } else {
  19443. this._setEndings( false, false, pingPong );
  19444. }
  19445. this._loopCount = loopCount;
  19446. this.time = time;
  19447. this._mixer.dispatchEvent( {
  19448. type: 'loop', action: this, loopDelta: loopDelta
  19449. } );
  19450. }
  19451. } else {
  19452. this.time = time;
  19453. }
  19454. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19455. // invert time for the "pong round"
  19456. return duration - time;
  19457. }
  19458. }
  19459. return time;
  19460. }
  19461. _setEndings( atStart, atEnd, pingPong ) {
  19462. const settings = this._interpolantSettings;
  19463. if ( pingPong ) {
  19464. settings.endingStart = ZeroSlopeEnding;
  19465. settings.endingEnd = ZeroSlopeEnding;
  19466. } else {
  19467. // assuming for LoopOnce atStart == atEnd == true
  19468. if ( atStart ) {
  19469. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19470. } else {
  19471. settings.endingStart = WrapAroundEnding;
  19472. }
  19473. if ( atEnd ) {
  19474. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19475. } else {
  19476. settings.endingEnd = WrapAroundEnding;
  19477. }
  19478. }
  19479. }
  19480. _scheduleFading( duration, weightNow, weightThen ) {
  19481. const mixer = this._mixer, now = mixer.time;
  19482. let interpolant = this._weightInterpolant;
  19483. if ( interpolant === null ) {
  19484. interpolant = mixer._lendControlInterpolant();
  19485. this._weightInterpolant = interpolant;
  19486. }
  19487. const times = interpolant.parameterPositions,
  19488. values = interpolant.sampleValues;
  19489. times[ 0 ] = now;
  19490. values[ 0 ] = weightNow;
  19491. times[ 1 ] = now + duration;
  19492. values[ 1 ] = weightThen;
  19493. return this;
  19494. }
  19495. }
  19496. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19497. class AnimationMixer extends EventDispatcher {
  19498. constructor( root ) {
  19499. super();
  19500. this._root = root;
  19501. this._initMemoryManager();
  19502. this._accuIndex = 0;
  19503. this.time = 0;
  19504. this.timeScale = 1.0;
  19505. }
  19506. _bindAction( action, prototypeAction ) {
  19507. const root = action._localRoot || this._root,
  19508. tracks = action._clip.tracks,
  19509. nTracks = tracks.length,
  19510. bindings = action._propertyBindings,
  19511. interpolants = action._interpolants,
  19512. rootUuid = root.uuid,
  19513. bindingsByRoot = this._bindingsByRootAndName;
  19514. let bindingsByName = bindingsByRoot[ rootUuid ];
  19515. if ( bindingsByName === undefined ) {
  19516. bindingsByName = {};
  19517. bindingsByRoot[ rootUuid ] = bindingsByName;
  19518. }
  19519. for ( let i = 0; i !== nTracks; ++ i ) {
  19520. const track = tracks[ i ],
  19521. trackName = track.name;
  19522. let binding = bindingsByName[ trackName ];
  19523. if ( binding !== undefined ) {
  19524. ++ binding.referenceCount;
  19525. bindings[ i ] = binding;
  19526. } else {
  19527. binding = bindings[ i ];
  19528. if ( binding !== undefined ) {
  19529. // existing binding, make sure the cache knows
  19530. if ( binding._cacheIndex === null ) {
  19531. ++ binding.referenceCount;
  19532. this._addInactiveBinding( binding, rootUuid, trackName );
  19533. }
  19534. continue;
  19535. }
  19536. const path = prototypeAction && prototypeAction.
  19537. _propertyBindings[ i ].binding.parsedPath;
  19538. binding = new PropertyMixer(
  19539. PropertyBinding.create( root, trackName, path ),
  19540. track.ValueTypeName, track.getValueSize() );
  19541. ++ binding.referenceCount;
  19542. this._addInactiveBinding( binding, rootUuid, trackName );
  19543. bindings[ i ] = binding;
  19544. }
  19545. interpolants[ i ].resultBuffer = binding.buffer;
  19546. }
  19547. }
  19548. _activateAction( action ) {
  19549. if ( ! this._isActiveAction( action ) ) {
  19550. if ( action._cacheIndex === null ) {
  19551. // this action has been forgotten by the cache, but the user
  19552. // appears to be still using it -> rebind
  19553. const rootUuid = ( action._localRoot || this._root ).uuid,
  19554. clipUuid = action._clip.uuid,
  19555. actionsForClip = this._actionsByClip[ clipUuid ];
  19556. this._bindAction( action,
  19557. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19558. this._addInactiveAction( action, clipUuid, rootUuid );
  19559. }
  19560. const bindings = action._propertyBindings;
  19561. // increment reference counts / sort out state
  19562. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19563. const binding = bindings[ i ];
  19564. if ( binding.useCount ++ === 0 ) {
  19565. this._lendBinding( binding );
  19566. binding.saveOriginalState();
  19567. }
  19568. }
  19569. this._lendAction( action );
  19570. }
  19571. }
  19572. _deactivateAction( action ) {
  19573. if ( this._isActiveAction( action ) ) {
  19574. const bindings = action._propertyBindings;
  19575. // decrement reference counts / sort out state
  19576. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19577. const binding = bindings[ i ];
  19578. if ( -- binding.useCount === 0 ) {
  19579. binding.restoreOriginalState();
  19580. this._takeBackBinding( binding );
  19581. }
  19582. }
  19583. this._takeBackAction( action );
  19584. }
  19585. }
  19586. // Memory manager
  19587. _initMemoryManager() {
  19588. this._actions = []; // 'nActiveActions' followed by inactive ones
  19589. this._nActiveActions = 0;
  19590. this._actionsByClip = {};
  19591. // inside:
  19592. // {
  19593. // knownActions: Array< AnimationAction > - used as prototypes
  19594. // actionByRoot: AnimationAction - lookup
  19595. // }
  19596. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19597. this._nActiveBindings = 0;
  19598. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19599. this._controlInterpolants = []; // same game as above
  19600. this._nActiveControlInterpolants = 0;
  19601. const scope = this;
  19602. this.stats = {
  19603. actions: {
  19604. get total() {
  19605. return scope._actions.length;
  19606. },
  19607. get inUse() {
  19608. return scope._nActiveActions;
  19609. }
  19610. },
  19611. bindings: {
  19612. get total() {
  19613. return scope._bindings.length;
  19614. },
  19615. get inUse() {
  19616. return scope._nActiveBindings;
  19617. }
  19618. },
  19619. controlInterpolants: {
  19620. get total() {
  19621. return scope._controlInterpolants.length;
  19622. },
  19623. get inUse() {
  19624. return scope._nActiveControlInterpolants;
  19625. }
  19626. }
  19627. };
  19628. }
  19629. // Memory management for AnimationAction objects
  19630. _isActiveAction( action ) {
  19631. const index = action._cacheIndex;
  19632. return index !== null && index < this._nActiveActions;
  19633. }
  19634. _addInactiveAction( action, clipUuid, rootUuid ) {
  19635. const actions = this._actions,
  19636. actionsByClip = this._actionsByClip;
  19637. let actionsForClip = actionsByClip[ clipUuid ];
  19638. if ( actionsForClip === undefined ) {
  19639. actionsForClip = {
  19640. knownActions: [ action ],
  19641. actionByRoot: {}
  19642. };
  19643. action._byClipCacheIndex = 0;
  19644. actionsByClip[ clipUuid ] = actionsForClip;
  19645. } else {
  19646. const knownActions = actionsForClip.knownActions;
  19647. action._byClipCacheIndex = knownActions.length;
  19648. knownActions.push( action );
  19649. }
  19650. action._cacheIndex = actions.length;
  19651. actions.push( action );
  19652. actionsForClip.actionByRoot[ rootUuid ] = action;
  19653. }
  19654. _removeInactiveAction( action ) {
  19655. const actions = this._actions,
  19656. lastInactiveAction = actions[ actions.length - 1 ],
  19657. cacheIndex = action._cacheIndex;
  19658. lastInactiveAction._cacheIndex = cacheIndex;
  19659. actions[ cacheIndex ] = lastInactiveAction;
  19660. actions.pop();
  19661. action._cacheIndex = null;
  19662. const clipUuid = action._clip.uuid,
  19663. actionsByClip = this._actionsByClip,
  19664. actionsForClip = actionsByClip[ clipUuid ],
  19665. knownActionsForClip = actionsForClip.knownActions,
  19666. lastKnownAction =
  19667. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19668. byClipCacheIndex = action._byClipCacheIndex;
  19669. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19670. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19671. knownActionsForClip.pop();
  19672. action._byClipCacheIndex = null;
  19673. const actionByRoot = actionsForClip.actionByRoot,
  19674. rootUuid = ( action._localRoot || this._root ).uuid;
  19675. delete actionByRoot[ rootUuid ];
  19676. if ( knownActionsForClip.length === 0 ) {
  19677. delete actionsByClip[ clipUuid ];
  19678. }
  19679. this._removeInactiveBindingsForAction( action );
  19680. }
  19681. _removeInactiveBindingsForAction( action ) {
  19682. const bindings = action._propertyBindings;
  19683. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19684. const binding = bindings[ i ];
  19685. if ( -- binding.referenceCount === 0 ) {
  19686. this._removeInactiveBinding( binding );
  19687. }
  19688. }
  19689. }
  19690. _lendAction( action ) {
  19691. // [ active actions | inactive actions ]
  19692. // [ active actions >| inactive actions ]
  19693. // s a
  19694. // <-swap->
  19695. // a s
  19696. const actions = this._actions,
  19697. prevIndex = action._cacheIndex,
  19698. lastActiveIndex = this._nActiveActions ++,
  19699. firstInactiveAction = actions[ lastActiveIndex ];
  19700. action._cacheIndex = lastActiveIndex;
  19701. actions[ lastActiveIndex ] = action;
  19702. firstInactiveAction._cacheIndex = prevIndex;
  19703. actions[ prevIndex ] = firstInactiveAction;
  19704. }
  19705. _takeBackAction( action ) {
  19706. // [ active actions | inactive actions ]
  19707. // [ active actions |< inactive actions ]
  19708. // a s
  19709. // <-swap->
  19710. // s a
  19711. const actions = this._actions,
  19712. prevIndex = action._cacheIndex,
  19713. firstInactiveIndex = -- this._nActiveActions,
  19714. lastActiveAction = actions[ firstInactiveIndex ];
  19715. action._cacheIndex = firstInactiveIndex;
  19716. actions[ firstInactiveIndex ] = action;
  19717. lastActiveAction._cacheIndex = prevIndex;
  19718. actions[ prevIndex ] = lastActiveAction;
  19719. }
  19720. // Memory management for PropertyMixer objects
  19721. _addInactiveBinding( binding, rootUuid, trackName ) {
  19722. const bindingsByRoot = this._bindingsByRootAndName,
  19723. bindings = this._bindings;
  19724. let bindingByName = bindingsByRoot[ rootUuid ];
  19725. if ( bindingByName === undefined ) {
  19726. bindingByName = {};
  19727. bindingsByRoot[ rootUuid ] = bindingByName;
  19728. }
  19729. bindingByName[ trackName ] = binding;
  19730. binding._cacheIndex = bindings.length;
  19731. bindings.push( binding );
  19732. }
  19733. _removeInactiveBinding( binding ) {
  19734. const bindings = this._bindings,
  19735. propBinding = binding.binding,
  19736. rootUuid = propBinding.rootNode.uuid,
  19737. trackName = propBinding.path,
  19738. bindingsByRoot = this._bindingsByRootAndName,
  19739. bindingByName = bindingsByRoot[ rootUuid ],
  19740. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19741. cacheIndex = binding._cacheIndex;
  19742. lastInactiveBinding._cacheIndex = cacheIndex;
  19743. bindings[ cacheIndex ] = lastInactiveBinding;
  19744. bindings.pop();
  19745. delete bindingByName[ trackName ];
  19746. if ( Object.keys( bindingByName ).length === 0 ) {
  19747. delete bindingsByRoot[ rootUuid ];
  19748. }
  19749. }
  19750. _lendBinding( binding ) {
  19751. const bindings = this._bindings,
  19752. prevIndex = binding._cacheIndex,
  19753. lastActiveIndex = this._nActiveBindings ++,
  19754. firstInactiveBinding = bindings[ lastActiveIndex ];
  19755. binding._cacheIndex = lastActiveIndex;
  19756. bindings[ lastActiveIndex ] = binding;
  19757. firstInactiveBinding._cacheIndex = prevIndex;
  19758. bindings[ prevIndex ] = firstInactiveBinding;
  19759. }
  19760. _takeBackBinding( binding ) {
  19761. const bindings = this._bindings,
  19762. prevIndex = binding._cacheIndex,
  19763. firstInactiveIndex = -- this._nActiveBindings,
  19764. lastActiveBinding = bindings[ firstInactiveIndex ];
  19765. binding._cacheIndex = firstInactiveIndex;
  19766. bindings[ firstInactiveIndex ] = binding;
  19767. lastActiveBinding._cacheIndex = prevIndex;
  19768. bindings[ prevIndex ] = lastActiveBinding;
  19769. }
  19770. // Memory management of Interpolants for weight and time scale
  19771. _lendControlInterpolant() {
  19772. const interpolants = this._controlInterpolants,
  19773. lastActiveIndex = this._nActiveControlInterpolants ++;
  19774. let interpolant = interpolants[ lastActiveIndex ];
  19775. if ( interpolant === undefined ) {
  19776. interpolant = new LinearInterpolant(
  19777. new Float32Array( 2 ), new Float32Array( 2 ),
  19778. 1, _controlInterpolantsResultBuffer );
  19779. interpolant.__cacheIndex = lastActiveIndex;
  19780. interpolants[ lastActiveIndex ] = interpolant;
  19781. }
  19782. return interpolant;
  19783. }
  19784. _takeBackControlInterpolant( interpolant ) {
  19785. const interpolants = this._controlInterpolants,
  19786. prevIndex = interpolant.__cacheIndex,
  19787. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19788. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19789. interpolant.__cacheIndex = firstInactiveIndex;
  19790. interpolants[ firstInactiveIndex ] = interpolant;
  19791. lastActiveInterpolant.__cacheIndex = prevIndex;
  19792. interpolants[ prevIndex ] = lastActiveInterpolant;
  19793. }
  19794. // return an action for a clip optionally using a custom root target
  19795. // object (this method allocates a lot of dynamic memory in case a
  19796. // previously unknown clip/root combination is specified)
  19797. clipAction( clip, optionalRoot, blendMode ) {
  19798. const root = optionalRoot || this._root,
  19799. rootUuid = root.uuid;
  19800. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  19801. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  19802. const actionsForClip = this._actionsByClip[ clipUuid ];
  19803. let prototypeAction = null;
  19804. if ( blendMode === undefined ) {
  19805. if ( clipObject !== null ) {
  19806. blendMode = clipObject.blendMode;
  19807. } else {
  19808. blendMode = NormalAnimationBlendMode;
  19809. }
  19810. }
  19811. if ( actionsForClip !== undefined ) {
  19812. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  19813. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  19814. return existingAction;
  19815. }
  19816. // we know the clip, so we don't have to parse all
  19817. // the bindings again but can just copy
  19818. prototypeAction = actionsForClip.knownActions[ 0 ];
  19819. // also, take the clip from the prototype action
  19820. if ( clipObject === null )
  19821. clipObject = prototypeAction._clip;
  19822. }
  19823. // clip must be known when specified via string
  19824. if ( clipObject === null ) return null;
  19825. // allocate all resources required to run it
  19826. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  19827. this._bindAction( newAction, prototypeAction );
  19828. // and make the action known to the memory manager
  19829. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19830. return newAction;
  19831. }
  19832. // get an existing action
  19833. existingAction( clip, optionalRoot ) {
  19834. const root = optionalRoot || this._root,
  19835. rootUuid = root.uuid,
  19836. clipObject = typeof clip === 'string' ?
  19837. AnimationClip.findByName( root, clip ) : clip,
  19838. clipUuid = clipObject ? clipObject.uuid : clip,
  19839. actionsForClip = this._actionsByClip[ clipUuid ];
  19840. if ( actionsForClip !== undefined ) {
  19841. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19842. }
  19843. return null;
  19844. }
  19845. // deactivates all previously scheduled actions
  19846. stopAllAction() {
  19847. const actions = this._actions,
  19848. nActions = this._nActiveActions;
  19849. for ( let i = nActions - 1; i >= 0; -- i ) {
  19850. actions[ i ].stop();
  19851. }
  19852. return this;
  19853. }
  19854. // advance the time and update apply the animation
  19855. update( deltaTime ) {
  19856. deltaTime *= this.timeScale;
  19857. const actions = this._actions,
  19858. nActions = this._nActiveActions,
  19859. time = this.time += deltaTime,
  19860. timeDirection = Math.sign( deltaTime ),
  19861. accuIndex = this._accuIndex ^= 1;
  19862. // run active actions
  19863. for ( let i = 0; i !== nActions; ++ i ) {
  19864. const action = actions[ i ];
  19865. action._update( time, deltaTime, timeDirection, accuIndex );
  19866. }
  19867. // update scene graph
  19868. const bindings = this._bindings,
  19869. nBindings = this._nActiveBindings;
  19870. for ( let i = 0; i !== nBindings; ++ i ) {
  19871. bindings[ i ].apply( accuIndex );
  19872. }
  19873. return this;
  19874. }
  19875. // Allows you to seek to a specific time in an animation.
  19876. setTime( timeInSeconds ) {
  19877. this.time = 0; // Zero out time attribute for AnimationMixer object;
  19878. for ( let i = 0; i < this._actions.length; i ++ ) {
  19879. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  19880. }
  19881. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  19882. }
  19883. // return this mixer's root target object
  19884. getRoot() {
  19885. return this._root;
  19886. }
  19887. // free all resources specific to a particular clip
  19888. uncacheClip( clip ) {
  19889. const actions = this._actions,
  19890. clipUuid = clip.uuid,
  19891. actionsByClip = this._actionsByClip,
  19892. actionsForClip = actionsByClip[ clipUuid ];
  19893. if ( actionsForClip !== undefined ) {
  19894. // note: just calling _removeInactiveAction would mess up the
  19895. // iteration state and also require updating the state we can
  19896. // just throw away
  19897. const actionsToRemove = actionsForClip.knownActions;
  19898. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19899. const action = actionsToRemove[ i ];
  19900. this._deactivateAction( action );
  19901. const cacheIndex = action._cacheIndex,
  19902. lastInactiveAction = actions[ actions.length - 1 ];
  19903. action._cacheIndex = null;
  19904. action._byClipCacheIndex = null;
  19905. lastInactiveAction._cacheIndex = cacheIndex;
  19906. actions[ cacheIndex ] = lastInactiveAction;
  19907. actions.pop();
  19908. this._removeInactiveBindingsForAction( action );
  19909. }
  19910. delete actionsByClip[ clipUuid ];
  19911. }
  19912. }
  19913. // free all resources specific to a particular root target object
  19914. uncacheRoot( root ) {
  19915. const rootUuid = root.uuid,
  19916. actionsByClip = this._actionsByClip;
  19917. for ( const clipUuid in actionsByClip ) {
  19918. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19919. action = actionByRoot[ rootUuid ];
  19920. if ( action !== undefined ) {
  19921. this._deactivateAction( action );
  19922. this._removeInactiveAction( action );
  19923. }
  19924. }
  19925. const bindingsByRoot = this._bindingsByRootAndName,
  19926. bindingByName = bindingsByRoot[ rootUuid ];
  19927. if ( bindingByName !== undefined ) {
  19928. for ( const trackName in bindingByName ) {
  19929. const binding = bindingByName[ trackName ];
  19930. binding.restoreOriginalState();
  19931. this._removeInactiveBinding( binding );
  19932. }
  19933. }
  19934. }
  19935. // remove a targeted clip from the cache
  19936. uncacheAction( clip, optionalRoot ) {
  19937. const action = this.existingAction( clip, optionalRoot );
  19938. if ( action !== null ) {
  19939. this._deactivateAction( action );
  19940. this._removeInactiveAction( action );
  19941. }
  19942. }
  19943. }
  19944. let Uniform$1 = class Uniform {
  19945. constructor( value ) {
  19946. this.value = value;
  19947. }
  19948. clone() {
  19949. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  19950. }
  19951. };
  19952. let _id$5 = 0;
  19953. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  19954. constructor() {
  19955. super();
  19956. this.isUniformsGroup = true;
  19957. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  19958. this.name = '';
  19959. this.usage = StaticDrawUsage;
  19960. this.uniforms = [];
  19961. }
  19962. add( uniform ) {
  19963. this.uniforms.push( uniform );
  19964. return this;
  19965. }
  19966. remove( uniform ) {
  19967. const index = this.uniforms.indexOf( uniform );
  19968. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  19969. return this;
  19970. }
  19971. setName( name ) {
  19972. this.name = name;
  19973. return this;
  19974. }
  19975. setUsage( value ) {
  19976. this.usage = value;
  19977. return this;
  19978. }
  19979. dispose() {
  19980. this.dispatchEvent( { type: 'dispose' } );
  19981. return this;
  19982. }
  19983. copy( source ) {
  19984. this.name = source.name;
  19985. this.usage = source.usage;
  19986. const uniformsSource = source.uniforms;
  19987. this.uniforms.length = 0;
  19988. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  19989. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  19990. for ( let j = 0; j < uniforms.length; j ++ ) {
  19991. this.uniforms.push( uniforms[ j ].clone() );
  19992. }
  19993. }
  19994. return this;
  19995. }
  19996. clone() {
  19997. return new this.constructor().copy( this );
  19998. }
  19999. };
  20000. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20001. constructor( array, stride, meshPerAttribute = 1 ) {
  20002. super( array, stride );
  20003. this.isInstancedInterleavedBuffer = true;
  20004. this.meshPerAttribute = meshPerAttribute;
  20005. }
  20006. copy( source ) {
  20007. super.copy( source );
  20008. this.meshPerAttribute = source.meshPerAttribute;
  20009. return this;
  20010. }
  20011. clone( data ) {
  20012. const ib = super.clone( data );
  20013. ib.meshPerAttribute = this.meshPerAttribute;
  20014. return ib;
  20015. }
  20016. toJSON( data ) {
  20017. const json = super.toJSON( data );
  20018. json.isInstancedInterleavedBuffer = true;
  20019. json.meshPerAttribute = this.meshPerAttribute;
  20020. return json;
  20021. }
  20022. }
  20023. class GLBufferAttribute {
  20024. constructor( buffer, type, itemSize, elementSize, count ) {
  20025. this.isGLBufferAttribute = true;
  20026. this.name = '';
  20027. this.buffer = buffer;
  20028. this.type = type;
  20029. this.itemSize = itemSize;
  20030. this.elementSize = elementSize;
  20031. this.count = count;
  20032. this.version = 0;
  20033. }
  20034. set needsUpdate( value ) {
  20035. if ( value === true ) this.version ++;
  20036. }
  20037. setBuffer( buffer ) {
  20038. this.buffer = buffer;
  20039. return this;
  20040. }
  20041. setType( type, elementSize ) {
  20042. this.type = type;
  20043. this.elementSize = elementSize;
  20044. return this;
  20045. }
  20046. setItemSize( itemSize ) {
  20047. this.itemSize = itemSize;
  20048. return this;
  20049. }
  20050. setCount( count ) {
  20051. this.count = count;
  20052. return this;
  20053. }
  20054. }
  20055. const _matrix = /*@__PURE__*/ new Matrix4();
  20056. class Raycaster {
  20057. constructor( origin, direction, near = 0, far = Infinity ) {
  20058. this.ray = new Ray( origin, direction );
  20059. // direction is assumed to be normalized (for accurate distance calculations)
  20060. this.near = near;
  20061. this.far = far;
  20062. this.camera = null;
  20063. this.layers = new Layers();
  20064. this.params = {
  20065. Mesh: {},
  20066. Line: { threshold: 1 },
  20067. LOD: {},
  20068. Points: { threshold: 1 },
  20069. Sprite: {}
  20070. };
  20071. }
  20072. set( origin, direction ) {
  20073. // direction is assumed to be normalized (for accurate distance calculations)
  20074. this.ray.set( origin, direction );
  20075. }
  20076. setFromCamera( coords, camera ) {
  20077. if ( camera.isPerspectiveCamera ) {
  20078. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20079. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20080. this.camera = camera;
  20081. } else if ( camera.isOrthographicCamera ) {
  20082. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20083. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20084. this.camera = camera;
  20085. } else {
  20086. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20087. }
  20088. }
  20089. setFromXRController( controller ) {
  20090. _matrix.identity().extractRotation( controller.matrixWorld );
  20091. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20092. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20093. return this;
  20094. }
  20095. intersectObject( object, recursive = true, intersects = [] ) {
  20096. intersect( object, this, intersects, recursive );
  20097. intersects.sort( ascSort );
  20098. return intersects;
  20099. }
  20100. intersectObjects( objects, recursive = true, intersects = [] ) {
  20101. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20102. intersect( objects[ i ], this, intersects, recursive );
  20103. }
  20104. intersects.sort( ascSort );
  20105. return intersects;
  20106. }
  20107. }
  20108. function ascSort( a, b ) {
  20109. return a.distance - b.distance;
  20110. }
  20111. function intersect( object, raycaster, intersects, recursive ) {
  20112. let propagate = true;
  20113. if ( object.layers.test( raycaster.layers ) ) {
  20114. const result = object.raycast( raycaster, intersects );
  20115. if ( result === false ) propagate = false;
  20116. }
  20117. if ( propagate === true && recursive === true ) {
  20118. const children = object.children;
  20119. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20120. intersect( children[ i ], raycaster, intersects, true );
  20121. }
  20122. }
  20123. }
  20124. /**
  20125. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20126. *
  20127. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20128. * theta (the azimuthal angle) is measured from the positive z-axis.
  20129. */
  20130. class Spherical {
  20131. constructor( radius = 1, phi = 0, theta = 0 ) {
  20132. this.radius = radius;
  20133. this.phi = phi; // polar angle
  20134. this.theta = theta; // azimuthal angle
  20135. return this;
  20136. }
  20137. set( radius, phi, theta ) {
  20138. this.radius = radius;
  20139. this.phi = phi;
  20140. this.theta = theta;
  20141. return this;
  20142. }
  20143. copy( other ) {
  20144. this.radius = other.radius;
  20145. this.phi = other.phi;
  20146. this.theta = other.theta;
  20147. return this;
  20148. }
  20149. // restrict phi to be between EPS and PI-EPS
  20150. makeSafe() {
  20151. const EPS = 0.000001;
  20152. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20153. return this;
  20154. }
  20155. setFromVector3( v ) {
  20156. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20157. }
  20158. setFromCartesianCoords( x, y, z ) {
  20159. this.radius = Math.sqrt( x * x + y * y + z * z );
  20160. if ( this.radius === 0 ) {
  20161. this.theta = 0;
  20162. this.phi = 0;
  20163. } else {
  20164. this.theta = Math.atan2( x, z );
  20165. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20166. }
  20167. return this;
  20168. }
  20169. clone() {
  20170. return new this.constructor().copy( this );
  20171. }
  20172. }
  20173. /**
  20174. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20175. */
  20176. class Cylindrical {
  20177. constructor( radius = 1, theta = 0, y = 0 ) {
  20178. this.radius = radius; // distance from the origin to a point in the x-z plane
  20179. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20180. this.y = y; // height above the x-z plane
  20181. return this;
  20182. }
  20183. set( radius, theta, y ) {
  20184. this.radius = radius;
  20185. this.theta = theta;
  20186. this.y = y;
  20187. return this;
  20188. }
  20189. copy( other ) {
  20190. this.radius = other.radius;
  20191. this.theta = other.theta;
  20192. this.y = other.y;
  20193. return this;
  20194. }
  20195. setFromVector3( v ) {
  20196. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20197. }
  20198. setFromCartesianCoords( x, y, z ) {
  20199. this.radius = Math.sqrt( x * x + z * z );
  20200. this.theta = Math.atan2( x, z );
  20201. this.y = y;
  20202. return this;
  20203. }
  20204. clone() {
  20205. return new this.constructor().copy( this );
  20206. }
  20207. }
  20208. const _vector$4 = /*@__PURE__*/ new Vector2();
  20209. class Box2 {
  20210. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20211. this.isBox2 = true;
  20212. this.min = min;
  20213. this.max = max;
  20214. }
  20215. set( min, max ) {
  20216. this.min.copy( min );
  20217. this.max.copy( max );
  20218. return this;
  20219. }
  20220. setFromPoints( points ) {
  20221. this.makeEmpty();
  20222. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20223. this.expandByPoint( points[ i ] );
  20224. }
  20225. return this;
  20226. }
  20227. setFromCenterAndSize( center, size ) {
  20228. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20229. this.min.copy( center ).sub( halfSize );
  20230. this.max.copy( center ).add( halfSize );
  20231. return this;
  20232. }
  20233. clone() {
  20234. return new this.constructor().copy( this );
  20235. }
  20236. copy( box ) {
  20237. this.min.copy( box.min );
  20238. this.max.copy( box.max );
  20239. return this;
  20240. }
  20241. makeEmpty() {
  20242. this.min.x = this.min.y = + Infinity;
  20243. this.max.x = this.max.y = - Infinity;
  20244. return this;
  20245. }
  20246. isEmpty() {
  20247. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20248. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20249. }
  20250. getCenter( target ) {
  20251. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20252. }
  20253. getSize( target ) {
  20254. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20255. }
  20256. expandByPoint( point ) {
  20257. this.min.min( point );
  20258. this.max.max( point );
  20259. return this;
  20260. }
  20261. expandByVector( vector ) {
  20262. this.min.sub( vector );
  20263. this.max.add( vector );
  20264. return this;
  20265. }
  20266. expandByScalar( scalar ) {
  20267. this.min.addScalar( - scalar );
  20268. this.max.addScalar( scalar );
  20269. return this;
  20270. }
  20271. containsPoint( point ) {
  20272. return point.x < this.min.x || point.x > this.max.x ||
  20273. point.y < this.min.y || point.y > this.max.y ? false : true;
  20274. }
  20275. containsBox( box ) {
  20276. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20277. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20278. }
  20279. getParameter( point, target ) {
  20280. // This can potentially have a divide by zero if the box
  20281. // has a size dimension of 0.
  20282. return target.set(
  20283. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20284. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20285. );
  20286. }
  20287. intersectsBox( box ) {
  20288. // using 4 splitting planes to rule out intersections
  20289. return box.max.x < this.min.x || box.min.x > this.max.x ||
  20290. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  20291. }
  20292. clampPoint( point, target ) {
  20293. return target.copy( point ).clamp( this.min, this.max );
  20294. }
  20295. distanceToPoint( point ) {
  20296. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20297. }
  20298. intersect( box ) {
  20299. this.min.max( box.min );
  20300. this.max.min( box.max );
  20301. if ( this.isEmpty() ) this.makeEmpty();
  20302. return this;
  20303. }
  20304. union( box ) {
  20305. this.min.min( box.min );
  20306. this.max.max( box.max );
  20307. return this;
  20308. }
  20309. translate( offset ) {
  20310. this.min.add( offset );
  20311. this.max.add( offset );
  20312. return this;
  20313. }
  20314. equals( box ) {
  20315. return box.min.equals( this.min ) && box.max.equals( this.max );
  20316. }
  20317. }
  20318. const _startP = /*@__PURE__*/ new Vector3();
  20319. const _startEnd = /*@__PURE__*/ new Vector3();
  20320. class Line3 {
  20321. constructor( start = new Vector3(), end = new Vector3() ) {
  20322. this.start = start;
  20323. this.end = end;
  20324. }
  20325. set( start, end ) {
  20326. this.start.copy( start );
  20327. this.end.copy( end );
  20328. return this;
  20329. }
  20330. copy( line ) {
  20331. this.start.copy( line.start );
  20332. this.end.copy( line.end );
  20333. return this;
  20334. }
  20335. getCenter( target ) {
  20336. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20337. }
  20338. delta( target ) {
  20339. return target.subVectors( this.end, this.start );
  20340. }
  20341. distanceSq() {
  20342. return this.start.distanceToSquared( this.end );
  20343. }
  20344. distance() {
  20345. return this.start.distanceTo( this.end );
  20346. }
  20347. at( t, target ) {
  20348. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20349. }
  20350. closestPointToPointParameter( point, clampToLine ) {
  20351. _startP.subVectors( point, this.start );
  20352. _startEnd.subVectors( this.end, this.start );
  20353. const startEnd2 = _startEnd.dot( _startEnd );
  20354. const startEnd_startP = _startEnd.dot( _startP );
  20355. let t = startEnd_startP / startEnd2;
  20356. if ( clampToLine ) {
  20357. t = clamp$1( t, 0, 1 );
  20358. }
  20359. return t;
  20360. }
  20361. closestPointToPoint( point, clampToLine, target ) {
  20362. const t = this.closestPointToPointParameter( point, clampToLine );
  20363. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20364. }
  20365. applyMatrix4( matrix ) {
  20366. this.start.applyMatrix4( matrix );
  20367. this.end.applyMatrix4( matrix );
  20368. return this;
  20369. }
  20370. equals( line ) {
  20371. return line.start.equals( this.start ) && line.end.equals( this.end );
  20372. }
  20373. clone() {
  20374. return new this.constructor().copy( this );
  20375. }
  20376. }
  20377. const _vector$3 = /*@__PURE__*/ new Vector3();
  20378. class SpotLightHelper extends Object3D {
  20379. constructor( light, color ) {
  20380. super();
  20381. this.light = light;
  20382. this.matrixAutoUpdate = false;
  20383. this.color = color;
  20384. this.type = 'SpotLightHelper';
  20385. const geometry = new BufferGeometry();
  20386. const positions = [
  20387. 0, 0, 0, 0, 0, 1,
  20388. 0, 0, 0, 1, 0, 1,
  20389. 0, 0, 0, - 1, 0, 1,
  20390. 0, 0, 0, 0, 1, 1,
  20391. 0, 0, 0, 0, - 1, 1
  20392. ];
  20393. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20394. const p1 = ( i / l ) * Math.PI * 2;
  20395. const p2 = ( j / l ) * Math.PI * 2;
  20396. positions.push(
  20397. Math.cos( p1 ), Math.sin( p1 ), 1,
  20398. Math.cos( p2 ), Math.sin( p2 ), 1
  20399. );
  20400. }
  20401. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20402. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20403. this.cone = new LineSegments( geometry, material );
  20404. this.add( this.cone );
  20405. this.update();
  20406. }
  20407. dispose() {
  20408. this.cone.geometry.dispose();
  20409. this.cone.material.dispose();
  20410. }
  20411. update() {
  20412. this.light.updateWorldMatrix( true, false );
  20413. this.light.target.updateWorldMatrix( true, false );
  20414. // update the local matrix based on the parent and light target transforms
  20415. if ( this.parent ) {
  20416. this.parent.updateWorldMatrix( true );
  20417. this.matrix
  20418. .copy( this.parent.matrixWorld )
  20419. .invert()
  20420. .multiply( this.light.matrixWorld );
  20421. } else {
  20422. this.matrix.copy( this.light.matrixWorld );
  20423. }
  20424. this.matrixWorld.copy( this.light.matrixWorld );
  20425. const coneLength = this.light.distance ? this.light.distance : 1000;
  20426. const coneWidth = coneLength * Math.tan( this.light.angle );
  20427. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20428. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20429. this.cone.lookAt( _vector$3 );
  20430. if ( this.color !== undefined ) {
  20431. this.cone.material.color.set( this.color );
  20432. } else {
  20433. this.cone.material.color.copy( this.light.color );
  20434. }
  20435. }
  20436. }
  20437. const _vector$2 = /*@__PURE__*/ new Vector3();
  20438. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20439. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20440. class SkeletonHelper extends LineSegments {
  20441. constructor( object ) {
  20442. const bones = getBoneList( object );
  20443. const geometry = new BufferGeometry();
  20444. const vertices = [];
  20445. const colors = [];
  20446. const color1 = new Color( 0, 0, 1 );
  20447. const color2 = new Color( 0, 1, 0 );
  20448. for ( let i = 0; i < bones.length; i ++ ) {
  20449. const bone = bones[ i ];
  20450. if ( bone.parent && bone.parent.isBone ) {
  20451. vertices.push( 0, 0, 0 );
  20452. vertices.push( 0, 0, 0 );
  20453. colors.push( color1.r, color1.g, color1.b );
  20454. colors.push( color2.r, color2.g, color2.b );
  20455. }
  20456. }
  20457. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20458. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20459. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20460. super( geometry, material );
  20461. this.isSkeletonHelper = true;
  20462. this.type = 'SkeletonHelper';
  20463. this.root = object;
  20464. this.bones = bones;
  20465. this.matrix = object.matrixWorld;
  20466. this.matrixAutoUpdate = false;
  20467. }
  20468. updateMatrixWorld( force ) {
  20469. const bones = this.bones;
  20470. const geometry = this.geometry;
  20471. const position = geometry.getAttribute( 'position' );
  20472. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20473. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20474. const bone = bones[ i ];
  20475. if ( bone.parent && bone.parent.isBone ) {
  20476. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20477. _vector$2.setFromMatrixPosition( _boneMatrix );
  20478. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20479. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20480. _vector$2.setFromMatrixPosition( _boneMatrix );
  20481. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20482. j += 2;
  20483. }
  20484. }
  20485. geometry.getAttribute( 'position' ).needsUpdate = true;
  20486. super.updateMatrixWorld( force );
  20487. }
  20488. dispose() {
  20489. this.geometry.dispose();
  20490. this.material.dispose();
  20491. }
  20492. }
  20493. function getBoneList( object ) {
  20494. const boneList = [];
  20495. if ( object.isBone === true ) {
  20496. boneList.push( object );
  20497. }
  20498. for ( let i = 0; i < object.children.length; i ++ ) {
  20499. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20500. }
  20501. return boneList;
  20502. }
  20503. class PointLightHelper extends Mesh {
  20504. constructor( light, sphereSize, color ) {
  20505. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20506. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20507. super( geometry, material );
  20508. this.light = light;
  20509. this.color = color;
  20510. this.type = 'PointLightHelper';
  20511. this.matrix = this.light.matrixWorld;
  20512. this.matrixAutoUpdate = false;
  20513. this.update();
  20514. /*
  20515. // TODO: delete this comment?
  20516. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20517. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20518. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20519. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20520. const d = light.distance;
  20521. if ( d === 0.0 ) {
  20522. this.lightDistance.visible = false;
  20523. } else {
  20524. this.lightDistance.scale.set( d, d, d );
  20525. }
  20526. this.add( this.lightDistance );
  20527. */
  20528. }
  20529. dispose() {
  20530. this.geometry.dispose();
  20531. this.material.dispose();
  20532. }
  20533. update() {
  20534. this.light.updateWorldMatrix( true, false );
  20535. if ( this.color !== undefined ) {
  20536. this.material.color.set( this.color );
  20537. } else {
  20538. this.material.color.copy( this.light.color );
  20539. }
  20540. /*
  20541. const d = this.light.distance;
  20542. if ( d === 0.0 ) {
  20543. this.lightDistance.visible = false;
  20544. } else {
  20545. this.lightDistance.visible = true;
  20546. this.lightDistance.scale.set( d, d, d );
  20547. }
  20548. */
  20549. }
  20550. }
  20551. const _vector$1 = /*@__PURE__*/ new Vector3();
  20552. const _color1 = /*@__PURE__*/ new Color();
  20553. const _color2 = /*@__PURE__*/ new Color();
  20554. class HemisphereLightHelper extends Object3D {
  20555. constructor( light, size, color ) {
  20556. super();
  20557. this.light = light;
  20558. this.matrix = light.matrixWorld;
  20559. this.matrixAutoUpdate = false;
  20560. this.color = color;
  20561. this.type = 'HemisphereLightHelper';
  20562. const geometry = new OctahedronGeometry( size );
  20563. geometry.rotateY( Math.PI * 0.5 );
  20564. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20565. if ( this.color === undefined ) this.material.vertexColors = true;
  20566. const position = geometry.getAttribute( 'position' );
  20567. const colors = new Float32Array( position.count * 3 );
  20568. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20569. this.add( new Mesh( geometry, this.material ) );
  20570. this.update();
  20571. }
  20572. dispose() {
  20573. this.children[ 0 ].geometry.dispose();
  20574. this.children[ 0 ].material.dispose();
  20575. }
  20576. update() {
  20577. const mesh = this.children[ 0 ];
  20578. if ( this.color !== undefined ) {
  20579. this.material.color.set( this.color );
  20580. } else {
  20581. const colors = mesh.geometry.getAttribute( 'color' );
  20582. _color1.copy( this.light.color );
  20583. _color2.copy( this.light.groundColor );
  20584. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20585. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20586. colors.setXYZ( i, color.r, color.g, color.b );
  20587. }
  20588. colors.needsUpdate = true;
  20589. }
  20590. this.light.updateWorldMatrix( true, false );
  20591. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20592. }
  20593. }
  20594. class GridHelper extends LineSegments {
  20595. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20596. color1 = new Color( color1 );
  20597. color2 = new Color( color2 );
  20598. const center = divisions / 2;
  20599. const step = size / divisions;
  20600. const halfSize = size / 2;
  20601. const vertices = [], colors = [];
  20602. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20603. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20604. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20605. const color = i === center ? color1 : color2;
  20606. color.toArray( colors, j ); j += 3;
  20607. color.toArray( colors, j ); j += 3;
  20608. color.toArray( colors, j ); j += 3;
  20609. color.toArray( colors, j ); j += 3;
  20610. }
  20611. const geometry = new BufferGeometry();
  20612. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20613. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20614. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20615. super( geometry, material );
  20616. this.type = 'GridHelper';
  20617. }
  20618. dispose() {
  20619. this.geometry.dispose();
  20620. this.material.dispose();
  20621. }
  20622. }
  20623. class PolarGridHelper extends LineSegments {
  20624. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20625. color1 = new Color( color1 );
  20626. color2 = new Color( color2 );
  20627. const vertices = [];
  20628. const colors = [];
  20629. // create the sectors
  20630. if ( sectors > 1 ) {
  20631. for ( let i = 0; i < sectors; i ++ ) {
  20632. const v = ( i / sectors ) * ( Math.PI * 2 );
  20633. const x = Math.sin( v ) * radius;
  20634. const z = Math.cos( v ) * radius;
  20635. vertices.push( 0, 0, 0 );
  20636. vertices.push( x, 0, z );
  20637. const color = ( i & 1 ) ? color1 : color2;
  20638. colors.push( color.r, color.g, color.b );
  20639. colors.push( color.r, color.g, color.b );
  20640. }
  20641. }
  20642. // create the rings
  20643. for ( let i = 0; i < rings; i ++ ) {
  20644. const color = ( i & 1 ) ? color1 : color2;
  20645. const r = radius - ( radius / rings * i );
  20646. for ( let j = 0; j < divisions; j ++ ) {
  20647. // first vertex
  20648. let v = ( j / divisions ) * ( Math.PI * 2 );
  20649. let x = Math.sin( v ) * r;
  20650. let z = Math.cos( v ) * r;
  20651. vertices.push( x, 0, z );
  20652. colors.push( color.r, color.g, color.b );
  20653. // second vertex
  20654. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20655. x = Math.sin( v ) * r;
  20656. z = Math.cos( v ) * r;
  20657. vertices.push( x, 0, z );
  20658. colors.push( color.r, color.g, color.b );
  20659. }
  20660. }
  20661. const geometry = new BufferGeometry();
  20662. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20663. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20664. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20665. super( geometry, material );
  20666. this.type = 'PolarGridHelper';
  20667. }
  20668. dispose() {
  20669. this.geometry.dispose();
  20670. this.material.dispose();
  20671. }
  20672. }
  20673. const _v1 = /*@__PURE__*/ new Vector3();
  20674. const _v2 = /*@__PURE__*/ new Vector3();
  20675. const _v3 = /*@__PURE__*/ new Vector3();
  20676. class DirectionalLightHelper extends Object3D {
  20677. constructor( light, size, color ) {
  20678. super();
  20679. this.light = light;
  20680. this.matrix = light.matrixWorld;
  20681. this.matrixAutoUpdate = false;
  20682. this.color = color;
  20683. this.type = 'DirectionalLightHelper';
  20684. if ( size === undefined ) size = 1;
  20685. let geometry = new BufferGeometry();
  20686. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20687. - size, size, 0,
  20688. size, size, 0,
  20689. size, - size, 0,
  20690. - size, - size, 0,
  20691. - size, size, 0
  20692. ], 3 ) );
  20693. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20694. this.lightPlane = new Line( geometry, material );
  20695. this.add( this.lightPlane );
  20696. geometry = new BufferGeometry();
  20697. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20698. this.targetLine = new Line( geometry, material );
  20699. this.add( this.targetLine );
  20700. this.update();
  20701. }
  20702. dispose() {
  20703. this.lightPlane.geometry.dispose();
  20704. this.lightPlane.material.dispose();
  20705. this.targetLine.geometry.dispose();
  20706. this.targetLine.material.dispose();
  20707. }
  20708. update() {
  20709. this.light.updateWorldMatrix( true, false );
  20710. this.light.target.updateWorldMatrix( true, false );
  20711. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20712. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20713. _v3.subVectors( _v2, _v1 );
  20714. this.lightPlane.lookAt( _v2 );
  20715. if ( this.color !== undefined ) {
  20716. this.lightPlane.material.color.set( this.color );
  20717. this.targetLine.material.color.set( this.color );
  20718. } else {
  20719. this.lightPlane.material.color.copy( this.light.color );
  20720. this.targetLine.material.color.copy( this.light.color );
  20721. }
  20722. this.targetLine.lookAt( _v2 );
  20723. this.targetLine.scale.z = _v3.length();
  20724. }
  20725. }
  20726. const _vector = /*@__PURE__*/ new Vector3();
  20727. const _camera$1 = /*@__PURE__*/ new Camera();
  20728. /**
  20729. * - shows frustum, line of sight and up of the camera
  20730. * - suitable for fast updates
  20731. * - based on frustum visualization in lightgl.js shadowmap example
  20732. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20733. */
  20734. class CameraHelper extends LineSegments {
  20735. constructor( camera ) {
  20736. const geometry = new BufferGeometry();
  20737. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20738. const vertices = [];
  20739. const colors = [];
  20740. const pointMap = {};
  20741. // near
  20742. addLine( 'n1', 'n2' );
  20743. addLine( 'n2', 'n4' );
  20744. addLine( 'n4', 'n3' );
  20745. addLine( 'n3', 'n1' );
  20746. // far
  20747. addLine( 'f1', 'f2' );
  20748. addLine( 'f2', 'f4' );
  20749. addLine( 'f4', 'f3' );
  20750. addLine( 'f3', 'f1' );
  20751. // sides
  20752. addLine( 'n1', 'f1' );
  20753. addLine( 'n2', 'f2' );
  20754. addLine( 'n3', 'f3' );
  20755. addLine( 'n4', 'f4' );
  20756. // cone
  20757. addLine( 'p', 'n1' );
  20758. addLine( 'p', 'n2' );
  20759. addLine( 'p', 'n3' );
  20760. addLine( 'p', 'n4' );
  20761. // up
  20762. addLine( 'u1', 'u2' );
  20763. addLine( 'u2', 'u3' );
  20764. addLine( 'u3', 'u1' );
  20765. // target
  20766. addLine( 'c', 't' );
  20767. addLine( 'p', 'c' );
  20768. // cross
  20769. addLine( 'cn1', 'cn2' );
  20770. addLine( 'cn3', 'cn4' );
  20771. addLine( 'cf1', 'cf2' );
  20772. addLine( 'cf3', 'cf4' );
  20773. function addLine( a, b ) {
  20774. addPoint( a );
  20775. addPoint( b );
  20776. }
  20777. function addPoint( id ) {
  20778. vertices.push( 0, 0, 0 );
  20779. colors.push( 0, 0, 0 );
  20780. if ( pointMap[ id ] === undefined ) {
  20781. pointMap[ id ] = [];
  20782. }
  20783. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  20784. }
  20785. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20786. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20787. super( geometry, material );
  20788. this.type = 'CameraHelper';
  20789. this.camera = camera;
  20790. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  20791. this.matrix = camera.matrixWorld;
  20792. this.matrixAutoUpdate = false;
  20793. this.pointMap = pointMap;
  20794. this.update();
  20795. // colors
  20796. const colorFrustum = new Color( 0xffaa00 );
  20797. const colorCone = new Color( 0xff0000 );
  20798. const colorUp = new Color( 0x00aaff );
  20799. const colorTarget = new Color( 0xffffff );
  20800. const colorCross = new Color( 0x333333 );
  20801. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  20802. }
  20803. setColors( frustum, cone, up, target, cross ) {
  20804. const geometry = this.geometry;
  20805. const colorAttribute = geometry.getAttribute( 'color' );
  20806. // near
  20807. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  20808. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  20809. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  20810. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  20811. // far
  20812. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  20813. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  20814. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  20815. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  20816. // sides
  20817. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  20818. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  20819. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  20820. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  20821. // cone
  20822. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  20823. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  20824. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  20825. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  20826. // up
  20827. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  20828. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  20829. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  20830. // target
  20831. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  20832. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  20833. // cross
  20834. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  20835. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  20836. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  20837. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  20838. colorAttribute.needsUpdate = true;
  20839. }
  20840. update() {
  20841. const geometry = this.geometry;
  20842. const pointMap = this.pointMap;
  20843. const w = 1, h = 1;
  20844. // we need just camera projection matrix inverse
  20845. // world matrix must be identity
  20846. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  20847. // center / target
  20848. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  20849. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  20850. // near
  20851. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  20852. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  20853. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  20854. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  20855. // far
  20856. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  20857. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  20858. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  20859. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  20860. // up
  20861. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  20862. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  20863. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  20864. // cross
  20865. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  20866. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  20867. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  20868. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  20869. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  20870. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  20871. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  20872. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  20873. geometry.getAttribute( 'position' ).needsUpdate = true;
  20874. }
  20875. dispose() {
  20876. this.geometry.dispose();
  20877. this.material.dispose();
  20878. }
  20879. }
  20880. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  20881. _vector.set( x, y, z ).unproject( camera );
  20882. const points = pointMap[ point ];
  20883. if ( points !== undefined ) {
  20884. const position = geometry.getAttribute( 'position' );
  20885. for ( let i = 0, l = points.length; i < l; i ++ ) {
  20886. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  20887. }
  20888. }
  20889. }
  20890. const _box = /*@__PURE__*/ new Box3();
  20891. class BoxHelper extends LineSegments {
  20892. constructor( object, color = 0xffff00 ) {
  20893. 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 ] );
  20894. const positions = new Float32Array( 8 * 3 );
  20895. const geometry = new BufferGeometry();
  20896. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20897. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  20898. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20899. this.object = object;
  20900. this.type = 'BoxHelper';
  20901. this.matrixAutoUpdate = false;
  20902. this.update();
  20903. }
  20904. update( object ) {
  20905. if ( object !== undefined ) {
  20906. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  20907. }
  20908. if ( this.object !== undefined ) {
  20909. _box.setFromObject( this.object );
  20910. }
  20911. if ( _box.isEmpty() ) return;
  20912. const min = _box.min;
  20913. const max = _box.max;
  20914. /*
  20915. 5____4
  20916. 1/___0/|
  20917. | 6__|_7
  20918. 2/___3/
  20919. 0: max.x, max.y, max.z
  20920. 1: min.x, max.y, max.z
  20921. 2: min.x, min.y, max.z
  20922. 3: max.x, min.y, max.z
  20923. 4: max.x, max.y, min.z
  20924. 5: min.x, max.y, min.z
  20925. 6: min.x, min.y, min.z
  20926. 7: max.x, min.y, min.z
  20927. */
  20928. const position = this.geometry.attributes.position;
  20929. const array = position.array;
  20930. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  20931. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  20932. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  20933. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  20934. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  20935. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  20936. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  20937. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  20938. position.needsUpdate = true;
  20939. this.geometry.computeBoundingSphere();
  20940. }
  20941. setFromObject( object ) {
  20942. this.object = object;
  20943. this.update();
  20944. return this;
  20945. }
  20946. copy( source, recursive ) {
  20947. super.copy( source, recursive );
  20948. this.object = source.object;
  20949. return this;
  20950. }
  20951. dispose() {
  20952. this.geometry.dispose();
  20953. this.material.dispose();
  20954. }
  20955. }
  20956. class Box3Helper extends LineSegments {
  20957. constructor( box, color = 0xffff00 ) {
  20958. 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 ] );
  20959. 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 ];
  20960. const geometry = new BufferGeometry();
  20961. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20962. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20963. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20964. this.box = box;
  20965. this.type = 'Box3Helper';
  20966. this.geometry.computeBoundingSphere();
  20967. }
  20968. updateMatrixWorld( force ) {
  20969. const box = this.box;
  20970. if ( box.isEmpty() ) return;
  20971. box.getCenter( this.position );
  20972. box.getSize( this.scale );
  20973. this.scale.multiplyScalar( 0.5 );
  20974. super.updateMatrixWorld( force );
  20975. }
  20976. dispose() {
  20977. this.geometry.dispose();
  20978. this.material.dispose();
  20979. }
  20980. }
  20981. class PlaneHelper extends Line {
  20982. constructor( plane, size = 1, hex = 0xffff00 ) {
  20983. const color = hex;
  20984. 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 ];
  20985. const geometry = new BufferGeometry();
  20986. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20987. geometry.computeBoundingSphere();
  20988. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20989. this.type = 'PlaneHelper';
  20990. this.plane = plane;
  20991. this.size = size;
  20992. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  20993. const geometry2 = new BufferGeometry();
  20994. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  20995. geometry2.computeBoundingSphere();
  20996. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  20997. }
  20998. updateMatrixWorld( force ) {
  20999. this.position.set( 0, 0, 0 );
  21000. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21001. this.lookAt( this.plane.normal );
  21002. this.translateZ( - this.plane.constant );
  21003. super.updateMatrixWorld( force );
  21004. }
  21005. dispose() {
  21006. this.geometry.dispose();
  21007. this.material.dispose();
  21008. this.children[ 0 ].geometry.dispose();
  21009. this.children[ 0 ].material.dispose();
  21010. }
  21011. }
  21012. const _axis = /*@__PURE__*/ new Vector3();
  21013. let _lineGeometry, _coneGeometry;
  21014. class ArrowHelper extends Object3D {
  21015. // dir is assumed to be normalized
  21016. 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 ) {
  21017. super();
  21018. this.type = 'ArrowHelper';
  21019. if ( _lineGeometry === undefined ) {
  21020. _lineGeometry = new BufferGeometry();
  21021. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21022. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21023. _coneGeometry.translate( 0, - 0.5, 0 );
  21024. }
  21025. this.position.copy( origin );
  21026. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21027. this.line.matrixAutoUpdate = false;
  21028. this.add( this.line );
  21029. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21030. this.cone.matrixAutoUpdate = false;
  21031. this.add( this.cone );
  21032. this.setDirection( dir );
  21033. this.setLength( length, headLength, headWidth );
  21034. }
  21035. setDirection( dir ) {
  21036. // dir is assumed to be normalized
  21037. if ( dir.y > 0.99999 ) {
  21038. this.quaternion.set( 0, 0, 0, 1 );
  21039. } else if ( dir.y < - 0.99999 ) {
  21040. this.quaternion.set( 1, 0, 0, 0 );
  21041. } else {
  21042. _axis.set( dir.z, 0, - dir.x ).normalize();
  21043. const radians = Math.acos( dir.y );
  21044. this.quaternion.setFromAxisAngle( _axis, radians );
  21045. }
  21046. }
  21047. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21048. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21049. this.line.updateMatrix();
  21050. this.cone.scale.set( headWidth, headLength, headWidth );
  21051. this.cone.position.y = length;
  21052. this.cone.updateMatrix();
  21053. }
  21054. setColor( color ) {
  21055. this.line.material.color.set( color );
  21056. this.cone.material.color.set( color );
  21057. }
  21058. copy( source ) {
  21059. super.copy( source, false );
  21060. this.line.copy( source.line );
  21061. this.cone.copy( source.cone );
  21062. return this;
  21063. }
  21064. dispose() {
  21065. this.line.geometry.dispose();
  21066. this.line.material.dispose();
  21067. this.cone.geometry.dispose();
  21068. this.cone.material.dispose();
  21069. }
  21070. }
  21071. class AxesHelper extends LineSegments {
  21072. constructor( size = 1 ) {
  21073. const vertices = [
  21074. 0, 0, 0, size, 0, 0,
  21075. 0, 0, 0, 0, size, 0,
  21076. 0, 0, 0, 0, 0, size
  21077. ];
  21078. const colors = [
  21079. 1, 0, 0, 1, 0.6, 0,
  21080. 0, 1, 0, 0.6, 1, 0,
  21081. 0, 0, 1, 0, 0.6, 1
  21082. ];
  21083. const geometry = new BufferGeometry();
  21084. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21085. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21086. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21087. super( geometry, material );
  21088. this.type = 'AxesHelper';
  21089. }
  21090. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21091. const color = new Color();
  21092. const array = this.geometry.attributes.color.array;
  21093. color.set( xAxisColor );
  21094. color.toArray( array, 0 );
  21095. color.toArray( array, 3 );
  21096. color.set( yAxisColor );
  21097. color.toArray( array, 6 );
  21098. color.toArray( array, 9 );
  21099. color.set( zAxisColor );
  21100. color.toArray( array, 12 );
  21101. color.toArray( array, 15 );
  21102. this.geometry.attributes.color.needsUpdate = true;
  21103. return this;
  21104. }
  21105. dispose() {
  21106. this.geometry.dispose();
  21107. this.material.dispose();
  21108. }
  21109. }
  21110. class ShapePath {
  21111. constructor() {
  21112. this.type = 'ShapePath';
  21113. this.color = new Color();
  21114. this.subPaths = [];
  21115. this.currentPath = null;
  21116. }
  21117. moveTo( x, y ) {
  21118. this.currentPath = new Path();
  21119. this.subPaths.push( this.currentPath );
  21120. this.currentPath.moveTo( x, y );
  21121. return this;
  21122. }
  21123. lineTo( x, y ) {
  21124. this.currentPath.lineTo( x, y );
  21125. return this;
  21126. }
  21127. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21128. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21129. return this;
  21130. }
  21131. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21132. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21133. return this;
  21134. }
  21135. splineThru( pts ) {
  21136. this.currentPath.splineThru( pts );
  21137. return this;
  21138. }
  21139. toShapes( isCCW ) {
  21140. function toShapesNoHoles( inSubpaths ) {
  21141. const shapes = [];
  21142. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21143. const tmpPath = inSubpaths[ i ];
  21144. const tmpShape = new Shape();
  21145. tmpShape.curves = tmpPath.curves;
  21146. shapes.push( tmpShape );
  21147. }
  21148. return shapes;
  21149. }
  21150. function isPointInsidePolygon( inPt, inPolygon ) {
  21151. const polyLen = inPolygon.length;
  21152. // inPt on polygon contour => immediate success or
  21153. // toggling of inside/outside at every single! intersection point of an edge
  21154. // with the horizontal line through inPt, left of inPt
  21155. // not counting lowerY endpoints of edges and whole edges on that line
  21156. let inside = false;
  21157. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21158. let edgeLowPt = inPolygon[ p ];
  21159. let edgeHighPt = inPolygon[ q ];
  21160. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21161. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21162. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21163. // not parallel
  21164. if ( edgeDy < 0 ) {
  21165. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21166. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21167. }
  21168. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21169. if ( inPt.y === edgeLowPt.y ) {
  21170. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21171. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21172. } else {
  21173. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21174. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21175. if ( perpEdge < 0 ) continue;
  21176. inside = ! inside; // true intersection left of inPt
  21177. }
  21178. } else {
  21179. // parallel or collinear
  21180. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21181. // edge lies on the same horizontal line as inPt
  21182. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21183. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21184. // continue;
  21185. }
  21186. }
  21187. return inside;
  21188. }
  21189. const isClockWise = ShapeUtils.isClockWise;
  21190. const subPaths = this.subPaths;
  21191. if ( subPaths.length === 0 ) return [];
  21192. let solid, tmpPath, tmpShape;
  21193. const shapes = [];
  21194. if ( subPaths.length === 1 ) {
  21195. tmpPath = subPaths[ 0 ];
  21196. tmpShape = new Shape();
  21197. tmpShape.curves = tmpPath.curves;
  21198. shapes.push( tmpShape );
  21199. return shapes;
  21200. }
  21201. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21202. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21203. // console.log("Holes first", holesFirst);
  21204. const betterShapeHoles = [];
  21205. const newShapes = [];
  21206. let newShapeHoles = [];
  21207. let mainIdx = 0;
  21208. let tmpPoints;
  21209. newShapes[ mainIdx ] = undefined;
  21210. newShapeHoles[ mainIdx ] = [];
  21211. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21212. tmpPath = subPaths[ i ];
  21213. tmpPoints = tmpPath.getPoints();
  21214. solid = isClockWise( tmpPoints );
  21215. solid = isCCW ? ! solid : solid;
  21216. if ( solid ) {
  21217. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21218. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21219. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21220. if ( holesFirst ) mainIdx ++;
  21221. newShapeHoles[ mainIdx ] = [];
  21222. //console.log('cw', i);
  21223. } else {
  21224. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21225. //console.log('ccw', i);
  21226. }
  21227. }
  21228. // only Holes? -> probably all Shapes with wrong orientation
  21229. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21230. if ( newShapes.length > 1 ) {
  21231. let ambiguous = false;
  21232. let toChange = 0;
  21233. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21234. betterShapeHoles[ sIdx ] = [];
  21235. }
  21236. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21237. const sho = newShapeHoles[ sIdx ];
  21238. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21239. const ho = sho[ hIdx ];
  21240. let hole_unassigned = true;
  21241. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21242. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21243. if ( sIdx !== s2Idx ) toChange ++;
  21244. if ( hole_unassigned ) {
  21245. hole_unassigned = false;
  21246. betterShapeHoles[ s2Idx ].push( ho );
  21247. } else {
  21248. ambiguous = true;
  21249. }
  21250. }
  21251. }
  21252. if ( hole_unassigned ) {
  21253. betterShapeHoles[ sIdx ].push( ho );
  21254. }
  21255. }
  21256. }
  21257. if ( toChange > 0 && ambiguous === false ) {
  21258. newShapeHoles = betterShapeHoles;
  21259. }
  21260. }
  21261. let tmpHoles;
  21262. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21263. tmpShape = newShapes[ i ].s;
  21264. shapes.push( tmpShape );
  21265. tmpHoles = newShapeHoles[ i ];
  21266. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21267. tmpShape.holes.push( tmpHoles[ j ].h );
  21268. }
  21269. }
  21270. //console.log("shape", shapes);
  21271. return shapes;
  21272. }
  21273. }
  21274. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21275. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21276. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21277. super( width, height, { ...options, count } );
  21278. this.isWebGLMultipleRenderTargets = true;
  21279. }
  21280. get texture() {
  21281. return this.textures;
  21282. }
  21283. }
  21284. if ( self.GPUShaderStage === undefined ) {
  21285. self.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  21286. }
  21287. // statics
  21288. let isAvailable = navigator.gpu !== undefined;
  21289. if ( typeof window !== 'undefined' && isAvailable ) {
  21290. isAvailable = await navigator.gpu.requestAdapter();
  21291. }
  21292. class WebGPU {
  21293. static isAvailable() {
  21294. return Boolean( isAvailable );
  21295. }
  21296. static getStaticAdapter() {
  21297. return isAvailable;
  21298. }
  21299. static getErrorMessage() {
  21300. const message = 'Your browser does not support <a href="https://gpuweb.github.io/gpuweb/" style="color:blue">WebGPU</a> yet';
  21301. const element = document.createElement( 'div' );
  21302. element.id = 'webgpumessage';
  21303. element.style.fontFamily = 'monospace';
  21304. element.style.fontSize = '13px';
  21305. element.style.fontWeight = 'normal';
  21306. element.style.textAlign = 'center';
  21307. element.style.background = '#fff';
  21308. element.style.color = '#000';
  21309. element.style.padding = '1.5em';
  21310. element.style.maxWidth = '400px';
  21311. element.style.margin = '5em auto 0';
  21312. element.innerHTML = message;
  21313. return element;
  21314. }
  21315. }
  21316. class Animation {
  21317. constructor( nodes, info ) {
  21318. this.nodes = nodes;
  21319. this.info = info;
  21320. this.animationLoop = null;
  21321. this.requestId = null;
  21322. this._init();
  21323. }
  21324. _init() {
  21325. const update = ( time, frame ) => {
  21326. this.requestId = self.requestAnimationFrame( update );
  21327. if ( this.info.autoReset === true ) this.info.reset();
  21328. this.nodes.nodeFrame.update();
  21329. this.info.frame = this.nodes.nodeFrame.frameId;
  21330. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  21331. };
  21332. update();
  21333. }
  21334. dispose() {
  21335. self.cancelAnimationFrame( this.requestId );
  21336. this.requestId = null;
  21337. }
  21338. setAnimationLoop( callback ) {
  21339. this.animationLoop = callback;
  21340. }
  21341. }
  21342. class ChainMap {
  21343. constructor() {
  21344. this.weakMap = new WeakMap();
  21345. }
  21346. get( keys ) {
  21347. let map = this.weakMap;
  21348. for ( let i = 0; i < keys.length; i ++ ) {
  21349. map = map.get( keys[ i ] );
  21350. if ( map === undefined ) return undefined;
  21351. }
  21352. return map.get( keys[ keys.length - 1 ] );
  21353. }
  21354. set( keys, value ) {
  21355. let map = this.weakMap;
  21356. for ( let i = 0; i < keys.length; i ++ ) {
  21357. const key = keys[ i ];
  21358. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  21359. map = map.get( key );
  21360. }
  21361. return map.set( keys[ keys.length - 1 ], value );
  21362. }
  21363. delete( keys ) {
  21364. let map = this.weakMap;
  21365. for ( let i = 0; i < keys.length; i ++ ) {
  21366. map = map.get( keys[ i ] );
  21367. if ( map === undefined ) return false;
  21368. }
  21369. return map.delete( keys[ keys.length - 1 ] );
  21370. }
  21371. }
  21372. const _plane = new Plane();
  21373. let _clippingContextVersion = 0;
  21374. class ClippingContext {
  21375. constructor() {
  21376. this.version = ++ _clippingContextVersion;
  21377. this.globalClippingCount = 0;
  21378. this.localClippingCount = 0;
  21379. this.localClippingEnabled = false;
  21380. this.localClipIntersection = false;
  21381. this.planes = [];
  21382. this.parentVersion = 0;
  21383. this.viewNormalMatrix = new Matrix3();
  21384. }
  21385. projectPlanes( source, offset ) {
  21386. const l = source.length;
  21387. const planes = this.planes;
  21388. for ( let i = 0; i < l; i ++ ) {
  21389. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  21390. const v = planes[ offset + i ];
  21391. const normal = _plane.normal;
  21392. v.x = - normal.x;
  21393. v.y = - normal.y;
  21394. v.z = - normal.z;
  21395. v.w = _plane.constant;
  21396. }
  21397. }
  21398. updateGlobal( renderer, camera ) {
  21399. const rendererClippingPlanes = renderer.clippingPlanes;
  21400. this.viewMatrix = camera.matrixWorldInverse;
  21401. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  21402. let update = false;
  21403. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  21404. const l = rendererClippingPlanes.length;
  21405. if ( l !== this.globalClippingCount ) {
  21406. const planes = [];
  21407. for ( let i = 0; i < l; i ++ ) {
  21408. planes.push( new Vector4() );
  21409. }
  21410. this.globalClippingCount = l;
  21411. this.planes = planes;
  21412. update = true;
  21413. }
  21414. this.projectPlanes( rendererClippingPlanes, 0 );
  21415. } else if ( this.globalClippingCount !== 0 ) {
  21416. this.globalClippingCount = 0;
  21417. this.planes = [];
  21418. update = true;
  21419. }
  21420. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  21421. this.localClippingEnabled = renderer.localClippingEnabled;
  21422. update = true;
  21423. }
  21424. if ( update ) this.version = _clippingContextVersion ++;
  21425. }
  21426. update( parent, material ) {
  21427. let update = false;
  21428. if ( this !== parent && parent.version !== this.parentVersion ) {
  21429. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  21430. this.localClippingEnabled = parent.localClippingEnabled;
  21431. this.planes = Array.from( parent.planes );
  21432. this.parentVersion = parent.version;
  21433. this.viewMatrix = parent.viewMatrix;
  21434. this.viewNormalMatrix = parent.viewNormalMatrix;
  21435. update = true;
  21436. }
  21437. if ( this.localClippingEnabled ) {
  21438. const localClippingPlanes = material.clippingPlanes;
  21439. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  21440. const l = localClippingPlanes.length;
  21441. const planes = this.planes;
  21442. const offset = this.globalClippingCount;
  21443. if ( update || l !== this.localClippingCount ) {
  21444. planes.length = offset + l;
  21445. for ( let i = 0; i < l; i ++ ) {
  21446. planes[ offset + i ] = new Vector4();
  21447. }
  21448. this.localClippingCount = l;
  21449. update = true;
  21450. }
  21451. this.projectPlanes( localClippingPlanes, offset );
  21452. } else if ( this.localClippingCount !== 0 ) {
  21453. this.localClippingCount = 0;
  21454. update = true;
  21455. }
  21456. if ( this.localClipIntersection !== material.clipIntersection ) {
  21457. this.localClipIntersection = material.clipIntersection;
  21458. update = true;
  21459. }
  21460. }
  21461. if ( update ) this.version = _clippingContextVersion ++;
  21462. }
  21463. }
  21464. let id$4 = 0;
  21465. function getKeys( obj ) {
  21466. const keys = Object.keys( obj );
  21467. let proto = Object.getPrototypeOf( obj );
  21468. while ( proto ) {
  21469. const descriptors = Object.getOwnPropertyDescriptors( proto );
  21470. for ( const key in descriptors ) {
  21471. if ( descriptors[ key ] !== undefined ) {
  21472. const descriptor = descriptors[ key ];
  21473. if ( descriptor && typeof descriptor.get === 'function' ) {
  21474. keys.push( key );
  21475. }
  21476. }
  21477. }
  21478. proto = Object.getPrototypeOf( proto );
  21479. }
  21480. return keys;
  21481. }
  21482. class RenderObject {
  21483. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  21484. this._nodes = nodes;
  21485. this._geometries = geometries;
  21486. this.id = id$4 ++;
  21487. this.renderer = renderer;
  21488. this.object = object;
  21489. this.material = material;
  21490. this.scene = scene;
  21491. this.camera = camera;
  21492. this.lightsNode = lightsNode;
  21493. this.context = renderContext;
  21494. this.geometry = object.geometry;
  21495. this.version = material.version;
  21496. this.drawRange = null;
  21497. this.attributes = null;
  21498. this.pipeline = null;
  21499. this.vertexBuffers = null;
  21500. this.updateClipping( renderContext.clippingContext );
  21501. this.clippingContextVersion = this.clippingContext.version;
  21502. this.initialNodesCacheKey = this.getNodesCacheKey();
  21503. this.initialCacheKey = this.getCacheKey();
  21504. this._nodeBuilderState = null;
  21505. this._bindings = null;
  21506. this.onDispose = null;
  21507. this.isRenderObject = true;
  21508. this.onMaterialDispose = () => {
  21509. this.dispose();
  21510. };
  21511. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  21512. }
  21513. updateClipping( parent ) {
  21514. const material = this.material;
  21515. let clippingContext = this.clippingContext;
  21516. if ( Array.isArray( material.clippingPlanes ) ) {
  21517. if ( clippingContext === parent || ! clippingContext ) {
  21518. clippingContext = new ClippingContext();
  21519. this.clippingContext = clippingContext;
  21520. }
  21521. clippingContext.update( parent, material );
  21522. } else if ( this.clippingContext !== parent ) {
  21523. this.clippingContext = parent;
  21524. }
  21525. }
  21526. get clippingNeedsUpdate() {
  21527. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  21528. this.clippingContextVersion = this.clippingContext.version;
  21529. return true;
  21530. }
  21531. getNodeBuilderState() {
  21532. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21533. }
  21534. getBindings() {
  21535. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21536. }
  21537. getIndex() {
  21538. return this._geometries.getIndex( this );
  21539. }
  21540. getChainArray() {
  21541. return [ this.object, this.material, this.context, this.lightsNode ];
  21542. }
  21543. getAttributes() {
  21544. if ( this.attributes !== null ) return this.attributes;
  21545. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21546. const geometry = this.geometry;
  21547. const attributes = [];
  21548. const vertexBuffers = new Set();
  21549. for ( const nodeAttribute of nodeAttributes ) {
  21550. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  21551. if ( attribute === undefined ) continue;
  21552. attributes.push( attribute );
  21553. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21554. vertexBuffers.add( bufferAttribute );
  21555. }
  21556. this.attributes = attributes;
  21557. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21558. return attributes;
  21559. }
  21560. getVertexBuffers() {
  21561. if ( this.vertexBuffers === null ) this.getAttributes();
  21562. return this.vertexBuffers;
  21563. }
  21564. getMaterialCacheKey() {
  21565. const { object, material } = this;
  21566. let cacheKey = material.customProgramCacheKey();
  21567. for ( const property of getKeys( material ) ) {
  21568. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21569. let value = material[ property ];
  21570. if ( value !== null ) {
  21571. const type = typeof value;
  21572. if ( type === 'number' ) value = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21573. else if ( type === 'object' ) value = '{}';
  21574. }
  21575. cacheKey += /*property + ':' +*/ value + ',';
  21576. }
  21577. cacheKey += this.clippingContextVersion + ',';
  21578. if ( object.skeleton ) {
  21579. cacheKey += object.skeleton.bones.length + ',';
  21580. }
  21581. if ( object.morphTargetInfluences ) {
  21582. cacheKey += object.morphTargetInfluences.length + ',';
  21583. }
  21584. if ( object.isBatchedMesh ) {
  21585. cacheKey += object._matricesTexture.uuid + ',';
  21586. if ( object._colorsTexture !== null ) {
  21587. cacheKey += object._colorsTexture.uuid + ',';
  21588. }
  21589. }
  21590. if ( object.count > 1 ) {
  21591. cacheKey += object.count + ',';
  21592. }
  21593. return cacheKey;
  21594. }
  21595. get needsUpdate() {
  21596. return this.initialNodesCacheKey !== this.getNodesCacheKey() || this.clippingNeedsUpdate;
  21597. }
  21598. getNodesCacheKey() {
  21599. // Environment Nodes Cache Key
  21600. return this._nodes.getCacheKey( this.scene, this.lightsNode );
  21601. }
  21602. getCacheKey() {
  21603. return this.getMaterialCacheKey() + ',' + this.getNodesCacheKey();
  21604. }
  21605. dispose() {
  21606. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21607. this.onDispose();
  21608. }
  21609. }
  21610. class RenderObjects {
  21611. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21612. this.renderer = renderer;
  21613. this.nodes = nodes;
  21614. this.geometries = geometries;
  21615. this.pipelines = pipelines;
  21616. this.bindings = bindings;
  21617. this.info = info;
  21618. this.chainMaps = {};
  21619. }
  21620. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  21621. const chainMap = this.getChainMap( passId );
  21622. const chainArray = [ object, material, renderContext, lightsNode ];
  21623. let renderObject = chainMap.get( chainArray );
  21624. if ( renderObject === undefined ) {
  21625. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  21626. chainMap.set( chainArray, renderObject );
  21627. } else {
  21628. renderObject.updateClipping( renderContext.clippingContext );
  21629. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21630. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21631. renderObject.dispose();
  21632. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  21633. } else {
  21634. renderObject.version = material.version;
  21635. }
  21636. }
  21637. }
  21638. return renderObject;
  21639. }
  21640. getChainMap( passId = 'default' ) {
  21641. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21642. }
  21643. dispose() {
  21644. this.chainMaps = {};
  21645. }
  21646. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  21647. const chainMap = this.getChainMap( passId );
  21648. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  21649. renderObject.onDispose = () => {
  21650. this.pipelines.delete( renderObject );
  21651. this.bindings.delete( renderObject );
  21652. this.nodes.delete( renderObject );
  21653. chainMap.delete( renderObject.getChainArray() );
  21654. };
  21655. return renderObject;
  21656. }
  21657. }
  21658. class DataMap {
  21659. constructor() {
  21660. this.data = new WeakMap();
  21661. }
  21662. get( object ) {
  21663. let map = this.data.get( object );
  21664. if ( map === undefined ) {
  21665. map = {};
  21666. this.data.set( object, map );
  21667. }
  21668. return map;
  21669. }
  21670. delete( object ) {
  21671. let map;
  21672. if ( this.data.has( object ) ) {
  21673. map = this.data.get( object );
  21674. this.data.delete( object );
  21675. }
  21676. return map;
  21677. }
  21678. has( object ) {
  21679. return this.data.has( object );
  21680. }
  21681. dispose() {
  21682. this.data = new WeakMap();
  21683. }
  21684. }
  21685. const AttributeType = {
  21686. VERTEX: 1,
  21687. INDEX: 2,
  21688. STORAGE: 4
  21689. };
  21690. // size of a chunk in bytes (STD140 layout)
  21691. const GPU_CHUNK_BYTES = 16;
  21692. // @TODO: Move to src/constants.js
  21693. const BlendColorFactor = 211;
  21694. const OneMinusBlendColorFactor = 212;
  21695. class Attributes extends DataMap {
  21696. constructor( backend ) {
  21697. super();
  21698. this.backend = backend;
  21699. }
  21700. delete( attribute ) {
  21701. const attributeData = super.delete( attribute );
  21702. if ( attributeData !== undefined ) {
  21703. this.backend.destroyAttribute( attribute );
  21704. }
  21705. return attributeData;
  21706. }
  21707. update( attribute, type ) {
  21708. const data = this.get( attribute );
  21709. if ( data.version === undefined ) {
  21710. if ( type === AttributeType.VERTEX ) {
  21711. this.backend.createAttribute( attribute );
  21712. } else if ( type === AttributeType.INDEX ) {
  21713. this.backend.createIndexAttribute( attribute );
  21714. } else if ( type === AttributeType.STORAGE ) {
  21715. this.backend.createStorageAttribute( attribute );
  21716. }
  21717. data.version = this._getBufferAttribute( attribute ).version;
  21718. } else {
  21719. const bufferAttribute = this._getBufferAttribute( attribute );
  21720. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21721. this.backend.updateAttribute( attribute );
  21722. data.version = bufferAttribute.version;
  21723. }
  21724. }
  21725. }
  21726. _getBufferAttribute( attribute ) {
  21727. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21728. return attribute;
  21729. }
  21730. }
  21731. function arrayNeedsUint32( array ) {
  21732. // assumes larger values usually on last
  21733. for ( let i = array.length - 1; i >= 0; -- i ) {
  21734. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  21735. }
  21736. return false;
  21737. }
  21738. function getWireframeVersion( geometry ) {
  21739. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21740. }
  21741. function getWireframeIndex( geometry ) {
  21742. const indices = [];
  21743. const geometryIndex = geometry.index;
  21744. const geometryPosition = geometry.attributes.position;
  21745. if ( geometryIndex !== null ) {
  21746. const array = geometryIndex.array;
  21747. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21748. const a = array[ i + 0 ];
  21749. const b = array[ i + 1 ];
  21750. const c = array[ i + 2 ];
  21751. indices.push( a, b, b, c, c, a );
  21752. }
  21753. } else {
  21754. const array = geometryPosition.array;
  21755. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21756. const a = i + 0;
  21757. const b = i + 1;
  21758. const c = i + 2;
  21759. indices.push( a, b, b, c, c, a );
  21760. }
  21761. }
  21762. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21763. attribute.version = getWireframeVersion( geometry );
  21764. return attribute;
  21765. }
  21766. class Geometries extends DataMap {
  21767. constructor( attributes, info ) {
  21768. super();
  21769. this.attributes = attributes;
  21770. this.info = info;
  21771. this.wireframes = new WeakMap();
  21772. this.attributeCall = new WeakMap();
  21773. }
  21774. has( renderObject ) {
  21775. const geometry = renderObject.geometry;
  21776. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21777. }
  21778. updateForRender( renderObject ) {
  21779. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21780. this.updateAttributes( renderObject );
  21781. }
  21782. initGeometry( renderObject ) {
  21783. const geometry = renderObject.geometry;
  21784. const geometryData = this.get( geometry );
  21785. geometryData.initialized = true;
  21786. this.info.memory.geometries ++;
  21787. const onDispose = () => {
  21788. this.info.memory.geometries --;
  21789. const index = geometry.index;
  21790. const geometryAttributes = renderObject.getAttributes();
  21791. if ( index !== null ) {
  21792. this.attributes.delete( index );
  21793. }
  21794. for ( const geometryAttribute of geometryAttributes ) {
  21795. this.attributes.delete( geometryAttribute );
  21796. }
  21797. const wireframeAttribute = this.wireframes.get( geometry );
  21798. if ( wireframeAttribute !== undefined ) {
  21799. this.attributes.delete( wireframeAttribute );
  21800. }
  21801. geometry.removeEventListener( 'dispose', onDispose );
  21802. };
  21803. geometry.addEventListener( 'dispose', onDispose );
  21804. }
  21805. updateAttributes( renderObject ) {
  21806. const attributes = renderObject.getAttributes();
  21807. for ( const attribute of attributes ) {
  21808. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21809. this.updateAttribute( attribute, AttributeType.STORAGE );
  21810. } else {
  21811. this.updateAttribute( attribute, AttributeType.VERTEX );
  21812. }
  21813. }
  21814. const index = this.getIndex( renderObject );
  21815. if ( index !== null ) {
  21816. this.updateAttribute( index, AttributeType.INDEX );
  21817. }
  21818. }
  21819. updateAttribute( attribute, type ) {
  21820. const callId = this.info.render.calls;
  21821. if ( ! attribute.isInterleavedBufferAttribute ) {
  21822. if ( this.attributeCall.get( attribute ) !== callId ) {
  21823. this.attributes.update( attribute, type );
  21824. this.attributeCall.set( attribute, callId );
  21825. }
  21826. } else {
  21827. if ( this.attributeCall.get( attribute ) === undefined ) {
  21828. this.attributes.update( attribute, type );
  21829. this.attributeCall.set( attribute, callId );
  21830. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21831. this.attributes.update( attribute, type );
  21832. this.attributeCall.set( attribute.data, callId );
  21833. this.attributeCall.set( attribute, callId );
  21834. }
  21835. }
  21836. }
  21837. getIndex( renderObject ) {
  21838. const { geometry, material } = renderObject;
  21839. let index = geometry.index;
  21840. if ( material.wireframe === true ) {
  21841. const wireframes = this.wireframes;
  21842. let wireframeAttribute = wireframes.get( geometry );
  21843. if ( wireframeAttribute === undefined ) {
  21844. wireframeAttribute = getWireframeIndex( geometry );
  21845. wireframes.set( geometry, wireframeAttribute );
  21846. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21847. this.attributes.delete( wireframeAttribute );
  21848. wireframeAttribute = getWireframeIndex( geometry );
  21849. wireframes.set( geometry, wireframeAttribute );
  21850. }
  21851. index = wireframeAttribute;
  21852. }
  21853. return index;
  21854. }
  21855. }
  21856. class Info {
  21857. constructor() {
  21858. this.autoReset = true;
  21859. this.frame = 0;
  21860. this.calls = 0;
  21861. this.render = {
  21862. calls: 0,
  21863. frameCalls: 0,
  21864. drawCalls: 0,
  21865. triangles: 0,
  21866. points: 0,
  21867. lines: 0,
  21868. timestamp: 0,
  21869. previousFrameCalls: 0,
  21870. timestampCalls: 0
  21871. };
  21872. this.compute = {
  21873. calls: 0,
  21874. frameCalls: 0,
  21875. timestamp: 0,
  21876. previousFrameCalls: 0,
  21877. timestampCalls: 0
  21878. };
  21879. this.memory = {
  21880. geometries: 0,
  21881. textures: 0
  21882. };
  21883. }
  21884. update( object, count, instanceCount ) {
  21885. this.render.drawCalls ++;
  21886. if ( object.isMesh || object.isSprite ) {
  21887. this.render.triangles += instanceCount * ( count / 3 );
  21888. } else if ( object.isPoints ) {
  21889. this.render.points += instanceCount * count;
  21890. } else if ( object.isLineSegments ) {
  21891. this.render.lines += instanceCount * ( count / 2 );
  21892. } else if ( object.isLine ) {
  21893. this.render.lines += instanceCount * ( count - 1 );
  21894. } else {
  21895. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  21896. }
  21897. }
  21898. updateTimestamp( type, time ) {
  21899. if ( this[ type ].timestampCalls === 0 ) {
  21900. this[ type ].timestamp = 0;
  21901. }
  21902. this[ type ].timestamp += time;
  21903. this[ type ].timestampCalls ++;
  21904. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  21905. this[ type ].timestampCalls = 0;
  21906. }
  21907. }
  21908. reset() {
  21909. const previousRenderFrameCalls = this.render.frameCalls;
  21910. this.render.previousFrameCalls = previousRenderFrameCalls;
  21911. const previousComputeFrameCalls = this.compute.frameCalls;
  21912. this.compute.previousFrameCalls = previousComputeFrameCalls;
  21913. this.render.drawCalls = 0;
  21914. this.render.frameCalls = 0;
  21915. this.compute.frameCalls = 0;
  21916. this.render.triangles = 0;
  21917. this.render.points = 0;
  21918. this.render.lines = 0;
  21919. }
  21920. dispose() {
  21921. this.reset();
  21922. this.calls = 0;
  21923. this.render.calls = 0;
  21924. this.compute.calls = 0;
  21925. this.render.timestamp = 0;
  21926. this.compute.timestamp = 0;
  21927. this.memory.geometries = 0;
  21928. this.memory.textures = 0;
  21929. }
  21930. }
  21931. class Pipeline {
  21932. constructor( cacheKey ) {
  21933. this.cacheKey = cacheKey;
  21934. this.usedTimes = 0;
  21935. }
  21936. }
  21937. class RenderPipeline extends Pipeline {
  21938. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21939. super( cacheKey );
  21940. this.vertexProgram = vertexProgram;
  21941. this.fragmentProgram = fragmentProgram;
  21942. }
  21943. }
  21944. class ComputePipeline extends Pipeline {
  21945. constructor( cacheKey, computeProgram ) {
  21946. super( cacheKey );
  21947. this.computeProgram = computeProgram;
  21948. this.isComputePipeline = true;
  21949. }
  21950. }
  21951. let _id$4 = 0;
  21952. class ProgrammableStage {
  21953. constructor( code, type, transforms = null, attributes = null ) {
  21954. this.id = _id$4 ++;
  21955. this.code = code;
  21956. this.stage = type;
  21957. this.transforms = transforms;
  21958. this.attributes = attributes;
  21959. this.usedTimes = 0;
  21960. }
  21961. }
  21962. class Pipelines extends DataMap {
  21963. constructor( backend, nodes ) {
  21964. super();
  21965. this.backend = backend;
  21966. this.nodes = nodes;
  21967. this.bindings = null; // set by the bindings
  21968. this.caches = new Map();
  21969. this.programs = {
  21970. vertex: new Map(),
  21971. fragment: new Map(),
  21972. compute: new Map()
  21973. };
  21974. }
  21975. getForCompute( computeNode, bindings ) {
  21976. const { backend } = this;
  21977. const data = this.get( computeNode );
  21978. if ( this._needsComputeUpdate( computeNode ) ) {
  21979. const previousPipeline = data.pipeline;
  21980. if ( previousPipeline ) {
  21981. previousPipeline.usedTimes --;
  21982. previousPipeline.computeProgram.usedTimes --;
  21983. }
  21984. // get shader
  21985. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21986. // programmable stage
  21987. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21988. if ( stageCompute === undefined ) {
  21989. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21990. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21991. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21992. backend.createProgram( stageCompute );
  21993. }
  21994. // determine compute pipeline
  21995. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21996. let pipeline = this.caches.get( cacheKey );
  21997. if ( pipeline === undefined ) {
  21998. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21999. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22000. }
  22001. // keep track of all used times
  22002. pipeline.usedTimes ++;
  22003. stageCompute.usedTimes ++;
  22004. //
  22005. data.version = computeNode.version;
  22006. data.pipeline = pipeline;
  22007. }
  22008. return data.pipeline;
  22009. }
  22010. getForRender( renderObject, promises = null ) {
  22011. const { backend } = this;
  22012. const data = this.get( renderObject );
  22013. if ( this._needsRenderUpdate( renderObject ) ) {
  22014. const previousPipeline = data.pipeline;
  22015. if ( previousPipeline ) {
  22016. previousPipeline.usedTimes --;
  22017. previousPipeline.vertexProgram.usedTimes --;
  22018. previousPipeline.fragmentProgram.usedTimes --;
  22019. }
  22020. // get shader
  22021. const nodeBuilderState = renderObject.getNodeBuilderState();
  22022. // programmable stages
  22023. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22024. if ( stageVertex === undefined ) {
  22025. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22026. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  22027. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22028. backend.createProgram( stageVertex );
  22029. }
  22030. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22031. if ( stageFragment === undefined ) {
  22032. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22033. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  22034. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22035. backend.createProgram( stageFragment );
  22036. }
  22037. // determine render pipeline
  22038. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22039. let pipeline = this.caches.get( cacheKey );
  22040. if ( pipeline === undefined ) {
  22041. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22042. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22043. } else {
  22044. renderObject.pipeline = pipeline;
  22045. }
  22046. // keep track of all used times
  22047. pipeline.usedTimes ++;
  22048. stageVertex.usedTimes ++;
  22049. stageFragment.usedTimes ++;
  22050. //
  22051. data.pipeline = pipeline;
  22052. }
  22053. return data.pipeline;
  22054. }
  22055. delete( object ) {
  22056. const pipeline = this.get( object ).pipeline;
  22057. if ( pipeline ) {
  22058. // pipeline
  22059. pipeline.usedTimes --;
  22060. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22061. // programs
  22062. if ( pipeline.isComputePipeline ) {
  22063. pipeline.computeProgram.usedTimes --;
  22064. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22065. } else {
  22066. pipeline.fragmentProgram.usedTimes --;
  22067. pipeline.vertexProgram.usedTimes --;
  22068. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22069. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22070. }
  22071. }
  22072. return super.delete( object );
  22073. }
  22074. dispose() {
  22075. super.dispose();
  22076. this.caches = new Map();
  22077. this.programs = {
  22078. vertex: new Map(),
  22079. fragment: new Map(),
  22080. compute: new Map()
  22081. };
  22082. }
  22083. updateForRender( renderObject ) {
  22084. this.getForRender( renderObject );
  22085. }
  22086. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22087. // check for existing pipeline
  22088. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22089. let pipeline = this.caches.get( cacheKey );
  22090. if ( pipeline === undefined ) {
  22091. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22092. this.caches.set( cacheKey, pipeline );
  22093. this.backend.createComputePipeline( pipeline, bindings );
  22094. }
  22095. return pipeline;
  22096. }
  22097. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22098. // check for existing pipeline
  22099. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22100. let pipeline = this.caches.get( cacheKey );
  22101. if ( pipeline === undefined ) {
  22102. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  22103. this.caches.set( cacheKey, pipeline );
  22104. renderObject.pipeline = pipeline;
  22105. this.backend.createRenderPipeline( renderObject, promises );
  22106. }
  22107. return pipeline;
  22108. }
  22109. _getComputeCacheKey( computeNode, stageCompute ) {
  22110. return computeNode.id + ',' + stageCompute.id;
  22111. }
  22112. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22113. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22114. }
  22115. _releasePipeline( pipeline ) {
  22116. this.caches.delete( pipeline.cacheKey );
  22117. }
  22118. _releaseProgram( program ) {
  22119. const code = program.code;
  22120. const stage = program.stage;
  22121. this.programs[ stage ].delete( code );
  22122. }
  22123. _needsComputeUpdate( computeNode ) {
  22124. const data = this.get( computeNode );
  22125. return data.pipeline === undefined || data.version !== computeNode.version;
  22126. }
  22127. _needsRenderUpdate( renderObject ) {
  22128. const data = this.get( renderObject );
  22129. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22130. }
  22131. }
  22132. class Bindings extends DataMap {
  22133. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22134. super();
  22135. this.backend = backend;
  22136. this.textures = textures;
  22137. this.pipelines = pipelines;
  22138. this.attributes = attributes;
  22139. this.nodes = nodes;
  22140. this.info = info;
  22141. this.pipelines.bindings = this; // assign bindings to pipelines
  22142. }
  22143. getForRender( renderObject ) {
  22144. const bindings = renderObject.getBindings();
  22145. for ( const bindGroup of bindings ) {
  22146. const groupData = this.get( bindGroup );
  22147. if ( groupData.bindGroup === undefined ) {
  22148. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22149. this._init( bindGroup );
  22150. this.backend.createBindings( bindGroup, bindings );
  22151. groupData.bindGroup = bindGroup;
  22152. }
  22153. }
  22154. return bindings;
  22155. }
  22156. getForCompute( computeNode ) {
  22157. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22158. for ( const bindGroup of bindings ) {
  22159. const groupData = this.get( bindGroup );
  22160. if ( groupData.bindGroup === undefined ) {
  22161. this._init( bindGroup );
  22162. this.backend.createBindings( bindGroup, bindings );
  22163. groupData.bindGroup = bindGroup;
  22164. }
  22165. }
  22166. return bindings;
  22167. }
  22168. updateForCompute( computeNode ) {
  22169. this._updateBindings( computeNode, this.getForCompute( computeNode ) );
  22170. }
  22171. updateForRender( renderObject ) {
  22172. this._updateBindings( renderObject, this.getForRender( renderObject ) );
  22173. }
  22174. _updateBindings( object, bindings ) {
  22175. for ( const bindGroup of bindings ) {
  22176. this._update( object, bindGroup, bindings );
  22177. }
  22178. }
  22179. _init( bindGroup ) {
  22180. for ( const binding of bindGroup.bindings ) {
  22181. if ( binding.isSampledTexture ) {
  22182. this.textures.updateTexture( binding.texture );
  22183. } else if ( binding.isStorageBuffer ) {
  22184. const attribute = binding.attribute;
  22185. this.attributes.update( attribute, AttributeType.STORAGE );
  22186. }
  22187. }
  22188. }
  22189. _update( object, bindGroup, bindings ) {
  22190. const { backend } = this;
  22191. let needsBindingsUpdate = false;
  22192. // iterate over all bindings and check if buffer updates or a new binding group is required
  22193. for ( const binding of bindGroup.bindings ) {
  22194. if ( binding.isNodeUniformsGroup ) {
  22195. const updated = this.nodes.updateGroup( binding );
  22196. if ( ! updated ) continue;
  22197. }
  22198. if ( binding.isUniformBuffer ) {
  22199. const updated = binding.update();
  22200. if ( updated ) {
  22201. backend.updateBinding( binding );
  22202. }
  22203. } else if ( binding.isSampler ) {
  22204. binding.update();
  22205. } else if ( binding.isSampledTexture ) {
  22206. const texture = binding.texture;
  22207. if ( binding.needsBindingsUpdate ) needsBindingsUpdate = true;
  22208. const updated = binding.update();
  22209. if ( updated ) {
  22210. this.textures.updateTexture( binding.texture );
  22211. }
  22212. const textureData = backend.get( binding.texture );
  22213. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  22214. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  22215. console.error( 'Bindings._update: binding should be available:', binding, updated, binding.texture, binding.textureNode.value );
  22216. this.textures.updateTexture( binding.texture );
  22217. needsBindingsUpdate = true;
  22218. }
  22219. if ( texture.isStorageTexture === true ) {
  22220. const textureData = this.get( texture );
  22221. if ( binding.store === true ) {
  22222. textureData.needsMipmap = true;
  22223. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22224. this.backend.generateMipmaps( texture );
  22225. textureData.needsMipmap = false;
  22226. }
  22227. }
  22228. }
  22229. }
  22230. if ( needsBindingsUpdate === true ) {
  22231. const pipeline = this.pipelines.getForRender( object );
  22232. this.backend.updateBindings( bindGroup, bindings, pipeline );
  22233. }
  22234. }
  22235. }
  22236. const NodeShaderStage = {
  22237. VERTEX: 'vertex',
  22238. FRAGMENT: 'fragment'
  22239. };
  22240. const NodeUpdateType = {
  22241. NONE: 'none',
  22242. FRAME: 'frame',
  22243. RENDER: 'render',
  22244. OBJECT: 'object'
  22245. };
  22246. const NodeType = {
  22247. BOOLEAN: 'bool',
  22248. INTEGER: 'int',
  22249. FLOAT: 'float',
  22250. VECTOR2: 'vec2',
  22251. VECTOR3: 'vec3',
  22252. VECTOR4: 'vec4',
  22253. MATRIX2: 'mat2',
  22254. MATRIX3: 'mat3',
  22255. MATRIX4: 'mat4'
  22256. };
  22257. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22258. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22259. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22260. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22261. function getCacheKey( object, force = false ) {
  22262. let cacheKey = '{';
  22263. if ( object.isNode === true ) {
  22264. cacheKey += object.id;
  22265. }
  22266. for ( const { property, childNode } of getNodeChildren( object ) ) {
  22267. cacheKey += ',' + property.slice( 0, - 4 ) + ':' + childNode.getCacheKey( force );
  22268. }
  22269. cacheKey += '}';
  22270. return cacheKey;
  22271. }
  22272. function* getNodeChildren( node, toJSON = false ) {
  22273. for ( const property in node ) {
  22274. // Ignore private properties.
  22275. if ( property.startsWith( '_' ) === true ) continue;
  22276. const object = node[ property ];
  22277. if ( Array.isArray( object ) === true ) {
  22278. for ( let i = 0; i < object.length; i ++ ) {
  22279. const child = object[ i ];
  22280. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22281. yield { property, index: i, childNode: child };
  22282. }
  22283. }
  22284. } else if ( object && object.isNode === true ) {
  22285. yield { property, childNode: object };
  22286. } else if ( typeof object === 'object' ) {
  22287. for ( const subProperty in object ) {
  22288. const child = object[ subProperty ];
  22289. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22290. yield { property, index: subProperty, childNode: child };
  22291. }
  22292. }
  22293. }
  22294. }
  22295. }
  22296. function getValueType( value ) {
  22297. if ( value === undefined || value === null ) return null;
  22298. const typeOf = typeof value;
  22299. if ( value.isNode === true ) {
  22300. return 'node';
  22301. } else if ( typeOf === 'number' ) {
  22302. return 'float';
  22303. } else if ( typeOf === 'boolean' ) {
  22304. return 'bool';
  22305. } else if ( typeOf === 'string' ) {
  22306. return 'string';
  22307. } else if ( typeOf === 'function' ) {
  22308. return 'shader';
  22309. } else if ( value.isVector2 === true ) {
  22310. return 'vec2';
  22311. } else if ( value.isVector3 === true ) {
  22312. return 'vec3';
  22313. } else if ( value.isVector4 === true ) {
  22314. return 'vec4';
  22315. } else if ( value.isMatrix3 === true ) {
  22316. return 'mat3';
  22317. } else if ( value.isMatrix4 === true ) {
  22318. return 'mat4';
  22319. } else if ( value.isColor === true ) {
  22320. return 'color';
  22321. } else if ( value instanceof ArrayBuffer ) {
  22322. return 'ArrayBuffer';
  22323. }
  22324. return null;
  22325. }
  22326. function getValueFromType( type, ...params ) {
  22327. const last4 = type ? type.slice( - 4 ) : undefined;
  22328. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  22329. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  22330. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  22331. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  22332. }
  22333. if ( type === 'color' ) {
  22334. return new Color( ...params );
  22335. } else if ( last4 === 'vec2' ) {
  22336. return new Vector2( ...params );
  22337. } else if ( last4 === 'vec3' ) {
  22338. return new Vector3( ...params );
  22339. } else if ( last4 === 'vec4' ) {
  22340. return new Vector4( ...params );
  22341. } else if ( last4 === 'mat3' ) {
  22342. return new Matrix3( ...params );
  22343. } else if ( last4 === 'mat4' ) {
  22344. return new Matrix4( ...params );
  22345. } else if ( type === 'bool' ) {
  22346. return params[ 0 ] || false;
  22347. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  22348. return params[ 0 ] || 0;
  22349. } else if ( type === 'string' ) {
  22350. return params[ 0 ] || '';
  22351. } else if ( type === 'ArrayBuffer' ) {
  22352. return base64ToArrayBuffer( params[ 0 ] );
  22353. }
  22354. return null;
  22355. }
  22356. function arrayBufferToBase64( arrayBuffer ) {
  22357. let chars = '';
  22358. const array = new Uint8Array( arrayBuffer );
  22359. for ( let i = 0; i < array.length; i ++ ) {
  22360. chars += String.fromCharCode( array[ i ] );
  22361. }
  22362. return btoa( chars );
  22363. }
  22364. function base64ToArrayBuffer( base64 ) {
  22365. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  22366. }
  22367. var NodeUtils = /*#__PURE__*/Object.freeze({
  22368. __proto__: null,
  22369. arrayBufferToBase64: arrayBufferToBase64,
  22370. base64ToArrayBuffer: base64ToArrayBuffer,
  22371. getCacheKey: getCacheKey,
  22372. getNodeChildren: getNodeChildren,
  22373. getValueFromType: getValueFromType,
  22374. getValueType: getValueType
  22375. });
  22376. const NodeClasses = new Map();
  22377. let _nodeId = 0;
  22378. class Node extends EventDispatcher {
  22379. constructor( nodeType = null ) {
  22380. super();
  22381. this.nodeType = nodeType;
  22382. this.updateType = NodeUpdateType.NONE;
  22383. this.updateBeforeType = NodeUpdateType.NONE;
  22384. this.updateAfterType = NodeUpdateType.NONE;
  22385. this.uuid = MathUtils.generateUUID();
  22386. this.version = 0;
  22387. this._cacheKey = null;
  22388. this._cacheKeyVersion = 0;
  22389. this.global = false;
  22390. this.isNode = true;
  22391. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22392. }
  22393. set needsUpdate( value ) {
  22394. if ( value === true ) {
  22395. this.version ++;
  22396. }
  22397. }
  22398. get type() {
  22399. return this.constructor.type;
  22400. }
  22401. onUpdate( callback, updateType ) {
  22402. this.updateType = updateType;
  22403. this.update = callback.bind( this.getSelf() );
  22404. return this;
  22405. }
  22406. onFrameUpdate( callback ) {
  22407. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22408. }
  22409. onRenderUpdate( callback ) {
  22410. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22411. }
  22412. onObjectUpdate( callback ) {
  22413. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22414. }
  22415. onReference( callback ) {
  22416. this.updateReference = callback.bind( this.getSelf() );
  22417. return this;
  22418. }
  22419. getSelf() {
  22420. // Returns non-node object.
  22421. return this.self || this;
  22422. }
  22423. updateReference( /*state*/ ) {
  22424. return this;
  22425. }
  22426. isGlobal( /*builder*/ ) {
  22427. return this.global;
  22428. }
  22429. * getChildren() {
  22430. for ( const { childNode } of getNodeChildren( this ) ) {
  22431. yield childNode;
  22432. }
  22433. }
  22434. dispose() {
  22435. this.dispatchEvent( { type: 'dispose' } );
  22436. }
  22437. traverse( callback ) {
  22438. callback( this );
  22439. for ( const childNode of this.getChildren() ) {
  22440. childNode.traverse( callback );
  22441. }
  22442. }
  22443. getCacheKey( force = false ) {
  22444. force = force || this.version !== this._cacheKeyVersion;
  22445. if ( force === true || this._cacheKey === null ) {
  22446. this._cacheKey = getCacheKey( this, force );
  22447. this._cacheKeyVersion = this.version;
  22448. }
  22449. return this._cacheKey;
  22450. }
  22451. getHash( /*builder*/ ) {
  22452. return this.uuid;
  22453. }
  22454. getUpdateType() {
  22455. return this.updateType;
  22456. }
  22457. getUpdateBeforeType() {
  22458. return this.updateBeforeType;
  22459. }
  22460. getUpdateAfterType() {
  22461. return this.updateAfterType;
  22462. }
  22463. getElementType( builder ) {
  22464. const type = this.getNodeType( builder );
  22465. const elementType = builder.getElementType( type );
  22466. return elementType;
  22467. }
  22468. getNodeType( builder ) {
  22469. const nodeProperties = builder.getNodeProperties( this );
  22470. if ( nodeProperties.outputNode ) {
  22471. return nodeProperties.outputNode.getNodeType( builder );
  22472. }
  22473. return this.nodeType;
  22474. }
  22475. getShared( builder ) {
  22476. const hash = this.getHash( builder );
  22477. const nodeFromHash = builder.getNodeFromHash( hash );
  22478. return nodeFromHash || this;
  22479. }
  22480. setup( builder ) {
  22481. const nodeProperties = builder.getNodeProperties( this );
  22482. let index = 0;
  22483. for ( const childNode of this.getChildren() ) {
  22484. nodeProperties[ 'node' + index ++ ] = childNode;
  22485. }
  22486. // return a outputNode if exists
  22487. return null;
  22488. }
  22489. construct( builder ) { // @deprecated, r157
  22490. console.warn( 'THREE.Node: construct() is deprecated. Use setup() instead.' );
  22491. return this.setup( builder );
  22492. }
  22493. increaseUsage( builder ) {
  22494. const nodeData = builder.getDataFromNode( this );
  22495. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  22496. return nodeData.usageCount;
  22497. }
  22498. analyze( builder ) {
  22499. const usageCount = this.increaseUsage( builder );
  22500. if ( usageCount === 1 ) {
  22501. // node flow children
  22502. const nodeProperties = builder.getNodeProperties( this );
  22503. for ( const childNode of Object.values( nodeProperties ) ) {
  22504. if ( childNode && childNode.isNode === true ) {
  22505. childNode.build( builder );
  22506. }
  22507. }
  22508. }
  22509. }
  22510. generate( builder, output ) {
  22511. const { outputNode } = builder.getNodeProperties( this );
  22512. if ( outputNode && outputNode.isNode === true ) {
  22513. return outputNode.build( builder, output );
  22514. }
  22515. }
  22516. updateBefore( /*frame*/ ) {
  22517. console.warn( 'Abstract function.' );
  22518. }
  22519. updateAfter( /*frame*/ ) {
  22520. console.warn( 'Abstract function.' );
  22521. }
  22522. update( /*frame*/ ) {
  22523. console.warn( 'Abstract function.' );
  22524. }
  22525. build( builder, output = null ) {
  22526. const refNode = this.getShared( builder );
  22527. if ( this !== refNode ) {
  22528. return refNode.build( builder, output );
  22529. }
  22530. builder.addNode( this );
  22531. builder.addChain( this );
  22532. /* Build stages expected results:
  22533. - "setup" -> Node
  22534. - "analyze" -> null
  22535. - "generate" -> String
  22536. */
  22537. let result = null;
  22538. const buildStage = builder.getBuildStage();
  22539. if ( buildStage === 'setup' ) {
  22540. this.updateReference( builder );
  22541. const properties = builder.getNodeProperties( this );
  22542. if ( properties.initialized !== true ) {
  22543. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22544. properties.initialized = true;
  22545. properties.outputNode = this.setup( builder );
  22546. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  22547. properties.outputNode = builder.stack;
  22548. }
  22549. for ( const childNode of Object.values( properties ) ) {
  22550. if ( childNode && childNode.isNode === true ) {
  22551. childNode.build( builder );
  22552. }
  22553. }
  22554. }
  22555. } else if ( buildStage === 'analyze' ) {
  22556. this.analyze( builder );
  22557. } else if ( buildStage === 'generate' ) {
  22558. const isGenerateOnce = this.generate.length === 1;
  22559. if ( isGenerateOnce ) {
  22560. const type = this.getNodeType( builder );
  22561. const nodeData = builder.getDataFromNode( this );
  22562. result = nodeData.snippet;
  22563. if ( result === undefined ) {
  22564. result = this.generate( builder ) || '';
  22565. nodeData.snippet = result;
  22566. }
  22567. result = builder.format( result, type, output );
  22568. } else {
  22569. result = this.generate( builder, output ) || '';
  22570. }
  22571. }
  22572. builder.removeChain( this );
  22573. return result;
  22574. }
  22575. getSerializeChildren() {
  22576. return getNodeChildren( this );
  22577. }
  22578. serialize( json ) {
  22579. const nodeChildren = this.getSerializeChildren();
  22580. const inputNodes = {};
  22581. for ( const { property, index, childNode } of nodeChildren ) {
  22582. if ( index !== undefined ) {
  22583. if ( inputNodes[ property ] === undefined ) {
  22584. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22585. }
  22586. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22587. } else {
  22588. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22589. }
  22590. }
  22591. if ( Object.keys( inputNodes ).length > 0 ) {
  22592. json.inputNodes = inputNodes;
  22593. }
  22594. }
  22595. deserialize( json ) {
  22596. if ( json.inputNodes !== undefined ) {
  22597. const nodes = json.meta.nodes;
  22598. for ( const property in json.inputNodes ) {
  22599. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22600. const inputArray = [];
  22601. for ( const uuid of json.inputNodes[ property ] ) {
  22602. inputArray.push( nodes[ uuid ] );
  22603. }
  22604. this[ property ] = inputArray;
  22605. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22606. const inputObject = {};
  22607. for ( const subProperty in json.inputNodes[ property ] ) {
  22608. const uuid = json.inputNodes[ property ][ subProperty ];
  22609. inputObject[ subProperty ] = nodes[ uuid ];
  22610. }
  22611. this[ property ] = inputObject;
  22612. } else {
  22613. const uuid = json.inputNodes[ property ];
  22614. this[ property ] = nodes[ uuid ];
  22615. }
  22616. }
  22617. }
  22618. }
  22619. toJSON( meta ) {
  22620. const { uuid, type } = this;
  22621. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22622. if ( isRoot ) {
  22623. meta = {
  22624. textures: {},
  22625. images: {},
  22626. nodes: {}
  22627. };
  22628. }
  22629. // serialize
  22630. let data = meta.nodes[ uuid ];
  22631. if ( data === undefined ) {
  22632. data = {
  22633. uuid,
  22634. type,
  22635. meta,
  22636. metadata: {
  22637. version: 4.6,
  22638. type: 'Node',
  22639. generator: 'Node.toJSON'
  22640. }
  22641. };
  22642. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22643. this.serialize( data );
  22644. delete data.meta;
  22645. }
  22646. // TODO: Copied from Object3D.toJSON
  22647. function extractFromCache( cache ) {
  22648. const values = [];
  22649. for ( const key in cache ) {
  22650. const data = cache[ key ];
  22651. delete data.metadata;
  22652. values.push( data );
  22653. }
  22654. return values;
  22655. }
  22656. if ( isRoot ) {
  22657. const textures = extractFromCache( meta.textures );
  22658. const images = extractFromCache( meta.images );
  22659. const nodes = extractFromCache( meta.nodes );
  22660. if ( textures.length > 0 ) data.textures = textures;
  22661. if ( images.length > 0 ) data.images = images;
  22662. if ( nodes.length > 0 ) data.nodes = nodes;
  22663. }
  22664. return data;
  22665. }
  22666. }
  22667. function addNodeClass( type, nodeClass ) {
  22668. if ( typeof nodeClass !== 'function' || ! type ) throw new Error( `Node class ${ type } is not a class` );
  22669. if ( NodeClasses.has( type ) ) {
  22670. console.warn( `Redefinition of node class ${ type }` );
  22671. return;
  22672. }
  22673. NodeClasses.set( type, nodeClass );
  22674. nodeClass.type = type;
  22675. }
  22676. function createNodeFromType( type ) {
  22677. const Class = NodeClasses.get( type );
  22678. if ( Class !== undefined ) {
  22679. return new Class();
  22680. }
  22681. }
  22682. class TempNode extends Node {
  22683. constructor( type ) {
  22684. super( type );
  22685. this.isTempNode = true;
  22686. }
  22687. hasDependencies( builder ) {
  22688. return builder.getDataFromNode( this ).usageCount > 1;
  22689. }
  22690. build( builder, output ) {
  22691. const buildStage = builder.getBuildStage();
  22692. if ( buildStage === 'generate' ) {
  22693. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22694. const nodeData = builder.getDataFromNode( this );
  22695. if ( nodeData.propertyName !== undefined ) {
  22696. return builder.format( nodeData.propertyName, type, output );
  22697. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22698. const snippet = super.build( builder, type );
  22699. const nodeVar = builder.getVarFromNode( this, null, type );
  22700. const propertyName = builder.getPropertyName( nodeVar );
  22701. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  22702. nodeData.snippet = snippet;
  22703. nodeData.propertyName = propertyName;
  22704. return builder.format( nodeData.propertyName, type, output );
  22705. }
  22706. }
  22707. return super.build( builder, output );
  22708. }
  22709. }
  22710. addNodeClass( 'TempNode', TempNode );
  22711. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  22712. constructor( node, indexNode ) {
  22713. super();
  22714. this.node = node;
  22715. this.indexNode = indexNode;
  22716. this.isArrayElementNode = true;
  22717. }
  22718. getNodeType( builder ) {
  22719. return this.node.getElementType( builder );
  22720. }
  22721. generate( builder ) {
  22722. const nodeSnippet = this.node.build( builder );
  22723. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22724. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22725. }
  22726. }
  22727. addNodeClass( 'ArrayElementNode', ArrayElementNode );
  22728. class ConvertNode extends Node {
  22729. constructor( node, convertTo ) {
  22730. super();
  22731. this.node = node;
  22732. this.convertTo = convertTo;
  22733. }
  22734. getNodeType( builder ) {
  22735. const requestType = this.node.getNodeType( builder );
  22736. let convertTo = null;
  22737. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22738. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22739. convertTo = overloadingType;
  22740. }
  22741. }
  22742. return convertTo;
  22743. }
  22744. serialize( data ) {
  22745. super.serialize( data );
  22746. data.convertTo = this.convertTo;
  22747. }
  22748. deserialize( data ) {
  22749. super.deserialize( data );
  22750. this.convertTo = data.convertTo;
  22751. }
  22752. generate( builder, output ) {
  22753. const node = this.node;
  22754. const type = this.getNodeType( builder );
  22755. const snippet = node.build( builder, type );
  22756. return builder.format( snippet, type, output );
  22757. }
  22758. }
  22759. addNodeClass( 'ConvertNode', ConvertNode );
  22760. class JoinNode extends TempNode {
  22761. constructor( nodes = [], nodeType = null ) {
  22762. super( nodeType );
  22763. this.nodes = nodes;
  22764. }
  22765. getNodeType( builder ) {
  22766. if ( this.nodeType !== null ) {
  22767. return builder.getVectorType( this.nodeType );
  22768. }
  22769. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22770. }
  22771. generate( builder, output ) {
  22772. const type = this.getNodeType( builder );
  22773. const nodes = this.nodes;
  22774. const primitiveType = builder.getComponentType( type );
  22775. const snippetValues = [];
  22776. for ( const input of nodes ) {
  22777. let inputSnippet = input.build( builder );
  22778. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22779. if ( inputPrimitiveType !== primitiveType ) {
  22780. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22781. }
  22782. snippetValues.push( inputSnippet );
  22783. }
  22784. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22785. return builder.format( snippet, type, output );
  22786. }
  22787. }
  22788. addNodeClass( 'JoinNode', JoinNode );
  22789. const stringVectorComponents = vectorComponents.join( '' );
  22790. class SplitNode extends Node {
  22791. constructor( node, components = 'x' ) {
  22792. super();
  22793. this.node = node;
  22794. this.components = components;
  22795. this.isSplitNode = true;
  22796. }
  22797. getVectorLength() {
  22798. let vectorLength = this.components.length;
  22799. for ( const c of this.components ) {
  22800. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22801. }
  22802. return vectorLength;
  22803. }
  22804. getComponentType( builder ) {
  22805. return builder.getComponentType( this.node.getNodeType( builder ) );
  22806. }
  22807. getNodeType( builder ) {
  22808. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22809. }
  22810. generate( builder, output ) {
  22811. const node = this.node;
  22812. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22813. let snippet = null;
  22814. if ( nodeTypeLength > 1 ) {
  22815. let type = null;
  22816. const componentsLength = this.getVectorLength();
  22817. if ( componentsLength >= nodeTypeLength ) {
  22818. // needed expand the input node
  22819. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22820. }
  22821. const nodeSnippet = node.build( builder, type );
  22822. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22823. // unnecessary swizzle
  22824. snippet = builder.format( nodeSnippet, type, output );
  22825. } else {
  22826. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22827. }
  22828. } else {
  22829. // ignore .components if .node returns float/integer
  22830. snippet = node.build( builder, output );
  22831. }
  22832. return snippet;
  22833. }
  22834. serialize( data ) {
  22835. super.serialize( data );
  22836. data.components = this.components;
  22837. }
  22838. deserialize( data ) {
  22839. super.deserialize( data );
  22840. this.components = data.components;
  22841. }
  22842. }
  22843. addNodeClass( 'SplitNode', SplitNode );
  22844. class SetNode extends TempNode {
  22845. constructor( sourceNode, components, targetNode ) {
  22846. super();
  22847. this.sourceNode = sourceNode;
  22848. this.components = components;
  22849. this.targetNode = targetNode;
  22850. }
  22851. getNodeType( builder ) {
  22852. return this.sourceNode.getNodeType( builder );
  22853. }
  22854. generate( builder ) {
  22855. const { sourceNode, components, targetNode } = this;
  22856. const sourceType = this.getNodeType( builder );
  22857. const targetType = builder.getTypeFromLength( components.length );
  22858. const targetSnippet = targetNode.build( builder, targetType );
  22859. const sourceSnippet = sourceNode.build( builder, sourceType );
  22860. const length = builder.getTypeLength( sourceType );
  22861. const snippetValues = [];
  22862. for ( let i = 0; i < length; i ++ ) {
  22863. const component = vectorComponents[ i ];
  22864. if ( component === components[ 0 ] ) {
  22865. snippetValues.push( targetSnippet );
  22866. i += components.length - 1;
  22867. } else {
  22868. snippetValues.push( sourceSnippet + '.' + component );
  22869. }
  22870. }
  22871. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22872. }
  22873. }
  22874. addNodeClass( 'SetNode', SetNode );
  22875. class InputNode extends Node {
  22876. constructor( value, nodeType = null ) {
  22877. super( nodeType );
  22878. this.isInputNode = true;
  22879. this.value = value;
  22880. this.precision = null;
  22881. }
  22882. getNodeType( /*builder*/ ) {
  22883. if ( this.nodeType === null ) {
  22884. return getValueType( this.value );
  22885. }
  22886. return this.nodeType;
  22887. }
  22888. getInputType( builder ) {
  22889. return this.getNodeType( builder );
  22890. }
  22891. setPrecision( precision ) {
  22892. this.precision = precision;
  22893. return this;
  22894. }
  22895. serialize( data ) {
  22896. super.serialize( data );
  22897. data.value = this.value;
  22898. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22899. data.valueType = getValueType( this.value );
  22900. data.nodeType = this.nodeType;
  22901. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22902. data.precision = this.precision;
  22903. }
  22904. deserialize( data ) {
  22905. super.deserialize( data );
  22906. this.nodeType = data.nodeType;
  22907. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22908. this.precision = data.precision || null;
  22909. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22910. }
  22911. generate( /*builder, output*/ ) {
  22912. console.warn( 'Abstract function.' );
  22913. }
  22914. }
  22915. addNodeClass( 'InputNode', InputNode );
  22916. class ConstNode extends InputNode {
  22917. constructor( value, nodeType = null ) {
  22918. super( value, nodeType );
  22919. this.isConstNode = true;
  22920. }
  22921. generateConst( builder ) {
  22922. return builder.generateConst( this.getNodeType( builder ), this.value );
  22923. }
  22924. generate( builder, output ) {
  22925. const type = this.getNodeType( builder );
  22926. return builder.format( this.generateConst( builder ), type, output );
  22927. }
  22928. }
  22929. addNodeClass( 'ConstNode', ConstNode );
  22930. //
  22931. let currentStack = null;
  22932. const NodeElements = new Map(); // @TODO: Currently only a few nodes are added, probably also add others
  22933. function addNodeElement( name, nodeElement ) {
  22934. if ( NodeElements.has( name ) ) {
  22935. console.warn( `Redefinition of node element ${ name }` );
  22936. return;
  22937. }
  22938. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22939. NodeElements.set( name, nodeElement );
  22940. }
  22941. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22942. const shaderNodeHandler = {
  22943. setup( NodeClosure, params ) {
  22944. const inputs = params.shift();
  22945. return NodeClosure( nodeObjects( inputs ), ...params );
  22946. },
  22947. get( node, prop, nodeObj ) {
  22948. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22949. if ( node.isStackNode !== true && prop === 'assign' ) {
  22950. return ( ...params ) => {
  22951. currentStack.assign( nodeObj, ...params );
  22952. return nodeObj;
  22953. };
  22954. } else if ( NodeElements.has( prop ) ) {
  22955. const nodeElement = NodeElements.get( prop );
  22956. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22957. } else if ( prop === 'self' ) {
  22958. return node;
  22959. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22960. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22961. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22962. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22963. // accessing properties ( swizzle )
  22964. prop = parseSwizzle( prop );
  22965. return nodeObject( new SplitNode( nodeObj, prop ) );
  22966. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22967. // set properties ( swizzle )
  22968. prop = parseSwizzle( prop.slice( 3 ).toLowerCase() );
  22969. // sort to xyzw sequence
  22970. prop = prop.split( '' ).sort().join( '' );
  22971. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22972. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22973. // accessing property
  22974. if ( prop === 'width' ) prop = 'x';
  22975. else if ( prop === 'height' ) prop = 'y';
  22976. else if ( prop === 'depth' ) prop = 'z';
  22977. return nodeObject( new SplitNode( node, prop ) );
  22978. } else if ( /^\d+$/.test( prop ) === true ) {
  22979. // accessing array
  22980. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22981. }
  22982. }
  22983. return Reflect.get( node, prop, nodeObj );
  22984. },
  22985. set( node, prop, value, nodeObj ) {
  22986. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22987. // setting properties
  22988. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22989. nodeObj[ prop ].assign( value );
  22990. return true;
  22991. }
  22992. }
  22993. return Reflect.set( node, prop, value, nodeObj );
  22994. }
  22995. };
  22996. const nodeObjectsCacheMap = new WeakMap();
  22997. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22998. const ShaderNodeObject = function ( obj, altType = null ) {
  22999. const type = getValueType( obj );
  23000. if ( type === 'node' ) {
  23001. let nodeObject = nodeObjectsCacheMap.get( obj );
  23002. if ( nodeObject === undefined ) {
  23003. nodeObject = new Proxy( obj, shaderNodeHandler );
  23004. nodeObjectsCacheMap.set( obj, nodeObject );
  23005. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  23006. }
  23007. return nodeObject;
  23008. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  23009. return nodeObject( getConstNode( obj, altType ) );
  23010. } else if ( type === 'shader' ) {
  23011. return tslFn( obj );
  23012. }
  23013. return obj;
  23014. };
  23015. const ShaderNodeObjects = function ( objects, altType = null ) {
  23016. for ( const name in objects ) {
  23017. objects[ name ] = nodeObject( objects[ name ], altType );
  23018. }
  23019. return objects;
  23020. };
  23021. const ShaderNodeArray = function ( array, altType = null ) {
  23022. const len = array.length;
  23023. for ( let i = 0; i < len; i ++ ) {
  23024. array[ i ] = nodeObject( array[ i ], altType );
  23025. }
  23026. return array;
  23027. };
  23028. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  23029. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  23030. if ( scope === null ) {
  23031. return ( ...params ) => {
  23032. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  23033. };
  23034. } else if ( factor !== null ) {
  23035. factor = nodeObject( factor );
  23036. return ( ...params ) => {
  23037. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  23038. };
  23039. } else {
  23040. return ( ...params ) => {
  23041. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  23042. };
  23043. }
  23044. };
  23045. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  23046. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  23047. };
  23048. class ShaderCallNodeInternal extends Node {
  23049. constructor( shaderNode, inputNodes ) {
  23050. super();
  23051. this.shaderNode = shaderNode;
  23052. this.inputNodes = inputNodes;
  23053. }
  23054. getNodeType( builder ) {
  23055. const properties = builder.getNodeProperties( this );
  23056. if ( properties.outputNode === null ) {
  23057. properties.outputNode = this.setupOutput( builder );
  23058. }
  23059. return properties.outputNode.getNodeType( builder );
  23060. }
  23061. call( builder ) {
  23062. const { shaderNode, inputNodes } = this;
  23063. if ( shaderNode.layout ) {
  23064. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  23065. if ( functionNodesCacheMap === undefined ) {
  23066. functionNodesCacheMap = new WeakMap();
  23067. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  23068. }
  23069. let functionNode = functionNodesCacheMap.get( shaderNode );
  23070. if ( functionNode === undefined ) {
  23071. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  23072. functionNodesCacheMap.set( shaderNode, functionNode );
  23073. }
  23074. if ( builder.currentFunctionNode !== null ) {
  23075. builder.currentFunctionNode.includes.push( functionNode );
  23076. }
  23077. return nodeObject( functionNode.call( inputNodes ) );
  23078. }
  23079. const jsFunc = shaderNode.jsFunc;
  23080. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder.stack, builder ) : jsFunc( builder.stack, builder );
  23081. return nodeObject( outputNode );
  23082. }
  23083. setup( builder ) {
  23084. const { outputNode } = builder.getNodeProperties( this );
  23085. return outputNode || this.setupOutput( builder );
  23086. }
  23087. setupOutput( builder ) {
  23088. builder.addStack();
  23089. builder.stack.outputNode = this.call( builder );
  23090. return builder.removeStack();
  23091. }
  23092. generate( builder, output ) {
  23093. const { outputNode } = builder.getNodeProperties( this );
  23094. if ( outputNode === null ) {
  23095. // TSL: It's recommended to use `tslFn` in setup() pass.
  23096. return this.call( builder ).build( builder, output );
  23097. }
  23098. return super.generate( builder, output );
  23099. }
  23100. }
  23101. class ShaderNodeInternal extends Node {
  23102. constructor( jsFunc ) {
  23103. super();
  23104. this.jsFunc = jsFunc;
  23105. this.layout = null;
  23106. this.global = true;
  23107. }
  23108. get isArrayInput() {
  23109. return /^\((\s+)?\[/.test( this.jsFunc.toString() );
  23110. }
  23111. setLayout( layout ) {
  23112. this.layout = layout;
  23113. return this;
  23114. }
  23115. call( inputs = null ) {
  23116. nodeObjects( inputs );
  23117. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  23118. }
  23119. setup() {
  23120. return this.call();
  23121. }
  23122. }
  23123. const bools = [ false, true ];
  23124. const uints = [ 0, 1, 2, 3 ];
  23125. const ints = [ - 1, - 2 ];
  23126. 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 ];
  23127. const boolsCacheMap = new Map();
  23128. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  23129. const uintsCacheMap = new Map();
  23130. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  23131. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  23132. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  23133. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  23134. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  23135. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  23136. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  23137. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  23138. const getConstNode = ( value, type ) => {
  23139. if ( constNodesCacheMap.has( value ) ) {
  23140. return constNodesCacheMap.get( value );
  23141. } else if ( value.isNode === true ) {
  23142. return value;
  23143. } else {
  23144. return new ConstNode( value, type );
  23145. }
  23146. };
  23147. const safeGetNodeType = ( node ) => {
  23148. try {
  23149. return node.getNodeType();
  23150. } catch ( _ ) {
  23151. return undefined;
  23152. }
  23153. };
  23154. const ConvertType = function ( type, cacheMap = null ) {
  23155. return ( ...params ) => {
  23156. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  23157. params = [ getValueFromType( type, ...params ) ];
  23158. }
  23159. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  23160. return nodeObject( cacheMap.get( params[ 0 ] ) );
  23161. }
  23162. if ( params.length === 1 ) {
  23163. const node = getConstNode( params[ 0 ], type );
  23164. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  23165. return nodeObject( new ConvertNode( node, type ) );
  23166. }
  23167. const nodes = params.map( param => getConstNode( param ) );
  23168. return nodeObject( new JoinNode( nodes, type ) );
  23169. };
  23170. };
  23171. // exports
  23172. const defined = ( value ) => value && value.value;
  23173. // utils
  23174. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  23175. // shader node base
  23176. function ShaderNode( jsFunc ) {
  23177. return new Proxy( new ShaderNodeInternal( jsFunc ), shaderNodeHandler );
  23178. }
  23179. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  23180. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  23181. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  23182. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  23183. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  23184. const tslFn = ( jsFunc ) => {
  23185. const shaderNode = new ShaderNode( jsFunc );
  23186. const fn = ( ...params ) => {
  23187. let inputs;
  23188. nodeObjects( params );
  23189. if ( params[ 0 ] && params[ 0 ].isNode ) {
  23190. inputs = [ ...params ];
  23191. } else {
  23192. inputs = params[ 0 ];
  23193. }
  23194. return shaderNode.call( inputs );
  23195. };
  23196. fn.shaderNode = shaderNode;
  23197. fn.setLayout = ( layout ) => {
  23198. shaderNode.setLayout( layout );
  23199. return fn;
  23200. };
  23201. return fn;
  23202. };
  23203. addNodeClass( 'ShaderNode', ShaderNode );
  23204. //
  23205. addNodeElement( 'toGlobal', ( node ) => {
  23206. node.global = true;
  23207. return node;
  23208. } );
  23209. //
  23210. const setCurrentStack = ( stack ) => {
  23211. currentStack = stack;
  23212. };
  23213. const getCurrentStack = () => currentStack;
  23214. const If = ( ...params ) => currentStack.if( ...params );
  23215. function append( node ) {
  23216. if ( currentStack ) currentStack.add( node );
  23217. return node;
  23218. }
  23219. addNodeElement( 'append', append );
  23220. // types
  23221. // @TODO: Maybe export from ConstNode.js?
  23222. const color = new ConvertType( 'color' );
  23223. const float = new ConvertType( 'float', cacheMaps.float );
  23224. const int = new ConvertType( 'int', cacheMaps.ints );
  23225. const uint = new ConvertType( 'uint', cacheMaps.uint );
  23226. const bool = new ConvertType( 'bool', cacheMaps.bool );
  23227. const vec2 = new ConvertType( 'vec2' );
  23228. const ivec2 = new ConvertType( 'ivec2' );
  23229. const uvec2 = new ConvertType( 'uvec2' );
  23230. const bvec2 = new ConvertType( 'bvec2' );
  23231. const vec3 = new ConvertType( 'vec3' );
  23232. const ivec3 = new ConvertType( 'ivec3' );
  23233. const uvec3 = new ConvertType( 'uvec3' );
  23234. const bvec3 = new ConvertType( 'bvec3' );
  23235. const vec4 = new ConvertType( 'vec4' );
  23236. const ivec4 = new ConvertType( 'ivec4' );
  23237. const uvec4 = new ConvertType( 'uvec4' );
  23238. const bvec4 = new ConvertType( 'bvec4' );
  23239. const mat2 = new ConvertType( 'mat2' );
  23240. const imat2 = new ConvertType( 'imat2' );
  23241. const umat2 = new ConvertType( 'umat2' );
  23242. const bmat2 = new ConvertType( 'bmat2' );
  23243. const mat3 = new ConvertType( 'mat3' );
  23244. const imat3 = new ConvertType( 'imat3' );
  23245. const umat3 = new ConvertType( 'umat3' );
  23246. const bmat3 = new ConvertType( 'bmat3' );
  23247. const mat4 = new ConvertType( 'mat4' );
  23248. const imat4 = new ConvertType( 'imat4' );
  23249. const umat4 = new ConvertType( 'umat4' );
  23250. const bmat4 = new ConvertType( 'bmat4' );
  23251. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  23252. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  23253. addNodeElement( 'toColor', color );
  23254. addNodeElement( 'toFloat', float );
  23255. addNodeElement( 'toInt', int );
  23256. addNodeElement( 'toUint', uint );
  23257. addNodeElement( 'toBool', bool );
  23258. addNodeElement( 'toVec2', vec2 );
  23259. addNodeElement( 'toIvec2', ivec2 );
  23260. addNodeElement( 'toUvec2', uvec2 );
  23261. addNodeElement( 'toBvec2', bvec2 );
  23262. addNodeElement( 'toVec3', vec3 );
  23263. addNodeElement( 'toIvec3', ivec3 );
  23264. addNodeElement( 'toUvec3', uvec3 );
  23265. addNodeElement( 'toBvec3', bvec3 );
  23266. addNodeElement( 'toVec4', vec4 );
  23267. addNodeElement( 'toIvec4', ivec4 );
  23268. addNodeElement( 'toUvec4', uvec4 );
  23269. addNodeElement( 'toBvec4', bvec4 );
  23270. addNodeElement( 'toMat2', mat2 );
  23271. addNodeElement( 'toImat2', imat2 );
  23272. addNodeElement( 'toUmat2', umat2 );
  23273. addNodeElement( 'toBmat2', bmat2 );
  23274. addNodeElement( 'toMat3', mat3 );
  23275. addNodeElement( 'toImat3', imat3 );
  23276. addNodeElement( 'toUmat3', umat3 );
  23277. addNodeElement( 'toBmat3', bmat3 );
  23278. addNodeElement( 'toMat4', mat4 );
  23279. addNodeElement( 'toImat4', imat4 );
  23280. addNodeElement( 'toUmat4', umat4 );
  23281. addNodeElement( 'toBmat4', bmat4 );
  23282. // basic nodes
  23283. // HACK - we cannot export them from the corresponding files because of the cyclic dependency
  23284. const element = nodeProxy( ArrayElementNode );
  23285. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  23286. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  23287. addNodeElement( 'element', element );
  23288. addNodeElement( 'convert', convert );
  23289. class AssignNode extends TempNode {
  23290. constructor( targetNode, sourceNode ) {
  23291. super();
  23292. this.targetNode = targetNode;
  23293. this.sourceNode = sourceNode;
  23294. }
  23295. hasDependencies() {
  23296. return false;
  23297. }
  23298. getNodeType( builder, output ) {
  23299. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23300. }
  23301. needsSplitAssign( builder ) {
  23302. const { targetNode } = this;
  23303. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23304. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23305. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23306. return assignDiferentVector;
  23307. }
  23308. return false;
  23309. }
  23310. generate( builder, output ) {
  23311. const { targetNode, sourceNode } = this;
  23312. const needsSplitAssign = this.needsSplitAssign( builder );
  23313. const targetType = targetNode.getNodeType( builder );
  23314. const target = targetNode.context( { assign: true } ).build( builder );
  23315. const source = sourceNode.build( builder, targetType );
  23316. const sourceType = sourceNode.getNodeType( builder );
  23317. const nodeData = builder.getDataFromNode( this );
  23318. //
  23319. let snippet;
  23320. if ( nodeData.initialized === true ) {
  23321. if ( output !== 'void' ) {
  23322. snippet = target;
  23323. }
  23324. } else if ( needsSplitAssign ) {
  23325. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23326. const sourceProperty = builder.getPropertyName( sourceVar );
  23327. builder.addLineFlowCode( `${ sourceProperty } = ${ source }` );
  23328. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23329. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23330. const component = targetNode.components[ i ];
  23331. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` );
  23332. }
  23333. if ( output !== 'void' ) {
  23334. snippet = target;
  23335. }
  23336. } else {
  23337. snippet = `${ target } = ${ source }`;
  23338. if ( output === 'void' || sourceType === 'void' ) {
  23339. builder.addLineFlowCode( snippet );
  23340. if ( output !== 'void' ) {
  23341. snippet = target;
  23342. }
  23343. }
  23344. }
  23345. nodeData.initialized = true;
  23346. return builder.format( snippet, targetType, output );
  23347. }
  23348. }
  23349. const assign = nodeProxy( AssignNode );
  23350. addNodeClass( 'AssignNode', AssignNode );
  23351. addNodeElement( 'assign', assign );
  23352. class VaryingNode extends Node {
  23353. constructor( node, name = null ) {
  23354. super();
  23355. this.node = node;
  23356. this.name = name;
  23357. this.isVaryingNode = true;
  23358. }
  23359. isGlobal() {
  23360. return true;
  23361. }
  23362. getHash( builder ) {
  23363. return this.name || super.getHash( builder );
  23364. }
  23365. getNodeType( builder ) {
  23366. // VaryingNode is auto type
  23367. return this.node.getNodeType( builder );
  23368. }
  23369. setupVarying( builder ) {
  23370. const properties = builder.getNodeProperties( this );
  23371. let varying = properties.varying;
  23372. if ( varying === undefined ) {
  23373. const name = this.name;
  23374. const type = this.getNodeType( builder );
  23375. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23376. properties.node = this.node;
  23377. }
  23378. // this property can be used to check if the varying can be optimized for a variable
  23379. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23380. return varying;
  23381. }
  23382. setup( builder ) {
  23383. this.setupVarying( builder );
  23384. }
  23385. analyze( builder ) {
  23386. this.setupVarying( builder );
  23387. return this.node.analyze( builder );
  23388. }
  23389. generate( builder ) {
  23390. const properties = builder.getNodeProperties( this );
  23391. const varying = this.setupVarying( builder );
  23392. if ( properties.propertyName === undefined ) {
  23393. const type = this.getNodeType( builder );
  23394. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23395. // force node run in vertex stage
  23396. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23397. properties.propertyName = propertyName;
  23398. }
  23399. return builder.getPropertyName( varying );
  23400. }
  23401. }
  23402. const varying = nodeProxy( VaryingNode );
  23403. addNodeElement( 'varying', varying );
  23404. addNodeClass( 'VaryingNode', VaryingNode );
  23405. class AttributeNode extends Node {
  23406. constructor( attributeName, nodeType = null, defaultNode = null ) {
  23407. super( nodeType );
  23408. this.defaultNode = defaultNode;
  23409. this.global = true;
  23410. this._attributeName = attributeName;
  23411. }
  23412. getHash( builder ) {
  23413. return this.getAttributeName( builder );
  23414. }
  23415. getNodeType( builder ) {
  23416. let nodeType = super.getNodeType( builder );
  23417. if ( nodeType === null ) {
  23418. const attributeName = this.getAttributeName( builder );
  23419. if ( builder.hasGeometryAttribute( attributeName ) ) {
  23420. const attribute = builder.geometry.getAttribute( attributeName );
  23421. nodeType = builder.getTypeFromAttribute( attribute );
  23422. } else {
  23423. nodeType = 'float';
  23424. }
  23425. }
  23426. return nodeType;
  23427. }
  23428. setAttributeName( attributeName ) {
  23429. this._attributeName = attributeName;
  23430. return this;
  23431. }
  23432. getAttributeName( /*builder*/ ) {
  23433. return this._attributeName;
  23434. }
  23435. generate( builder ) {
  23436. const attributeName = this.getAttributeName( builder );
  23437. const nodeType = this.getNodeType( builder );
  23438. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  23439. if ( geometryAttribute === true ) {
  23440. const attribute = builder.geometry.getAttribute( attributeName );
  23441. const attributeType = builder.getTypeFromAttribute( attribute );
  23442. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  23443. if ( builder.shaderStage === 'vertex' ) {
  23444. return builder.format( nodeAttribute.name, attributeType, nodeType );
  23445. } else {
  23446. const nodeVarying = varying( this );
  23447. return nodeVarying.build( builder, nodeType );
  23448. }
  23449. } else {
  23450. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  23451. const { defaultNode } = this;
  23452. if ( defaultNode !== null ) {
  23453. return defaultNode.build( builder, nodeType );
  23454. } else {
  23455. return builder.generateConst( nodeType );
  23456. }
  23457. }
  23458. }
  23459. }
  23460. const attribute = ( name, nodeType, defaultNode ) => nodeObject( new AttributeNode( name, nodeType, nodeObject( defaultNode ) ) );
  23461. addNodeClass( 'AttributeNode', AttributeNode );
  23462. class BypassNode extends Node {
  23463. constructor( returnNode, callNode ) {
  23464. super();
  23465. this.isBypassNode = true;
  23466. this.outputNode = returnNode;
  23467. this.callNode = callNode;
  23468. }
  23469. getNodeType( builder ) {
  23470. return this.outputNode.getNodeType( builder );
  23471. }
  23472. generate( builder ) {
  23473. const snippet = this.callNode.build( builder, 'void' );
  23474. if ( snippet !== '' ) {
  23475. builder.addLineFlowCode( snippet );
  23476. }
  23477. return this.outputNode.build( builder );
  23478. }
  23479. }
  23480. const bypass = nodeProxy( BypassNode );
  23481. addNodeElement( 'bypass', bypass );
  23482. addNodeClass( 'BypassNode', BypassNode );
  23483. class CacheNode extends Node {
  23484. constructor( node, parent = true ) {
  23485. super();
  23486. this.node = node;
  23487. this.parent = parent;
  23488. this.isCacheNode = true;
  23489. }
  23490. getNodeType( builder ) {
  23491. return this.node.getNodeType( builder );
  23492. }
  23493. build( builder, ...params ) {
  23494. const previousCache = builder.getCache();
  23495. const cache = builder.getCacheFromNode( this, parent );
  23496. builder.setCache( cache );
  23497. const data = this.node.build( builder, ...params );
  23498. builder.setCache( previousCache );
  23499. return data;
  23500. }
  23501. }
  23502. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23503. addNodeElement( 'cache', cache );
  23504. addNodeClass( 'CacheNode', CacheNode );
  23505. class ContextNode extends Node {
  23506. constructor( node, context = {} ) {
  23507. super();
  23508. this.isContextNode = true;
  23509. this.node = node;
  23510. this.context = context;
  23511. }
  23512. getNodeType( builder ) {
  23513. return this.node.getNodeType( builder );
  23514. }
  23515. analyze( builder ) {
  23516. this.node.build( builder );
  23517. }
  23518. setup( builder ) {
  23519. const previousContext = builder.getContext();
  23520. builder.setContext( { ...builder.context, ...this.context } );
  23521. const node = this.node.build( builder );
  23522. builder.setContext( previousContext );
  23523. return node;
  23524. }
  23525. generate( builder, output ) {
  23526. const previousContext = builder.getContext();
  23527. builder.setContext( { ...builder.context, ...this.context } );
  23528. const snippet = this.node.build( builder, output );
  23529. builder.setContext( previousContext );
  23530. return snippet;
  23531. }
  23532. }
  23533. const context = nodeProxy( ContextNode );
  23534. const label = ( node, name ) => context( node, { label: name } );
  23535. addNodeElement( 'context', context );
  23536. addNodeElement( 'label', label );
  23537. addNodeClass( 'ContextNode', ContextNode );
  23538. class IndexNode extends Node {
  23539. constructor( scope ) {
  23540. super( 'uint' );
  23541. this.scope = scope;
  23542. this.isInstanceIndexNode = true;
  23543. }
  23544. generate( builder ) {
  23545. const nodeType = this.getNodeType( builder );
  23546. const scope = this.scope;
  23547. let propertyName;
  23548. if ( scope === IndexNode.VERTEX ) {
  23549. propertyName = builder.getVertexIndex();
  23550. } else if ( scope === IndexNode.INSTANCE ) {
  23551. propertyName = builder.getInstanceIndex();
  23552. } else if ( scope === IndexNode.DRAW ) {
  23553. propertyName = builder.getDrawIndex();
  23554. } else {
  23555. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  23556. }
  23557. let output;
  23558. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23559. output = propertyName;
  23560. } else {
  23561. const nodeVarying = varying( this );
  23562. output = nodeVarying.build( builder, nodeType );
  23563. }
  23564. return output;
  23565. }
  23566. }
  23567. IndexNode.VERTEX = 'vertex';
  23568. IndexNode.INSTANCE = 'instance';
  23569. IndexNode.DRAW = 'draw';
  23570. const vertexIndex = nodeImmutable( IndexNode, IndexNode.VERTEX );
  23571. const instanceIndex = nodeImmutable( IndexNode, IndexNode.INSTANCE );
  23572. const drawIndex = nodeImmutable( IndexNode, IndexNode.DRAW );
  23573. addNodeClass( 'IndexNode', IndexNode );
  23574. class LightingModel {
  23575. start( /*input, stack, builder*/ ) { }
  23576. finish( /*input, stack, builder*/ ) { }
  23577. direct( /*input, stack, builder*/ ) { }
  23578. directRectArea( /*input, stack, builder*/ ) {}
  23579. indirectDiffuse( /*input, stack, builder*/ ) { }
  23580. indirectSpecular( /*input, stack, builder*/ ) { }
  23581. ambientOcclusion( /*input, stack, builder*/ ) { }
  23582. }
  23583. class VarNode extends Node {
  23584. constructor( node, name = null ) {
  23585. super();
  23586. this.node = node;
  23587. this.name = name;
  23588. this.global = true;
  23589. this.isVarNode = true;
  23590. }
  23591. getHash( builder ) {
  23592. return this.name || super.getHash( builder );
  23593. }
  23594. getNodeType( builder ) {
  23595. return this.node.getNodeType( builder );
  23596. }
  23597. generate( builder ) {
  23598. const { node, name } = this;
  23599. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23600. const propertyName = builder.getPropertyName( nodeVar );
  23601. const snippet = node.build( builder, nodeVar.type );
  23602. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  23603. return propertyName;
  23604. }
  23605. }
  23606. const temp = nodeProxy( VarNode );
  23607. addNodeElement( 'temp', temp ); // @TODO: Will be removed in the future
  23608. addNodeElement( 'toVar', ( ...params ) => temp( ...params ).append() );
  23609. addNodeClass( 'VarNode', VarNode );
  23610. class NodeAttribute {
  23611. constructor( name, type, node = null ) {
  23612. this.isNodeAttribute = true;
  23613. this.name = name;
  23614. this.type = type;
  23615. this.node = node;
  23616. }
  23617. }
  23618. class NodeUniform {
  23619. constructor( name, type, node ) {
  23620. this.isNodeUniform = true;
  23621. this.name = name;
  23622. this.type = type;
  23623. this.node = node.getSelf();
  23624. }
  23625. get value() {
  23626. return this.node.value;
  23627. }
  23628. set value( val ) {
  23629. this.node.value = val;
  23630. }
  23631. get id() {
  23632. return this.node.id;
  23633. }
  23634. get groupNode() {
  23635. return this.node.groupNode;
  23636. }
  23637. }
  23638. class NodeVar {
  23639. constructor( name, type ) {
  23640. this.isNodeVar = true;
  23641. this.name = name;
  23642. this.type = type;
  23643. }
  23644. }
  23645. class NodeVarying extends NodeVar {
  23646. constructor( name, type ) {
  23647. super( name, type );
  23648. this.needsInterpolation = false;
  23649. this.isNodeVarying = true;
  23650. }
  23651. }
  23652. class NodeCode {
  23653. constructor( name, type, code = '' ) {
  23654. this.name = name;
  23655. this.type = type;
  23656. this.code = code;
  23657. Object.defineProperty( this, 'isNodeCode', { value: true } );
  23658. }
  23659. }
  23660. class NodeKeywords {
  23661. constructor() {
  23662. this.keywords = [];
  23663. this.nodes = {};
  23664. this.keywordsCallback = {};
  23665. }
  23666. getNode( name ) {
  23667. let node = this.nodes[ name ];
  23668. if ( node === undefined && this.keywordsCallback[ name ] !== undefined ) {
  23669. node = this.keywordsCallback[ name ]( name );
  23670. this.nodes[ name ] = node;
  23671. }
  23672. return node;
  23673. }
  23674. addKeyword( name, callback ) {
  23675. this.keywords.push( name );
  23676. this.keywordsCallback[ name ] = callback;
  23677. return this;
  23678. }
  23679. parse( code ) {
  23680. const keywordNames = this.keywords;
  23681. const regExp = new RegExp( `\\b${keywordNames.join( '\\b|\\b' )}\\b`, 'g' );
  23682. const codeKeywords = code.match( regExp );
  23683. const keywordNodes = [];
  23684. if ( codeKeywords !== null ) {
  23685. for ( const keyword of codeKeywords ) {
  23686. const node = this.getNode( keyword );
  23687. if ( node !== undefined && keywordNodes.indexOf( node ) === - 1 ) {
  23688. keywordNodes.push( node );
  23689. }
  23690. }
  23691. }
  23692. return keywordNodes;
  23693. }
  23694. include( builder, code ) {
  23695. const keywordNodes = this.parse( code );
  23696. for ( const keywordNode of keywordNodes ) {
  23697. keywordNode.build( builder );
  23698. }
  23699. }
  23700. }
  23701. let id$3 = 0;
  23702. class NodeCache {
  23703. constructor( parent = null ) {
  23704. this.id = id$3 ++;
  23705. this.nodesData = new WeakMap();
  23706. this.parent = parent;
  23707. }
  23708. getData( node ) {
  23709. let data = this.nodesData.get( node );
  23710. if ( data === undefined && this.parent !== null ) {
  23711. data = this.parent.getData( node );
  23712. }
  23713. return data;
  23714. }
  23715. setData( node, data ) {
  23716. this.nodesData.set( node, data );
  23717. }
  23718. }
  23719. class PropertyNode extends Node {
  23720. constructor( nodeType, name = null, varying = false ) {
  23721. super( nodeType );
  23722. this.name = name;
  23723. this.varying = varying;
  23724. this.isPropertyNode = true;
  23725. }
  23726. getHash( builder ) {
  23727. return this.name || super.getHash( builder );
  23728. }
  23729. isGlobal( /*builder*/ ) {
  23730. return true;
  23731. }
  23732. generate( builder ) {
  23733. let nodeVar;
  23734. if ( this.varying === true ) {
  23735. nodeVar = builder.getVaryingFromNode( this, this.name );
  23736. nodeVar.needsInterpolation = true;
  23737. } else {
  23738. nodeVar = builder.getVarFromNode( this, this.name );
  23739. }
  23740. return builder.getPropertyName( nodeVar );
  23741. }
  23742. }
  23743. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23744. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23745. const diffuseColor = nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23746. const roughness = nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23747. const metalness = nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23748. const clearcoat = nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23749. const clearcoatRoughness = nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23750. const sheen = nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23751. const sheenRoughness = nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23752. const iridescence = nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23753. const iridescenceIOR = nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23754. const iridescenceThickness = nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23755. const alphaT = nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23756. const anisotropy = nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23757. const anisotropyT = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23758. const anisotropyB = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23759. const specularColor = nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23760. const specularF90 = nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23761. const shininess = nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23762. const output = nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23763. const dashSize = nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23764. const gapSize = nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23765. const pointWidth = nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23766. const ior = nodeImmutable( PropertyNode, 'float', 'IOR' );
  23767. const transmission = nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23768. const thickness = nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23769. const attenuationDistance = nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23770. const attenuationColor = nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23771. const dispersion = nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23772. addNodeClass( 'PropertyNode', PropertyNode );
  23773. class ParameterNode extends PropertyNode {
  23774. constructor( nodeType, name = null ) {
  23775. super( nodeType, name );
  23776. this.isParameterNode = true;
  23777. }
  23778. getHash() {
  23779. return this.uuid;
  23780. }
  23781. generate() {
  23782. return this.name;
  23783. }
  23784. }
  23785. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23786. addNodeClass( 'ParameterNode', ParameterNode );
  23787. class CodeNode extends Node {
  23788. constructor( code = '', includes = [], language = '' ) {
  23789. super( 'code' );
  23790. this.isCodeNode = true;
  23791. this.code = code;
  23792. this.language = language;
  23793. this.includes = includes;
  23794. }
  23795. isGlobal() {
  23796. return true;
  23797. }
  23798. setIncludes( includes ) {
  23799. this.includes = includes;
  23800. return this;
  23801. }
  23802. getIncludes( /*builder*/ ) {
  23803. return this.includes;
  23804. }
  23805. generate( builder ) {
  23806. const includes = this.getIncludes( builder );
  23807. for ( const include of includes ) {
  23808. include.build( builder );
  23809. }
  23810. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23811. nodeCode.code = this.code;
  23812. return nodeCode.code;
  23813. }
  23814. serialize( data ) {
  23815. super.serialize( data );
  23816. data.code = this.code;
  23817. data.language = this.language;
  23818. }
  23819. deserialize( data ) {
  23820. super.deserialize( data );
  23821. this.code = data.code;
  23822. this.language = data.language;
  23823. }
  23824. }
  23825. const code = nodeProxy( CodeNode );
  23826. const js = ( src, includes ) => code( src, includes, 'js' );
  23827. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23828. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23829. addNodeClass( 'CodeNode', CodeNode );
  23830. class FunctionNode extends CodeNode {
  23831. constructor( code = '', includes = [], language = '' ) {
  23832. super( code, includes, language );
  23833. this.keywords = {};
  23834. }
  23835. getNodeType( builder ) {
  23836. return this.getNodeFunction( builder ).type;
  23837. }
  23838. getInputs( builder ) {
  23839. return this.getNodeFunction( builder ).inputs;
  23840. }
  23841. getNodeFunction( builder ) {
  23842. const nodeData = builder.getDataFromNode( this );
  23843. let nodeFunction = nodeData.nodeFunction;
  23844. if ( nodeFunction === undefined ) {
  23845. nodeFunction = builder.parser.parseFunction( this.code );
  23846. nodeData.nodeFunction = nodeFunction;
  23847. }
  23848. return nodeFunction;
  23849. }
  23850. generate( builder, output ) {
  23851. super.generate( builder );
  23852. const nodeFunction = this.getNodeFunction( builder );
  23853. const name = nodeFunction.name;
  23854. const type = nodeFunction.type;
  23855. const nodeCode = builder.getCodeFromNode( this, type );
  23856. if ( name !== '' ) {
  23857. // use a custom property name
  23858. nodeCode.name = name;
  23859. }
  23860. const propertyName = builder.getPropertyName( nodeCode );
  23861. let code = this.getNodeFunction( builder ).getCode( propertyName );
  23862. const keywords = this.keywords;
  23863. const keywordsProperties = Object.keys( keywords );
  23864. if ( keywordsProperties.length > 0 ) {
  23865. for ( const property of keywordsProperties ) {
  23866. const propertyRegExp = new RegExp( `\\b${property}\\b`, 'g' );
  23867. const nodeProperty = keywords[ property ].build( builder, 'property' );
  23868. code = code.replace( propertyRegExp, nodeProperty );
  23869. }
  23870. }
  23871. nodeCode.code = code + '\n';
  23872. if ( output === 'property' ) {
  23873. return propertyName;
  23874. } else {
  23875. return builder.format( `${ propertyName }()`, type, output );
  23876. }
  23877. }
  23878. }
  23879. const nativeFn = ( code, includes = [], language = '' ) => {
  23880. for ( let i = 0; i < includes.length; i ++ ) {
  23881. const include = includes[ i ];
  23882. // TSL Function: glslFn, wgslFn
  23883. if ( typeof include === 'function' ) {
  23884. includes[ i ] = include.functionNode;
  23885. }
  23886. }
  23887. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23888. const fn = ( ...params ) => functionNode.call( ...params );
  23889. fn.functionNode = functionNode;
  23890. return fn;
  23891. };
  23892. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23893. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23894. addNodeClass( 'FunctionNode', FunctionNode );
  23895. class UniformGroupNode extends Node {
  23896. constructor( name, shared = false ) {
  23897. super( 'string' );
  23898. this.name = name;
  23899. this.version = 0;
  23900. this.shared = shared;
  23901. this.isUniformGroup = true;
  23902. }
  23903. set needsUpdate( value ) {
  23904. if ( value === true ) this.version ++;
  23905. }
  23906. }
  23907. const uniformGroup = ( name ) => new UniformGroupNode( name );
  23908. const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true );
  23909. const frameGroup = sharedUniformGroup( 'frame' );
  23910. const renderGroup = sharedUniformGroup( 'render' );
  23911. const objectGroup = uniformGroup( 'object' );
  23912. addNodeClass( 'UniformGroupNode', UniformGroupNode );
  23913. class UniformNode extends InputNode {
  23914. constructor( value, nodeType = null ) {
  23915. super( value, nodeType );
  23916. this.isUniformNode = true;
  23917. this.name = '';
  23918. this.groupNode = objectGroup;
  23919. }
  23920. label( name ) {
  23921. this.name = name;
  23922. return this;
  23923. }
  23924. setGroup( group ) {
  23925. this.groupNode = group;
  23926. return this;
  23927. }
  23928. getGroup() {
  23929. return this.groupNode;
  23930. }
  23931. getUniformHash( builder ) {
  23932. return this.getHash( builder );
  23933. }
  23934. onUpdate( callback, updateType ) {
  23935. const self = this.getSelf();
  23936. callback = callback.bind( self );
  23937. return super.onUpdate( ( frame ) => {
  23938. const value = callback( frame, self );
  23939. if ( value !== undefined ) {
  23940. this.value = value;
  23941. }
  23942. }, updateType );
  23943. }
  23944. generate( builder, output ) {
  23945. const type = this.getNodeType( builder );
  23946. const hash = this.getUniformHash( builder );
  23947. let sharedNode = builder.getNodeFromHash( hash );
  23948. if ( sharedNode === undefined ) {
  23949. builder.setHashNode( this, hash );
  23950. sharedNode = this;
  23951. }
  23952. const sharedNodeType = sharedNode.getInputType( builder );
  23953. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  23954. const propertyName = builder.getPropertyName( nodeUniform );
  23955. if ( builder.context.label !== undefined ) delete builder.context.label;
  23956. return builder.format( propertyName, type, output );
  23957. }
  23958. }
  23959. const uniform = ( arg1, arg2 ) => {
  23960. const nodeType = getConstNodeType( arg2 || arg1 );
  23961. // @TODO: get ConstNode from .traverse() in the future
  23962. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  23963. return nodeObject( new UniformNode( value, nodeType ) );
  23964. };
  23965. addNodeClass( 'UniformNode', UniformNode );
  23966. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  23967. class TextureSizeNode extends Node {
  23968. constructor( textureNode, levelNode = null ) {
  23969. super( 'uvec2' );
  23970. this.isTextureSizeNode = true;
  23971. this.textureNode = textureNode;
  23972. this.levelNode = levelNode;
  23973. }
  23974. generate( builder, output ) {
  23975. const textureProperty = this.textureNode.build( builder, 'property' );
  23976. const levelNode = this.levelNode.build( builder, 'int' );
  23977. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ levelNode } )`, this.getNodeType( builder ), output );
  23978. }
  23979. }
  23980. const textureSize = nodeProxy( TextureSizeNode );
  23981. addNodeElement( 'textureSize', textureSize );
  23982. addNodeClass( 'TextureSizeNode', TextureSizeNode );
  23983. class OperatorNode extends TempNode {
  23984. constructor( op, aNode, bNode, ...params ) {
  23985. super();
  23986. if ( params.length > 0 ) {
  23987. let finalOp = new OperatorNode( op, aNode, bNode );
  23988. for ( let i = 0; i < params.length - 1; i ++ ) {
  23989. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  23990. }
  23991. aNode = finalOp;
  23992. bNode = params[ params.length - 1 ];
  23993. }
  23994. this.op = op;
  23995. this.aNode = aNode;
  23996. this.bNode = bNode;
  23997. }
  23998. getNodeType( builder, output ) {
  23999. const op = this.op;
  24000. const aNode = this.aNode;
  24001. const bNode = this.bNode;
  24002. const typeA = aNode.getNodeType( builder );
  24003. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24004. if ( typeA === 'void' || typeB === 'void' ) {
  24005. return 'void';
  24006. } else if ( op === '%' ) {
  24007. return typeA;
  24008. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  24009. return builder.getIntegerType( typeA );
  24010. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  24011. return 'bool';
  24012. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  24013. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  24014. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  24015. } else {
  24016. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  24017. return typeB;
  24018. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24019. // matrix x vector
  24020. return builder.getVectorFromMatrix( typeA );
  24021. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24022. // vector x matrix
  24023. return builder.getVectorFromMatrix( typeB );
  24024. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  24025. // anytype x anytype: use the greater length vector
  24026. return typeB;
  24027. }
  24028. return typeA;
  24029. }
  24030. }
  24031. generate( builder, output ) {
  24032. const op = this.op;
  24033. const aNode = this.aNode;
  24034. const bNode = this.bNode;
  24035. const type = this.getNodeType( builder, output );
  24036. let typeA = null;
  24037. let typeB = null;
  24038. if ( type !== 'void' ) {
  24039. typeA = aNode.getNodeType( builder );
  24040. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24041. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  24042. if ( builder.isVector( typeA ) ) {
  24043. typeB = typeA;
  24044. } else {
  24045. typeA = typeB = 'float';
  24046. }
  24047. } else if ( op === '>>' || op === '<<' ) {
  24048. typeA = type;
  24049. typeB = builder.changeComponentType( typeB, 'uint' );
  24050. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24051. // matrix x vector
  24052. typeB = builder.getVectorFromMatrix( typeA );
  24053. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24054. // vector x matrix
  24055. typeA = builder.getVectorFromMatrix( typeB );
  24056. } else {
  24057. // anytype x anytype
  24058. typeA = typeB = type;
  24059. }
  24060. } else {
  24061. typeA = typeB = type;
  24062. }
  24063. const a = aNode.build( builder, typeA );
  24064. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  24065. const outputLength = builder.getTypeLength( output );
  24066. const fnOpSnippet = builder.getFunctionOperator( op );
  24067. if ( output !== 'void' ) {
  24068. if ( op === '<' && outputLength > 1 ) {
  24069. return builder.format( `${ builder.getMethod( 'lessThan' ) }( ${ a }, ${ b } )`, type, output );
  24070. } else if ( op === '<=' && outputLength > 1 ) {
  24071. return builder.format( `${ builder.getMethod( 'lessThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24072. } else if ( op === '>' && outputLength > 1 ) {
  24073. return builder.format( `${ builder.getMethod( 'greaterThan' ) }( ${ a }, ${ b } )`, type, output );
  24074. } else if ( op === '>=' && outputLength > 1 ) {
  24075. return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24076. } else if ( op === '!' || op === '~' ) {
  24077. return builder.format( `(${op}${a})`, typeA, output );
  24078. } else if ( fnOpSnippet ) {
  24079. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24080. } else {
  24081. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  24082. }
  24083. } else if ( typeA !== 'void' ) {
  24084. if ( fnOpSnippet ) {
  24085. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24086. } else {
  24087. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  24088. }
  24089. }
  24090. }
  24091. serialize( data ) {
  24092. super.serialize( data );
  24093. data.op = this.op;
  24094. }
  24095. deserialize( data ) {
  24096. super.deserialize( data );
  24097. this.op = data.op;
  24098. }
  24099. }
  24100. const add = nodeProxy( OperatorNode, '+' );
  24101. const sub = nodeProxy( OperatorNode, '-' );
  24102. const mul = nodeProxy( OperatorNode, '*' );
  24103. const div = nodeProxy( OperatorNode, '/' );
  24104. const remainder = nodeProxy( OperatorNode, '%' );
  24105. const equal = nodeProxy( OperatorNode, '==' );
  24106. const notEqual = nodeProxy( OperatorNode, '!=' );
  24107. const lessThan = nodeProxy( OperatorNode, '<' );
  24108. const greaterThan = nodeProxy( OperatorNode, '>' );
  24109. const lessThanEqual = nodeProxy( OperatorNode, '<=' );
  24110. const greaterThanEqual = nodeProxy( OperatorNode, '>=' );
  24111. const and = nodeProxy( OperatorNode, '&&' );
  24112. const or = nodeProxy( OperatorNode, '||' );
  24113. const not = nodeProxy( OperatorNode, '!' );
  24114. const xor = nodeProxy( OperatorNode, '^^' );
  24115. const bitAnd = nodeProxy( OperatorNode, '&' );
  24116. const bitNot = nodeProxy( OperatorNode, '~' );
  24117. const bitOr = nodeProxy( OperatorNode, '|' );
  24118. const bitXor = nodeProxy( OperatorNode, '^' );
  24119. const shiftLeft = nodeProxy( OperatorNode, '<<' );
  24120. const shiftRight = nodeProxy( OperatorNode, '>>' );
  24121. addNodeElement( 'add', add );
  24122. addNodeElement( 'sub', sub );
  24123. addNodeElement( 'mul', mul );
  24124. addNodeElement( 'div', div );
  24125. addNodeElement( 'remainder', remainder );
  24126. addNodeElement( 'equal', equal );
  24127. addNodeElement( 'notEqual', notEqual );
  24128. addNodeElement( 'lessThan', lessThan );
  24129. addNodeElement( 'greaterThan', greaterThan );
  24130. addNodeElement( 'lessThanEqual', lessThanEqual );
  24131. addNodeElement( 'greaterThanEqual', greaterThanEqual );
  24132. addNodeElement( 'and', and );
  24133. addNodeElement( 'or', or );
  24134. addNodeElement( 'not', not );
  24135. addNodeElement( 'xor', xor );
  24136. addNodeElement( 'bitAnd', bitAnd );
  24137. addNodeElement( 'bitNot', bitNot );
  24138. addNodeElement( 'bitOr', bitOr );
  24139. addNodeElement( 'bitXor', bitXor );
  24140. addNodeElement( 'shiftLeft', shiftLeft );
  24141. addNodeElement( 'shiftRight', shiftRight );
  24142. addNodeClass( 'OperatorNode', OperatorNode );
  24143. class MathNode extends TempNode {
  24144. constructor( method, aNode, bNode = null, cNode = null ) {
  24145. super();
  24146. this.method = method;
  24147. this.aNode = aNode;
  24148. this.bNode = bNode;
  24149. this.cNode = cNode;
  24150. }
  24151. getInputType( builder ) {
  24152. const aType = this.aNode.getNodeType( builder );
  24153. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  24154. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  24155. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  24156. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  24157. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  24158. if ( aLen > bLen && aLen > cLen ) {
  24159. return aType;
  24160. } else if ( bLen > cLen ) {
  24161. return bType;
  24162. } else if ( cLen > aLen ) {
  24163. return cType;
  24164. }
  24165. return aType;
  24166. }
  24167. getNodeType( builder ) {
  24168. const method = this.method;
  24169. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  24170. return 'float';
  24171. } else if ( method === MathNode.CROSS ) {
  24172. return 'vec3';
  24173. } else if ( method === MathNode.ALL ) {
  24174. return 'bool';
  24175. } else if ( method === MathNode.EQUALS ) {
  24176. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  24177. } else if ( method === MathNode.MOD ) {
  24178. return this.aNode.getNodeType( builder );
  24179. } else {
  24180. return this.getInputType( builder );
  24181. }
  24182. }
  24183. generate( builder, output ) {
  24184. const method = this.method;
  24185. const type = this.getNodeType( builder );
  24186. const inputType = this.getInputType( builder );
  24187. const a = this.aNode;
  24188. const b = this.bNode;
  24189. const c = this.cNode;
  24190. const isWebGL = builder.renderer.isWebGLRenderer === true;
  24191. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  24192. // dir can be either a direction vector or a normal vector
  24193. // upper-left 3x3 of matrix is assumed to be orthogonal
  24194. let tA = a;
  24195. let tB = b;
  24196. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  24197. tB = vec4( vec3( tB ), 0.0 );
  24198. } else {
  24199. tA = vec4( vec3( tA ), 0.0 );
  24200. }
  24201. const mulNode = mul( tA, tB ).xyz;
  24202. return normalize( mulNode ).build( builder, output );
  24203. } else if ( method === MathNode.NEGATE ) {
  24204. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  24205. } else if ( method === MathNode.ONE_MINUS ) {
  24206. return sub( 1.0, a ).build( builder, output );
  24207. } else if ( method === MathNode.RECIPROCAL ) {
  24208. return div( 1.0, a ).build( builder, output );
  24209. } else if ( method === MathNode.DIFFERENCE ) {
  24210. return abs( sub( a, b ) ).build( builder, output );
  24211. } else {
  24212. const params = [];
  24213. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  24214. params.push(
  24215. a.build( builder, type ),
  24216. b.build( builder, type )
  24217. );
  24218. } else if ( method === MathNode.STEP ) {
  24219. params.push(
  24220. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  24221. b.build( builder, inputType )
  24222. );
  24223. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  24224. params.push(
  24225. a.build( builder, inputType ),
  24226. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24227. );
  24228. } else if ( method === MathNode.REFRACT ) {
  24229. params.push(
  24230. a.build( builder, inputType ),
  24231. b.build( builder, inputType ),
  24232. c.build( builder, 'float' )
  24233. );
  24234. } else if ( method === MathNode.MIX ) {
  24235. params.push(
  24236. a.build( builder, inputType ),
  24237. b.build( builder, inputType ),
  24238. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24239. );
  24240. } else {
  24241. params.push( a.build( builder, inputType ) );
  24242. if ( b !== null ) params.push( b.build( builder, inputType ) );
  24243. if ( c !== null ) params.push( c.build( builder, inputType ) );
  24244. }
  24245. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  24246. }
  24247. }
  24248. serialize( data ) {
  24249. super.serialize( data );
  24250. data.method = this.method;
  24251. }
  24252. deserialize( data ) {
  24253. super.deserialize( data );
  24254. this.method = data.method;
  24255. }
  24256. }
  24257. // 1 input
  24258. MathNode.ALL = 'all';
  24259. MathNode.ANY = 'any';
  24260. MathNode.EQUALS = 'equals';
  24261. MathNode.RADIANS = 'radians';
  24262. MathNode.DEGREES = 'degrees';
  24263. MathNode.EXP = 'exp';
  24264. MathNode.EXP2 = 'exp2';
  24265. MathNode.LOG = 'log';
  24266. MathNode.LOG2 = 'log2';
  24267. MathNode.SQRT = 'sqrt';
  24268. MathNode.INVERSE_SQRT = 'inversesqrt';
  24269. MathNode.FLOOR = 'floor';
  24270. MathNode.CEIL = 'ceil';
  24271. MathNode.NORMALIZE = 'normalize';
  24272. MathNode.FRACT = 'fract';
  24273. MathNode.SIN = 'sin';
  24274. MathNode.COS = 'cos';
  24275. MathNode.TAN = 'tan';
  24276. MathNode.ASIN = 'asin';
  24277. MathNode.ACOS = 'acos';
  24278. MathNode.ATAN = 'atan';
  24279. MathNode.ABS = 'abs';
  24280. MathNode.SIGN = 'sign';
  24281. MathNode.LENGTH = 'length';
  24282. MathNode.NEGATE = 'negate';
  24283. MathNode.ONE_MINUS = 'oneMinus';
  24284. MathNode.DFDX = 'dFdx';
  24285. MathNode.DFDY = 'dFdy';
  24286. MathNode.ROUND = 'round';
  24287. MathNode.RECIPROCAL = 'reciprocal';
  24288. MathNode.TRUNC = 'trunc';
  24289. MathNode.FWIDTH = 'fwidth';
  24290. MathNode.BITCAST = 'bitcast';
  24291. MathNode.TRANSPOSE = 'transpose';
  24292. // 2 inputs
  24293. MathNode.ATAN2 = 'atan2';
  24294. MathNode.MIN = 'min';
  24295. MathNode.MAX = 'max';
  24296. MathNode.MOD = 'mod';
  24297. MathNode.STEP = 'step';
  24298. MathNode.REFLECT = 'reflect';
  24299. MathNode.DISTANCE = 'distance';
  24300. MathNode.DIFFERENCE = 'difference';
  24301. MathNode.DOT = 'dot';
  24302. MathNode.CROSS = 'cross';
  24303. MathNode.POW = 'pow';
  24304. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  24305. // 3 inputs
  24306. MathNode.MIX = 'mix';
  24307. MathNode.CLAMP = 'clamp';
  24308. MathNode.REFRACT = 'refract';
  24309. MathNode.SMOOTHSTEP = 'smoothstep';
  24310. MathNode.FACEFORWARD = 'faceforward';
  24311. const EPSILON = float( 1e-6 );
  24312. const INFINITY = float( 1e6 );
  24313. const PI = float( Math.PI );
  24314. const PI2 = float( Math.PI * 2 );
  24315. const all = nodeProxy( MathNode, MathNode.ALL );
  24316. const any = nodeProxy( MathNode, MathNode.ANY );
  24317. const equals = nodeProxy( MathNode, MathNode.EQUALS );
  24318. const radians = nodeProxy( MathNode, MathNode.RADIANS );
  24319. const degrees = nodeProxy( MathNode, MathNode.DEGREES );
  24320. const exp = nodeProxy( MathNode, MathNode.EXP );
  24321. const exp2 = nodeProxy( MathNode, MathNode.EXP2 );
  24322. const log = nodeProxy( MathNode, MathNode.LOG );
  24323. const log2 = nodeProxy( MathNode, MathNode.LOG2 );
  24324. const sqrt = nodeProxy( MathNode, MathNode.SQRT );
  24325. const inverseSqrt = nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  24326. const floor = nodeProxy( MathNode, MathNode.FLOOR );
  24327. const ceil = nodeProxy( MathNode, MathNode.CEIL );
  24328. const normalize = nodeProxy( MathNode, MathNode.NORMALIZE );
  24329. const fract = nodeProxy( MathNode, MathNode.FRACT );
  24330. const sin = nodeProxy( MathNode, MathNode.SIN );
  24331. const cos = nodeProxy( MathNode, MathNode.COS );
  24332. const tan = nodeProxy( MathNode, MathNode.TAN );
  24333. const asin = nodeProxy( MathNode, MathNode.ASIN );
  24334. const acos = nodeProxy( MathNode, MathNode.ACOS );
  24335. const atan = nodeProxy( MathNode, MathNode.ATAN );
  24336. const abs = nodeProxy( MathNode, MathNode.ABS );
  24337. const sign = nodeProxy( MathNode, MathNode.SIGN );
  24338. const length = nodeProxy( MathNode, MathNode.LENGTH );
  24339. const negate = nodeProxy( MathNode, MathNode.NEGATE );
  24340. const oneMinus = nodeProxy( MathNode, MathNode.ONE_MINUS );
  24341. const dFdx = nodeProxy( MathNode, MathNode.DFDX );
  24342. const dFdy = nodeProxy( MathNode, MathNode.DFDY );
  24343. const round = nodeProxy( MathNode, MathNode.ROUND );
  24344. const reciprocal = nodeProxy( MathNode, MathNode.RECIPROCAL );
  24345. const trunc = nodeProxy( MathNode, MathNode.TRUNC );
  24346. const fwidth = nodeProxy( MathNode, MathNode.FWIDTH );
  24347. const bitcast = nodeProxy( MathNode, MathNode.BITCAST );
  24348. const transpose = nodeProxy( MathNode, MathNode.TRANSPOSE );
  24349. const atan2 = nodeProxy( MathNode, MathNode.ATAN2 );
  24350. const min$1 = nodeProxy( MathNode, MathNode.MIN );
  24351. const max$1 = nodeProxy( MathNode, MathNode.MAX );
  24352. const mod = nodeProxy( MathNode, MathNode.MOD );
  24353. const step = nodeProxy( MathNode, MathNode.STEP );
  24354. const reflect = nodeProxy( MathNode, MathNode.REFLECT );
  24355. const distance = nodeProxy( MathNode, MathNode.DISTANCE );
  24356. const difference = nodeProxy( MathNode, MathNode.DIFFERENCE );
  24357. const dot = nodeProxy( MathNode, MathNode.DOT );
  24358. const cross = nodeProxy( MathNode, MathNode.CROSS );
  24359. const pow = nodeProxy( MathNode, MathNode.POW );
  24360. const pow2 = nodeProxy( MathNode, MathNode.POW, 2 );
  24361. const pow3 = nodeProxy( MathNode, MathNode.POW, 3 );
  24362. const pow4 = nodeProxy( MathNode, MathNode.POW, 4 );
  24363. const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  24364. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  24365. const lengthSq = ( a ) => dot( a, a );
  24366. const mix = nodeProxy( MathNode, MathNode.MIX );
  24367. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  24368. const saturate = ( value ) => clamp( value );
  24369. const refract = nodeProxy( MathNode, MathNode.REFRACT );
  24370. const smoothstep = nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  24371. const faceForward = nodeProxy( MathNode, MathNode.FACEFORWARD );
  24372. const rand = tslFn( ( [ uv ] ) => {
  24373. const a = 12.9898, b = 78.233, c = 43758.5453;
  24374. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  24375. return fract( sin( sn ).mul( c ) );
  24376. } );
  24377. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  24378. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  24379. addNodeElement( 'all', all );
  24380. addNodeElement( 'any', any );
  24381. addNodeElement( 'equals', equals );
  24382. addNodeElement( 'radians', radians );
  24383. addNodeElement( 'degrees', degrees );
  24384. addNodeElement( 'exp', exp );
  24385. addNodeElement( 'exp2', exp2 );
  24386. addNodeElement( 'log', log );
  24387. addNodeElement( 'log2', log2 );
  24388. addNodeElement( 'sqrt', sqrt );
  24389. addNodeElement( 'inverseSqrt', inverseSqrt );
  24390. addNodeElement( 'floor', floor );
  24391. addNodeElement( 'ceil', ceil );
  24392. addNodeElement( 'normalize', normalize );
  24393. addNodeElement( 'fract', fract );
  24394. addNodeElement( 'sin', sin );
  24395. addNodeElement( 'cos', cos );
  24396. addNodeElement( 'tan', tan );
  24397. addNodeElement( 'asin', asin );
  24398. addNodeElement( 'acos', acos );
  24399. addNodeElement( 'atan', atan );
  24400. addNodeElement( 'abs', abs );
  24401. addNodeElement( 'sign', sign );
  24402. addNodeElement( 'length', length );
  24403. addNodeElement( 'lengthSq', lengthSq );
  24404. addNodeElement( 'negate', negate );
  24405. addNodeElement( 'oneMinus', oneMinus );
  24406. addNodeElement( 'dFdx', dFdx );
  24407. addNodeElement( 'dFdy', dFdy );
  24408. addNodeElement( 'round', round );
  24409. addNodeElement( 'reciprocal', reciprocal );
  24410. addNodeElement( 'trunc', trunc );
  24411. addNodeElement( 'fwidth', fwidth );
  24412. addNodeElement( 'atan2', atan2 );
  24413. addNodeElement( 'min', min$1 );
  24414. addNodeElement( 'max', max$1 );
  24415. addNodeElement( 'mod', mod );
  24416. addNodeElement( 'step', step );
  24417. addNodeElement( 'reflect', reflect );
  24418. addNodeElement( 'distance', distance );
  24419. addNodeElement( 'dot', dot );
  24420. addNodeElement( 'cross', cross );
  24421. addNodeElement( 'pow', pow );
  24422. addNodeElement( 'pow2', pow2 );
  24423. addNodeElement( 'pow3', pow3 );
  24424. addNodeElement( 'pow4', pow4 );
  24425. addNodeElement( 'transformDirection', transformDirection );
  24426. addNodeElement( 'mix', mixElement );
  24427. addNodeElement( 'clamp', clamp );
  24428. addNodeElement( 'refract', refract );
  24429. addNodeElement( 'smoothstep', smoothstepElement );
  24430. addNodeElement( 'faceForward', faceForward );
  24431. addNodeElement( 'difference', difference );
  24432. addNodeElement( 'saturate', saturate );
  24433. addNodeElement( 'cbrt', cbrt );
  24434. addNodeElement( 'transpose', transpose );
  24435. addNodeElement( 'rand', rand );
  24436. addNodeClass( 'MathNode', MathNode );
  24437. const sRGBToLinearShader = tslFn( ( inputs ) => {
  24438. const { value } = inputs;
  24439. const { rgb } = value;
  24440. const a = rgb.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  24441. const b = rgb.mul( 0.0773993808 );
  24442. const factor = rgb.lessThanEqual( 0.04045 );
  24443. const rgbResult = mix( a, b, factor );
  24444. return vec4( rgbResult, value.a );
  24445. } );
  24446. const LinearTosRGBShader = tslFn( ( inputs ) => {
  24447. const { value } = inputs;
  24448. const { rgb } = value;
  24449. const a = rgb.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  24450. const b = rgb.mul( 12.92 );
  24451. const factor = rgb.lessThanEqual( 0.0031308 );
  24452. const rgbResult = mix( a, b, factor );
  24453. return vec4( rgbResult, value.a );
  24454. } );
  24455. const getColorSpaceMethod = ( colorSpace ) => {
  24456. let method = null;
  24457. if ( colorSpace === LinearSRGBColorSpace ) {
  24458. method = 'Linear';
  24459. } else if ( colorSpace === SRGBColorSpace ) {
  24460. method = 'sRGB';
  24461. }
  24462. return method;
  24463. };
  24464. const getMethod = ( source, target ) => {
  24465. return getColorSpaceMethod( source ) + 'To' + getColorSpaceMethod( target );
  24466. };
  24467. class ColorSpaceNode extends TempNode {
  24468. constructor( method, node ) {
  24469. super( 'vec4' );
  24470. this.method = method;
  24471. this.node = node;
  24472. }
  24473. setup() {
  24474. const { method, node } = this;
  24475. if ( method === ColorSpaceNode.LINEAR_TO_LINEAR )
  24476. return node;
  24477. return Methods[ method ]( { value: node } );
  24478. }
  24479. }
  24480. ColorSpaceNode.LINEAR_TO_LINEAR = 'LinearToLinear';
  24481. ColorSpaceNode.LINEAR_TO_sRGB = 'LinearTosRGB';
  24482. ColorSpaceNode.sRGB_TO_LINEAR = 'sRGBToLinear';
  24483. const Methods = {
  24484. [ ColorSpaceNode.LINEAR_TO_sRGB ]: LinearTosRGBShader,
  24485. [ ColorSpaceNode.sRGB_TO_LINEAR ]: sRGBToLinearShader
  24486. };
  24487. const linearToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( LinearSRGBColorSpace, colorSpace ), nodeObject( node ) ) );
  24488. const colorSpaceToLinear = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( colorSpace, LinearSRGBColorSpace ), nodeObject( node ) ) );
  24489. const linearTosRGB = nodeProxy( ColorSpaceNode, ColorSpaceNode.LINEAR_TO_sRGB );
  24490. const sRGBToLinear = nodeProxy( ColorSpaceNode, ColorSpaceNode.sRGB_TO_LINEAR );
  24491. addNodeElement( 'linearTosRGB', linearTosRGB );
  24492. addNodeElement( 'sRGBToLinear', sRGBToLinear );
  24493. addNodeElement( 'linearToColorSpace', linearToColorSpace );
  24494. addNodeElement( 'colorSpaceToLinear', colorSpaceToLinear );
  24495. addNodeClass( 'ColorSpaceNode', ColorSpaceNode );
  24496. class ExpressionNode extends Node {
  24497. constructor( snippet = '', nodeType = 'void' ) {
  24498. super( nodeType );
  24499. this.snippet = snippet;
  24500. }
  24501. generate( builder, output ) {
  24502. const type = this.getNodeType( builder );
  24503. const snippet = this.snippet;
  24504. if ( type === 'void' ) {
  24505. builder.addLineFlowCode( snippet );
  24506. } else {
  24507. return builder.format( `( ${ snippet } )`, type, output );
  24508. }
  24509. }
  24510. }
  24511. const expression = nodeProxy( ExpressionNode );
  24512. addNodeClass( 'ExpressionNode', ExpressionNode );
  24513. class MaxMipLevelNode extends UniformNode {
  24514. constructor( textureNode ) {
  24515. super( 0 );
  24516. this._textureNode = textureNode;
  24517. this.updateType = NodeUpdateType.FRAME;
  24518. }
  24519. get textureNode() {
  24520. return this._textureNode;
  24521. }
  24522. get texture() {
  24523. return this._textureNode.value;
  24524. }
  24525. update() {
  24526. const texture = this.texture;
  24527. const images = texture.images;
  24528. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24529. if ( image && image.width !== undefined ) {
  24530. const { width, height } = image;
  24531. this.value = Math.log2( Math.max( width, height ) );
  24532. }
  24533. }
  24534. }
  24535. const maxMipLevel = nodeProxy( MaxMipLevelNode );
  24536. addNodeClass( 'MaxMipLevelNode', MaxMipLevelNode );
  24537. class TextureNode extends UniformNode {
  24538. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24539. super( value );
  24540. this.isTextureNode = true;
  24541. this.uvNode = uvNode;
  24542. this.levelNode = levelNode;
  24543. this.biasNode = biasNode;
  24544. this.compareNode = null;
  24545. this.depthNode = null;
  24546. this.gradNode = null;
  24547. this.sampler = true;
  24548. this.updateMatrix = false;
  24549. this.updateType = NodeUpdateType.NONE;
  24550. this.referenceNode = null;
  24551. this._value = value;
  24552. this.setUpdateMatrix( uvNode === null );
  24553. }
  24554. set value( value ) {
  24555. if ( this.referenceNode ) {
  24556. this.referenceNode.value = value;
  24557. } else {
  24558. this._value = value;
  24559. }
  24560. }
  24561. get value() {
  24562. return this.referenceNode ? this.referenceNode.value : this._value;
  24563. }
  24564. getUniformHash( /*builder*/ ) {
  24565. return this.value.uuid;
  24566. }
  24567. getNodeType( /*builder*/ ) {
  24568. if ( this.value.isDepthTexture === true ) return 'float';
  24569. if ( this.value.type === UnsignedIntType ) {
  24570. return 'uvec4';
  24571. } else if ( this.value.type === IntType ) {
  24572. return 'ivec4';
  24573. }
  24574. return 'vec4';
  24575. }
  24576. getInputType( /*builder*/ ) {
  24577. return 'texture';
  24578. }
  24579. getDefaultUV() {
  24580. return uv( this.value.channel );
  24581. }
  24582. updateReference( /*state*/ ) {
  24583. return this.value;
  24584. }
  24585. getTransformedUV( uvNode ) {
  24586. const texture = this.value;
  24587. return uniform( texture.matrix ).mul( vec3( uvNode, 1 ) ).xy;
  24588. }
  24589. setUpdateMatrix( value ) {
  24590. this.updateMatrix = value;
  24591. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24592. return this;
  24593. }
  24594. setupUV( builder, uvNode ) {
  24595. const texture = this.value;
  24596. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24597. uvNode = uvNode.setY( uvNode.y.oneMinus() );
  24598. }
  24599. return uvNode;
  24600. }
  24601. setup( builder ) {
  24602. const properties = builder.getNodeProperties( this );
  24603. properties.referenceNode = this.referenceNode;
  24604. //
  24605. let uvNode = this.uvNode;
  24606. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24607. uvNode = builder.context.getUV( this );
  24608. }
  24609. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24610. if ( this.updateMatrix === true ) {
  24611. uvNode = this.getTransformedUV( uvNode );
  24612. }
  24613. uvNode = this.setupUV( builder, uvNode );
  24614. //
  24615. let levelNode = this.levelNode;
  24616. if ( levelNode === null && builder.context.getTextureLevel ) {
  24617. levelNode = builder.context.getTextureLevel( this );
  24618. }
  24619. //
  24620. properties.uvNode = uvNode;
  24621. properties.levelNode = levelNode;
  24622. properties.biasNode = this.biasNode;
  24623. properties.compareNode = this.compareNode;
  24624. properties.gradNode = this.gradNode;
  24625. properties.depthNode = this.depthNode;
  24626. }
  24627. generateUV( builder, uvNode ) {
  24628. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24629. }
  24630. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24631. const texture = this.value;
  24632. let snippet;
  24633. if ( levelSnippet ) {
  24634. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24635. } else if ( biasSnippet ) {
  24636. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24637. } else if ( gradSnippet ) {
  24638. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24639. } else if ( compareSnippet ) {
  24640. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24641. } else if ( this.sampler === false ) {
  24642. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24643. } else {
  24644. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24645. }
  24646. return snippet;
  24647. }
  24648. generate( builder, output ) {
  24649. const properties = builder.getNodeProperties( this );
  24650. const texture = this.value;
  24651. if ( ! texture || texture.isTexture !== true ) {
  24652. throw new Error( 'TextureNode: Need a three.js texture.' );
  24653. }
  24654. const textureProperty = super.generate( builder, 'property' );
  24655. if ( output === 'sampler' ) {
  24656. return textureProperty + '_sampler';
  24657. } else if ( builder.isReference( output ) ) {
  24658. return textureProperty;
  24659. } else {
  24660. const nodeData = builder.getDataFromNode( this );
  24661. let propertyName = nodeData.propertyName;
  24662. if ( propertyName === undefined ) {
  24663. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24664. const uvSnippet = this.generateUV( builder, uvNode );
  24665. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24666. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24667. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24668. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24669. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24670. const nodeVar = builder.getVarFromNode( this );
  24671. propertyName = builder.getPropertyName( nodeVar );
  24672. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24673. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  24674. nodeData.snippet = snippet;
  24675. nodeData.propertyName = propertyName;
  24676. }
  24677. let snippet = propertyName;
  24678. const nodeType = this.getNodeType( builder );
  24679. if ( builder.needsColorSpaceToLinear( texture ) ) {
  24680. snippet = colorSpaceToLinear( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24681. }
  24682. return builder.format( snippet, nodeType, output );
  24683. }
  24684. }
  24685. setSampler( value ) {
  24686. this.sampler = value;
  24687. return this;
  24688. }
  24689. getSampler() {
  24690. return this.sampler;
  24691. }
  24692. // @TODO: Move to TSL
  24693. uv( uvNode ) {
  24694. const textureNode = this.clone();
  24695. textureNode.uvNode = nodeObject( uvNode );
  24696. textureNode.referenceNode = this;
  24697. return nodeObject( textureNode );
  24698. }
  24699. blur( amountNode ) {
  24700. const textureNode = this.clone();
  24701. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24702. textureNode.referenceNode = this;
  24703. return nodeObject( textureNode );
  24704. }
  24705. level( levelNode ) {
  24706. const textureNode = this.clone();
  24707. textureNode.levelNode = nodeObject( levelNode );
  24708. textureNode.referenceNode = this;
  24709. return nodeObject( textureNode );
  24710. }
  24711. size( levelNode ) {
  24712. return textureSize( this, levelNode );
  24713. }
  24714. bias( biasNode ) {
  24715. const textureNode = this.clone();
  24716. textureNode.biasNode = nodeObject( biasNode );
  24717. textureNode.referenceNode = this;
  24718. return nodeObject( textureNode );
  24719. }
  24720. compare( compareNode ) {
  24721. const textureNode = this.clone();
  24722. textureNode.compareNode = nodeObject( compareNode );
  24723. textureNode.referenceNode = this;
  24724. return nodeObject( textureNode );
  24725. }
  24726. grad( gradNodeX, gradNodeY ) {
  24727. const textureNode = this.clone();
  24728. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24729. textureNode.referenceNode = this;
  24730. return nodeObject( textureNode );
  24731. }
  24732. depth( depthNode ) {
  24733. const textureNode = this.clone();
  24734. textureNode.depthNode = nodeObject( depthNode );
  24735. textureNode.referenceNode = this;
  24736. return nodeObject( textureNode );
  24737. }
  24738. // --
  24739. serialize( data ) {
  24740. super.serialize( data );
  24741. data.value = this.value.toJSON( data.meta ).uuid;
  24742. }
  24743. deserialize( data ) {
  24744. super.deserialize( data );
  24745. this.value = data.meta.textures[ data.value ];
  24746. }
  24747. update() {
  24748. const texture = this.value;
  24749. if ( texture.matrixAutoUpdate === true ) {
  24750. texture.updateMatrix();
  24751. }
  24752. }
  24753. clone() {
  24754. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24755. newNode.sampler = this.sampler;
  24756. return newNode;
  24757. }
  24758. }
  24759. const texture = nodeProxy( TextureNode );
  24760. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24761. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24762. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24763. addNodeElement( 'texture', texture );
  24764. //addNodeElement( 'textureLevel', textureLevel );
  24765. addNodeClass( 'TextureNode', TextureNode );
  24766. class BufferNode extends UniformNode {
  24767. constructor( value, bufferType, bufferCount = 0 ) {
  24768. super( value, bufferType );
  24769. this.isBufferNode = true;
  24770. this.bufferType = bufferType;
  24771. this.bufferCount = bufferCount;
  24772. }
  24773. getElementType( builder ) {
  24774. return this.getNodeType( builder );
  24775. }
  24776. getInputType( /*builder*/ ) {
  24777. return 'buffer';
  24778. }
  24779. }
  24780. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24781. addNodeClass( 'BufferNode', BufferNode );
  24782. class UniformsElementNode extends ArrayElementNode {
  24783. constructor( arrayBuffer, indexNode ) {
  24784. super( arrayBuffer, indexNode );
  24785. this.isArrayBufferElementNode = true;
  24786. }
  24787. getNodeType( builder ) {
  24788. return this.node.getElementType( builder );
  24789. }
  24790. generate( builder ) {
  24791. const snippet = super.generate( builder );
  24792. const type = this.getNodeType();
  24793. return builder.format( snippet, 'vec4', type );
  24794. }
  24795. }
  24796. class UniformsNode extends BufferNode {
  24797. constructor( value, elementType = null ) {
  24798. super( null, 'vec4' );
  24799. this.array = value;
  24800. this.elementType = elementType;
  24801. this._elementType = null;
  24802. this._elementLength = 0;
  24803. this.updateType = NodeUpdateType.RENDER;
  24804. this.isArrayBufferNode = true;
  24805. }
  24806. getElementType() {
  24807. return this.elementType || this._elementType;
  24808. }
  24809. getElementLength() {
  24810. return this._elementLength;
  24811. }
  24812. update( /*frame*/ ) {
  24813. const { array, value } = this;
  24814. const elementLength = this.getElementLength();
  24815. const elementType = this.getElementType();
  24816. if ( elementLength === 1 ) {
  24817. for ( let i = 0; i < array.length; i ++ ) {
  24818. const index = i * 4;
  24819. value[ index ] = array[ i ];
  24820. }
  24821. } else if ( elementType === 'color' ) {
  24822. for ( let i = 0; i < array.length; i ++ ) {
  24823. const index = i * 4;
  24824. const vector = array[ i ];
  24825. value[ index ] = vector.r;
  24826. value[ index + 1 ] = vector.g;
  24827. value[ index + 2 ] = vector.b || 0;
  24828. //value[ index + 3 ] = vector.a || 0;
  24829. }
  24830. } else {
  24831. for ( let i = 0; i < array.length; i ++ ) {
  24832. const index = i * 4;
  24833. const vector = array[ i ];
  24834. value[ index ] = vector.x;
  24835. value[ index + 1 ] = vector.y;
  24836. value[ index + 2 ] = vector.z || 0;
  24837. value[ index + 3 ] = vector.w || 0;
  24838. }
  24839. }
  24840. }
  24841. setup( builder ) {
  24842. const length = this.array.length;
  24843. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24844. this._elementLength = builder.getTypeLength( this._elementType );
  24845. let arrayType = Float32Array;
  24846. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24847. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24848. this.value = new arrayType( length * 4 );
  24849. this.bufferCount = length;
  24850. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24851. return super.setup( builder );
  24852. }
  24853. element( indexNode ) {
  24854. return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) );
  24855. }
  24856. }
  24857. const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) );
  24858. addNodeClass( 'UniformsNode', UniformsNode );
  24859. class ReferenceElementNode extends ArrayElementNode {
  24860. constructor( referenceNode, indexNode ) {
  24861. super( referenceNode, indexNode );
  24862. this.referenceNode = referenceNode;
  24863. this.isReferenceElementNode = true;
  24864. }
  24865. getNodeType() {
  24866. return this.referenceNode.uniformType;
  24867. }
  24868. generate( builder ) {
  24869. const snippet = super.generate( builder );
  24870. const arrayType = this.referenceNode.getNodeType();
  24871. const elementType = this.getNodeType();
  24872. return builder.format( snippet, arrayType, elementType );
  24873. }
  24874. }
  24875. class ReferenceNode extends Node {
  24876. constructor( property, uniformType, object = null, count = null ) {
  24877. super();
  24878. this.property = property;
  24879. this.uniformType = uniformType;
  24880. this.object = object;
  24881. this.count = count;
  24882. this.properties = property.split( '.' );
  24883. this.reference = null;
  24884. this.node = null;
  24885. this.updateType = NodeUpdateType.OBJECT;
  24886. }
  24887. element( indexNode ) {
  24888. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24889. }
  24890. setNodeType( uniformType ) {
  24891. let node = null;
  24892. if ( this.count !== null ) {
  24893. node = buffer( null, uniformType, this.count );
  24894. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24895. node = uniforms( null, uniformType );
  24896. } else if ( uniformType === 'texture' ) {
  24897. node = texture( null );
  24898. } else {
  24899. node = uniform( null, uniformType );
  24900. }
  24901. this.node = node;
  24902. }
  24903. getNodeType( builder ) {
  24904. if ( this.node === null ) {
  24905. this.updateValue();
  24906. }
  24907. return this.node.getNodeType( builder );
  24908. }
  24909. getValueFromReference( object = this.reference ) {
  24910. const { properties } = this;
  24911. let value = object[ properties[ 0 ] ];
  24912. for ( let i = 1; i < properties.length; i ++ ) {
  24913. value = value[ properties[ i ] ];
  24914. }
  24915. return value;
  24916. }
  24917. updateReference( state ) {
  24918. this.reference = this.object !== null ? this.object : state.object;
  24919. return this.reference;
  24920. }
  24921. setup() {
  24922. this.updateValue();
  24923. return this.node;
  24924. }
  24925. update( /*frame*/ ) {
  24926. this.updateValue();
  24927. }
  24928. updateValue() {
  24929. if ( this.node === null ) this.setNodeType( this.uniformType );
  24930. const value = this.getValueFromReference();
  24931. if ( Array.isArray( value ) ) {
  24932. this.node.array = value;
  24933. } else {
  24934. this.node.value = value;
  24935. }
  24936. }
  24937. }
  24938. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  24939. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  24940. addNodeClass( 'ReferenceNode', ReferenceNode );
  24941. class MaterialReferenceNode extends ReferenceNode {
  24942. constructor( property, inputType, material = null ) {
  24943. super( property, inputType, material );
  24944. this.material = material;
  24945. //this.updateType = NodeUpdateType.RENDER;
  24946. }
  24947. /*setNodeType( node ) {
  24948. super.setNodeType( node );
  24949. this.node.groupNode = renderGroup;
  24950. }*/
  24951. updateReference( state ) {
  24952. this.reference = this.material !== null ? this.material : state.material;
  24953. return this.reference;
  24954. }
  24955. }
  24956. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  24957. addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode );
  24958. const cameraGroup = /*#__PURE__*/ sharedUniformGroup( 'camera' ).onRenderUpdate( () => {
  24959. cameraGroup.needsUpdate = true;
  24960. } );
  24961. const cameraNear = /*#__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24962. const cameraFar = /*#__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24963. const cameraLogDepth = /*#__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  24964. const cameraProjectionMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24965. const cameraProjectionMatrixInverse = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24966. const cameraViewMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24967. const cameraWorldMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24968. const cameraNormalMatrix = /*#__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24969. const cameraPosition = /*#__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24970. class Object3DNode extends Node {
  24971. constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) {
  24972. super();
  24973. this.scope = scope;
  24974. this.object3d = object3d;
  24975. this.updateType = NodeUpdateType.OBJECT;
  24976. this._uniformNode = new UniformNode( null );
  24977. }
  24978. getNodeType() {
  24979. const scope = this.scope;
  24980. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  24981. return 'mat4';
  24982. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  24983. return 'mat3';
  24984. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24985. return 'vec3';
  24986. }
  24987. }
  24988. update( frame ) {
  24989. const object = this.object3d;
  24990. const uniformNode = this._uniformNode;
  24991. const scope = this.scope;
  24992. if ( scope === Object3DNode.VIEW_MATRIX ) {
  24993. uniformNode.value = object.modelViewMatrix;
  24994. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  24995. uniformNode.value = object.normalMatrix;
  24996. } else if ( scope === Object3DNode.WORLD_MATRIX ) {
  24997. uniformNode.value = object.matrixWorld;
  24998. } else if ( scope === Object3DNode.POSITION ) {
  24999. uniformNode.value = uniformNode.value || new Vector3();
  25000. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25001. } else if ( scope === Object3DNode.SCALE ) {
  25002. uniformNode.value = uniformNode.value || new Vector3();
  25003. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  25004. } else if ( scope === Object3DNode.DIRECTION ) {
  25005. uniformNode.value = uniformNode.value || new Vector3();
  25006. object.getWorldDirection( uniformNode.value );
  25007. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  25008. const camera = frame.camera;
  25009. uniformNode.value = uniformNode.value || new Vector3();
  25010. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25011. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  25012. }
  25013. }
  25014. generate( builder ) {
  25015. const scope = this.scope;
  25016. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  25017. this._uniformNode.nodeType = 'mat4';
  25018. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25019. this._uniformNode.nodeType = 'mat3';
  25020. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  25021. this._uniformNode.nodeType = 'vec3';
  25022. }
  25023. return this._uniformNode.build( builder );
  25024. }
  25025. serialize( data ) {
  25026. super.serialize( data );
  25027. data.scope = this.scope;
  25028. }
  25029. deserialize( data ) {
  25030. super.deserialize( data );
  25031. this.scope = data.scope;
  25032. }
  25033. }
  25034. Object3DNode.VIEW_MATRIX = 'viewMatrix';
  25035. Object3DNode.NORMAL_MATRIX = 'normalMatrix';
  25036. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  25037. Object3DNode.POSITION = 'position';
  25038. Object3DNode.SCALE = 'scale';
  25039. Object3DNode.VIEW_POSITION = 'viewPosition';
  25040. Object3DNode.DIRECTION = 'direction';
  25041. const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  25042. const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX );
  25043. const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX );
  25044. const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  25045. const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION );
  25046. const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE );
  25047. const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  25048. addNodeClass( 'Object3DNode', Object3DNode );
  25049. class ModelNode extends Object3DNode {
  25050. constructor( scope = ModelNode.VIEW_MATRIX ) {
  25051. super( scope );
  25052. }
  25053. update( frame ) {
  25054. this.object3d = frame.object;
  25055. super.update( frame );
  25056. }
  25057. }
  25058. const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION );
  25059. const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' );
  25060. const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX );
  25061. const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  25062. const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION );
  25063. const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE );
  25064. const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  25065. const modelWorldMatrixInverse = uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  25066. addNodeClass( 'ModelNode', ModelNode );
  25067. const normalGeometry = /*#__PURE__*/ attribute( 'normal', 'vec3', vec3( 0, 1, 0 ) );
  25068. const normalLocal = /*#__PURE__*/ normalGeometry.toVar( 'normalLocal' );
  25069. const normalView = /*#__PURE__*/ varying( modelNormalMatrix.mul( normalLocal ), 'v_normalView' ).normalize().toVar( 'normalView' );
  25070. const normalWorld = /*#__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'transformedNormalWorld' );
  25071. const transformedNormalView = /*#__PURE__*/ property( 'vec3', 'transformedNormalView' );
  25072. const transformedNormalWorld = /*#__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedNormalWorld' );
  25073. const transformedClearcoatNormalView = /*#__PURE__*/ property( 'vec3', 'transformedClearcoatNormalView' );
  25074. const _propertyCache = new Map();
  25075. class MaterialNode extends Node {
  25076. constructor( scope ) {
  25077. super();
  25078. this.scope = scope;
  25079. }
  25080. getCache( property, type ) {
  25081. let node = _propertyCache.get( property );
  25082. if ( node === undefined ) {
  25083. node = materialReference( property, type );
  25084. _propertyCache.set( property, node );
  25085. }
  25086. return node;
  25087. }
  25088. getFloat( property ) {
  25089. return this.getCache( property, 'float' );
  25090. }
  25091. getColor( property ) {
  25092. return this.getCache( property, 'color' );
  25093. }
  25094. getTexture( property ) {
  25095. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25096. }
  25097. setup( builder ) {
  25098. const material = builder.context.material;
  25099. const scope = this.scope;
  25100. let node = null;
  25101. if ( scope === MaterialNode.COLOR ) {
  25102. const colorNode = this.getColor( scope );
  25103. if ( material.map && material.map.isTexture === true ) {
  25104. node = colorNode.mul( this.getTexture( 'map' ) );
  25105. } else {
  25106. node = colorNode;
  25107. }
  25108. } else if ( scope === MaterialNode.OPACITY ) {
  25109. const opacityNode = this.getFloat( scope );
  25110. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25111. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25112. } else {
  25113. node = opacityNode;
  25114. }
  25115. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25116. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25117. node = this.getTexture( 'specular' ).r;
  25118. } else {
  25119. node = float( 1 );
  25120. }
  25121. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25122. const specularIntensity = this.getFloat( scope );
  25123. if ( material.specularMap ) {
  25124. node = specularIntensity.mul( this.getTexture( scope ).a );
  25125. } else {
  25126. node = specularIntensity;
  25127. }
  25128. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25129. const specularColorNode = this.getColor( scope );
  25130. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25131. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25132. } else {
  25133. node = specularColorNode;
  25134. }
  25135. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25136. const roughnessNode = this.getFloat( scope );
  25137. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25138. node = roughnessNode.mul( this.getTexture( scope ).g );
  25139. } else {
  25140. node = roughnessNode;
  25141. }
  25142. } else if ( scope === MaterialNode.METALNESS ) {
  25143. const metalnessNode = this.getFloat( scope );
  25144. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25145. node = metalnessNode.mul( this.getTexture( scope ).b );
  25146. } else {
  25147. node = metalnessNode;
  25148. }
  25149. } else if ( scope === MaterialNode.EMISSIVE ) {
  25150. const emissiveNode = this.getColor( scope );
  25151. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25152. node = emissiveNode.mul( this.getTexture( scope ) );
  25153. } else {
  25154. node = emissiveNode;
  25155. }
  25156. } else if ( scope === MaterialNode.NORMAL ) {
  25157. if ( material.normalMap ) {
  25158. node = this.getTexture( 'normal' ).normalMap( this.getCache( 'normalScale', 'vec2' ) );
  25159. } else if ( material.bumpMap ) {
  25160. node = this.getTexture( 'bump' ).r.bumpMap( this.getFloat( 'bumpScale' ) );
  25161. } else {
  25162. node = normalView;
  25163. }
  25164. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25165. const clearcoatNode = this.getFloat( scope );
  25166. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25167. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25168. } else {
  25169. node = clearcoatNode;
  25170. }
  25171. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25172. const clearcoatRoughnessNode = this.getFloat( scope );
  25173. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25174. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25175. } else {
  25176. node = clearcoatRoughnessNode;
  25177. }
  25178. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25179. if ( material.clearcoatNormalMap ) {
  25180. node = this.getTexture( scope ).normalMap( this.getCache( scope + 'Scale', 'vec2' ) );
  25181. } else {
  25182. node = normalView;
  25183. }
  25184. } else if ( scope === MaterialNode.SHEEN ) {
  25185. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25186. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25187. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25188. } else {
  25189. node = sheenNode;
  25190. }
  25191. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25192. const sheenRoughnessNode = this.getFloat( scope );
  25193. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25194. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25195. } else {
  25196. node = sheenRoughnessNode;
  25197. }
  25198. node = node.clamp( 0.07, 1.0 );
  25199. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25200. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25201. const anisotropyPolar = this.getTexture( scope );
  25202. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25203. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25204. } else {
  25205. node = materialAnisotropyVector;
  25206. }
  25207. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25208. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25209. if ( material.iridescenceThicknessMap ) {
  25210. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25211. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25212. } else {
  25213. node = iridescenceThicknessMaximum;
  25214. }
  25215. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25216. const transmissionNode = this.getFloat( scope );
  25217. if ( material.transmissionMap ) {
  25218. node = transmissionNode.mul( this.getTexture( scope ).r );
  25219. } else {
  25220. node = transmissionNode;
  25221. }
  25222. } else if ( scope === MaterialNode.THICKNESS ) {
  25223. const thicknessNode = this.getFloat( scope );
  25224. if ( material.thicknessMap ) {
  25225. node = thicknessNode.mul( this.getTexture( scope ).g );
  25226. } else {
  25227. node = thicknessNode;
  25228. }
  25229. } else if ( scope === MaterialNode.IOR ) {
  25230. node = this.getFloat( scope );
  25231. } else {
  25232. const outputType = this.getNodeType( builder );
  25233. node = this.getCache( scope, outputType );
  25234. }
  25235. return node;
  25236. }
  25237. }
  25238. MaterialNode.ALPHA_TEST = 'alphaTest';
  25239. MaterialNode.COLOR = 'color';
  25240. MaterialNode.OPACITY = 'opacity';
  25241. MaterialNode.SHININESS = 'shininess';
  25242. MaterialNode.SPECULAR = 'specular';
  25243. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25244. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25245. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25246. MaterialNode.REFLECTIVITY = 'reflectivity';
  25247. MaterialNode.ROUGHNESS = 'roughness';
  25248. MaterialNode.METALNESS = 'metalness';
  25249. MaterialNode.NORMAL = 'normal';
  25250. MaterialNode.CLEARCOAT = 'clearcoat';
  25251. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25252. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25253. MaterialNode.EMISSIVE = 'emissive';
  25254. MaterialNode.ROTATION = 'rotation';
  25255. MaterialNode.SHEEN = 'sheen';
  25256. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25257. MaterialNode.ANISOTROPY = 'anisotropy';
  25258. MaterialNode.IRIDESCENCE = 'iridescence';
  25259. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25260. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25261. MaterialNode.IOR = 'ior';
  25262. MaterialNode.TRANSMISSION = 'transmission';
  25263. MaterialNode.THICKNESS = 'thickness';
  25264. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25265. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25266. MaterialNode.LINE_SCALE = 'scale';
  25267. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25268. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25269. MaterialNode.LINE_WIDTH = 'linewidth';
  25270. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25271. MaterialNode.POINT_WIDTH = 'pointWidth';
  25272. MaterialNode.DISPERSION = 'dispersion';
  25273. const materialAlphaTest = nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25274. const materialColor = nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25275. const materialShininess = nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25276. const materialEmissive = nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25277. const materialOpacity = nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25278. const materialSpecular = nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25279. const materialSpecularIntensity = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25280. const materialSpecularColor = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25281. const materialSpecularStrength = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25282. const materialReflectivity = nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25283. const materialRoughness = nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25284. const materialMetalness = nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25285. const materialNormal = nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  25286. const materialClearcoat = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25287. const materialClearcoatRoughness = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25288. const materialClearcoatNormal = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  25289. const materialRotation = nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25290. const materialSheen = nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25291. const materialSheenRoughness = nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25292. const materialAnisotropy = nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25293. const materialIridescence = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25294. const materialIridescenceIOR = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25295. const materialIridescenceThickness = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25296. const materialTransmission = nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25297. const materialThickness = nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25298. const materialIOR = nodeImmutable( MaterialNode, MaterialNode.IOR );
  25299. const materialAttenuationDistance = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25300. const materialAttenuationColor = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25301. const materialLineScale = nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25302. const materialLineDashSize = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25303. const materialLineGapSize = nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25304. const materialLineWidth = nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25305. const materialLineDashOffset = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25306. const materialPointWidth = nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25307. const materialDispersion = nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25308. const materialAnisotropyVector = uniform( new Vector2() ).onReference( function ( frame ) {
  25309. return frame.material;
  25310. } ).onRenderUpdate( function ( { material } ) {
  25311. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25312. } );
  25313. addNodeClass( 'MaterialNode', MaterialNode );
  25314. const positionGeometry = /*#__PURE__*/ attribute( 'position', 'vec3' );
  25315. const positionLocal = /*#__PURE__*/ positionGeometry.toVar( 'positionLocal' );
  25316. const positionWorld = /*#__PURE__*/ varying( modelWorldMatrix.mul( positionLocal ).xyz, 'v_positionWorld' );
  25317. const positionWorldDirection = /*#__PURE__*/ varying( positionLocal.transformDirection( modelWorldMatrix ), 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  25318. const positionView = /*#__PURE__*/ varying( modelViewMatrix.mul( positionLocal ).xyz, 'v_positionView' );
  25319. const positionViewDirection = /*#__PURE__*/ varying( positionView.negate(), 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  25320. class ModelViewProjectionNode extends TempNode {
  25321. constructor( positionNode = null ) {
  25322. super( 'vec4' );
  25323. this.positionNode = positionNode;
  25324. }
  25325. setup( builder ) {
  25326. if ( builder.shaderStage === 'fragment' ) {
  25327. return varying( builder.context.mvp );
  25328. }
  25329. const position = this.positionNode || positionLocal;
  25330. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( position );
  25331. }
  25332. }
  25333. const modelViewProjection = nodeProxy( ModelViewProjectionNode );
  25334. addNodeClass( 'ModelViewProjectionNode', ModelViewProjectionNode );
  25335. class BufferAttributeNode extends InputNode {
  25336. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  25337. super( value, bufferType );
  25338. this.isBufferNode = true;
  25339. this.bufferType = bufferType;
  25340. this.bufferStride = bufferStride;
  25341. this.bufferOffset = bufferOffset;
  25342. this.usage = StaticDrawUsage;
  25343. this.instanced = false;
  25344. this.attribute = null;
  25345. this.global = true;
  25346. if ( value && value.isBufferAttribute === true ) {
  25347. this.attribute = value;
  25348. this.usage = value.usage;
  25349. this.instanced = value.isInstancedBufferAttribute;
  25350. }
  25351. }
  25352. getHash( builder ) {
  25353. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  25354. let bufferData = builder.globalCache.getData( this.value );
  25355. if ( bufferData === undefined ) {
  25356. bufferData = {
  25357. node: this
  25358. };
  25359. builder.globalCache.setData( this.value, bufferData );
  25360. }
  25361. return bufferData.node.uuid;
  25362. }
  25363. return this.uuid;
  25364. }
  25365. getNodeType( builder ) {
  25366. if ( this.bufferType === null ) {
  25367. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  25368. }
  25369. return this.bufferType;
  25370. }
  25371. setup( builder ) {
  25372. if ( this.attribute !== null ) return;
  25373. const type = this.getNodeType( builder );
  25374. const array = this.value;
  25375. const itemSize = builder.getTypeLength( type );
  25376. const stride = this.bufferStride || itemSize;
  25377. const offset = this.bufferOffset;
  25378. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  25379. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  25380. buffer.setUsage( this.usage );
  25381. this.attribute = bufferAttribute;
  25382. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  25383. }
  25384. generate( builder ) {
  25385. const nodeType = this.getNodeType( builder );
  25386. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  25387. const propertyName = builder.getPropertyName( nodeAttribute );
  25388. let output = null;
  25389. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25390. this.name = propertyName;
  25391. output = propertyName;
  25392. } else {
  25393. const nodeVarying = varying( this );
  25394. output = nodeVarying.build( builder, nodeType );
  25395. }
  25396. return output;
  25397. }
  25398. getInputType( /*builder*/ ) {
  25399. return 'bufferAttribute';
  25400. }
  25401. setUsage( value ) {
  25402. this.usage = value;
  25403. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  25404. this.attribute.usage = value;
  25405. }
  25406. return this;
  25407. }
  25408. setInstanced( value ) {
  25409. this.instanced = value;
  25410. return this;
  25411. }
  25412. }
  25413. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  25414. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  25415. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  25416. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  25417. addNodeElement( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  25418. addNodeClass( 'BufferAttributeNode', BufferAttributeNode );
  25419. class InstanceNode extends Node {
  25420. constructor( instanceMesh ) {
  25421. super( 'void' );
  25422. this.instanceMesh = instanceMesh;
  25423. this.instanceMatrixNode = null;
  25424. this.instanceColorNode = null;
  25425. this.updateType = NodeUpdateType.FRAME;
  25426. this.buffer = null;
  25427. this.bufferColor = null;
  25428. }
  25429. setup( /*builder*/ ) {
  25430. let instanceMatrixNode = this.instanceMatrixNode;
  25431. const instanceMesh = this.instanceMesh;
  25432. if ( instanceMatrixNode === null ) {
  25433. const instanceAttribute = instanceMesh.instanceMatrix;
  25434. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25435. this.buffer = buffer;
  25436. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25437. const instanceBuffers = [
  25438. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25439. bufferFn( buffer, 'vec4', 16, 0 ),
  25440. bufferFn( buffer, 'vec4', 16, 4 ),
  25441. bufferFn( buffer, 'vec4', 16, 8 ),
  25442. bufferFn( buffer, 'vec4', 16, 12 )
  25443. ];
  25444. instanceMatrixNode = mat4( ...instanceBuffers );
  25445. this.instanceMatrixNode = instanceMatrixNode;
  25446. }
  25447. const instanceColorAttribute = instanceMesh.instanceColor;
  25448. if ( instanceColorAttribute && this.instanceColorNode === null ) {
  25449. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25450. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25451. this.bufferColor = buffer;
  25452. this.instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25453. }
  25454. // POSITION
  25455. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25456. // NORMAL
  25457. const m = mat3( instanceMatrixNode[ 0 ].xyz, instanceMatrixNode[ 1 ].xyz, instanceMatrixNode[ 2 ].xyz );
  25458. const transformedNormal = normalLocal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  25459. const instanceNormal = m.mul( transformedNormal ).xyz;
  25460. // ASSIGNS
  25461. positionLocal.assign( instancePosition );
  25462. normalLocal.assign( instanceNormal );
  25463. // COLOR
  25464. if ( this.instanceColorNode !== null ) {
  25465. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25466. }
  25467. }
  25468. update( /*frame*/ ) {
  25469. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25470. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25471. }
  25472. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25473. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25474. }
  25475. }
  25476. }
  25477. const instance = nodeProxy( InstanceNode );
  25478. addNodeClass( 'InstanceNode', InstanceNode );
  25479. const tangentGeometry = /*#__PURE__*/ tslFn( ( stack, builder ) => {
  25480. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25481. builder.geometry.computeTangents();
  25482. }
  25483. return attribute( 'tangent', 'vec4' );
  25484. } )();
  25485. const tangentLocal = /*#__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25486. const tangentView = /*#__PURE__*/ varying( modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz, 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25487. const tangentWorld = /*#__PURE__*/ varying( tangentView.transformDirection( cameraViewMatrix ), 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25488. const transformedTangentView = /*#__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25489. const transformedTangentWorld = /*#__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25490. class BatchNode extends Node {
  25491. constructor( batchMesh ) {
  25492. super( 'void' );
  25493. this.batchMesh = batchMesh;
  25494. this.instanceColorNode = null;
  25495. this.batchingIdNode = null;
  25496. }
  25497. setup( builder ) {
  25498. // POSITION
  25499. if ( this.batchingIdNode === null ) {
  25500. if ( builder.getDrawIndex() === null ) {
  25501. this.batchingIdNode = instanceIndex;
  25502. } else {
  25503. this.batchingIdNode = drawIndex;
  25504. }
  25505. }
  25506. const getIndirectIndex = tslFn( ( [ id ] ) => {
  25507. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25508. const x = int( id ).remainder( int( size ) );
  25509. const y = int( id ).div( int( size ) );
  25510. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25511. } ).setLayout( {
  25512. name: 'getIndirectIndex',
  25513. type: 'uint',
  25514. inputs: [
  25515. { name: 'id', type: 'int' }
  25516. ]
  25517. } );
  25518. const matriceTexture = this.batchMesh._matricesTexture;
  25519. const size = textureSize( textureLoad( matriceTexture ), 0 );
  25520. const j = float( getIndirectIndex( int( this.batchingIdNode ) ) ).mul( 4 ).toVar();
  25521. const x = int( j.mod( size ) );
  25522. const y = int( j ).div( int( size ) );
  25523. const batchingMatrix = mat4(
  25524. textureLoad( matriceTexture, ivec2( x, y ) ),
  25525. textureLoad( matriceTexture, ivec2( x.add( 1 ), y ) ),
  25526. textureLoad( matriceTexture, ivec2( x.add( 2 ), y ) ),
  25527. textureLoad( matriceTexture, ivec2( x.add( 3 ), y ) )
  25528. );
  25529. const bm = mat3(
  25530. batchingMatrix[ 0 ].xyz,
  25531. batchingMatrix[ 1 ].xyz,
  25532. batchingMatrix[ 2 ].xyz
  25533. );
  25534. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25535. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25536. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25537. normalLocal.assign( batchingNormal );
  25538. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25539. tangentLocal.mulAssign( bm );
  25540. }
  25541. }
  25542. }
  25543. const batch = nodeProxy( BatchNode );
  25544. addNodeClass( 'batch', BatchNode );
  25545. class SkinningNode extends Node {
  25546. constructor( skinnedMesh, useReference = false ) {
  25547. super( 'void' );
  25548. this.skinnedMesh = skinnedMesh;
  25549. this.useReference = useReference;
  25550. this.updateType = NodeUpdateType.OBJECT;
  25551. //
  25552. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25553. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25554. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25555. if ( useReference ) {
  25556. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25557. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25558. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25559. } else {
  25560. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25561. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25562. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25563. }
  25564. this.bindMatrixNode = bindMatrixNode;
  25565. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25566. this.boneMatricesNode = boneMatricesNode;
  25567. }
  25568. setup( builder ) {
  25569. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode, boneMatricesNode } = this;
  25570. const boneMatX = boneMatricesNode.element( skinIndexNode.x );
  25571. const boneMatY = boneMatricesNode.element( skinIndexNode.y );
  25572. const boneMatZ = boneMatricesNode.element( skinIndexNode.z );
  25573. const boneMatW = boneMatricesNode.element( skinIndexNode.w );
  25574. // POSITION
  25575. const skinVertex = bindMatrixNode.mul( positionLocal );
  25576. const skinned = add(
  25577. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25578. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25579. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25580. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25581. );
  25582. const skinPosition = bindMatrixInverseNode.mul( skinned ).xyz;
  25583. // NORMAL
  25584. let skinMatrix = add(
  25585. skinWeightNode.x.mul( boneMatX ),
  25586. skinWeightNode.y.mul( boneMatY ),
  25587. skinWeightNode.z.mul( boneMatZ ),
  25588. skinWeightNode.w.mul( boneMatW )
  25589. );
  25590. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25591. const skinNormal = skinMatrix.transformDirection( normalLocal ).xyz;
  25592. // ASSIGNS
  25593. positionLocal.assign( skinPosition );
  25594. normalLocal.assign( skinNormal );
  25595. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25596. tangentLocal.assign( skinNormal );
  25597. }
  25598. }
  25599. generate( builder, output ) {
  25600. if ( output !== 'void' ) {
  25601. return positionLocal.build( builder, output );
  25602. }
  25603. }
  25604. update( frame ) {
  25605. const object = this.useReference ? frame.object : this.skinnedMesh;
  25606. object.skeleton.update();
  25607. }
  25608. }
  25609. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25610. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25611. addNodeClass( 'SkinningNode', SkinningNode );
  25612. class LoopNode extends Node {
  25613. constructor( params = [] ) {
  25614. super();
  25615. this.params = params;
  25616. }
  25617. getVarName( index ) {
  25618. return String.fromCharCode( 'i'.charCodeAt() + index );
  25619. }
  25620. getProperties( builder ) {
  25621. const properties = builder.getNodeProperties( this );
  25622. if ( properties.stackNode !== undefined ) return properties;
  25623. //
  25624. const inputs = {};
  25625. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25626. const param = this.params[ i ];
  25627. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25628. const type = ( param.isNode !== true && param.type ) || 'int';
  25629. inputs[ name ] = expression( name, type );
  25630. }
  25631. const stack = builder.addStack(); // TODO: cache() it
  25632. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25633. properties.stackNode = stack;
  25634. builder.removeStack();
  25635. return properties;
  25636. }
  25637. getNodeType( builder ) {
  25638. const { returnsNode } = this.getProperties( builder );
  25639. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25640. }
  25641. setup( builder ) {
  25642. // setup properties
  25643. this.getProperties( builder );
  25644. }
  25645. generate( builder ) {
  25646. const properties = this.getProperties( builder );
  25647. const params = this.params;
  25648. const stackNode = properties.stackNode;
  25649. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25650. const param = params[ i ];
  25651. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25652. if ( param.isNode ) {
  25653. type = 'int';
  25654. name = this.getVarName( i );
  25655. start = '0';
  25656. end = param.build( builder, type );
  25657. condition = '<';
  25658. } else {
  25659. type = param.type || 'int';
  25660. name = param.name || this.getVarName( i );
  25661. start = param.start;
  25662. end = param.end;
  25663. condition = param.condition;
  25664. update = param.update;
  25665. if ( typeof start === 'number' ) start = start.toString();
  25666. else if ( start && start.isNode ) start = start.build( builder, type );
  25667. if ( typeof end === 'number' ) end = end.toString();
  25668. else if ( end && end.isNode ) end = end.build( builder, type );
  25669. if ( start !== undefined && end === undefined ) {
  25670. start = start + ' - 1';
  25671. end = '0';
  25672. condition = '>=';
  25673. } else if ( end !== undefined && start === undefined ) {
  25674. start = '0';
  25675. condition = '<';
  25676. }
  25677. if ( condition === undefined ) {
  25678. if ( Number( start ) > Number( end ) ) {
  25679. condition = '>=';
  25680. } else {
  25681. condition = '<';
  25682. }
  25683. }
  25684. }
  25685. const internalParam = { start, end, condition };
  25686. //
  25687. const startSnippet = internalParam.start;
  25688. const endSnippet = internalParam.end;
  25689. let declarationSnippet = '';
  25690. let conditionalSnippet = '';
  25691. let updateSnippet = '';
  25692. if ( ! update ) {
  25693. if ( type === 'int' || type === 'uint' ) {
  25694. if ( condition.includes( '<' ) ) update = '++';
  25695. else update = '--';
  25696. } else {
  25697. if ( condition.includes( '<' ) ) update = '+= 1.';
  25698. else update = '-= 1.';
  25699. }
  25700. }
  25701. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25702. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25703. updateSnippet += name + ' ' + update;
  25704. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25705. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25706. }
  25707. const stackSnippet = stackNode.build( builder, 'void' );
  25708. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25709. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25710. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25711. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25712. }
  25713. builder.addFlowTab();
  25714. return returnsSnippet;
  25715. }
  25716. }
  25717. const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25718. const Continue = () => expression( 'continue' ).append();
  25719. const Break = () => expression( 'break' ).append();
  25720. addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) );
  25721. addNodeClass( 'LoopNode', LoopNode );
  25722. const morphTextures = new WeakMap();
  25723. const morphVec4 = new Vector4();
  25724. const getMorph = tslFn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25725. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25726. const y = texelIndex.div( width );
  25727. const x = texelIndex.sub( y.mul( width ) );
  25728. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25729. return bufferAttrib.mul( influence );
  25730. } );
  25731. function getEntry( geometry ) {
  25732. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25733. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25734. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25735. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25736. // into an array of data textures. Each layer represents a single morph target.
  25737. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25738. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25739. let entry = morphTextures.get( geometry );
  25740. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25741. if ( entry !== undefined ) entry.texture.dispose();
  25742. const morphTargets = geometry.morphAttributes.position || [];
  25743. const morphNormals = geometry.morphAttributes.normal || [];
  25744. const morphColors = geometry.morphAttributes.color || [];
  25745. let vertexDataCount = 0;
  25746. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25747. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25748. if ( hasMorphColors === true ) vertexDataCount = 3;
  25749. let width = geometry.attributes.position.count * vertexDataCount;
  25750. let height = 1;
  25751. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25752. if ( width > maxTextureSize ) {
  25753. height = Math.ceil( width / maxTextureSize );
  25754. width = maxTextureSize;
  25755. }
  25756. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25757. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25758. bufferTexture.type = FloatType;
  25759. bufferTexture.needsUpdate = true;
  25760. // fill buffer
  25761. const vertexDataStride = vertexDataCount * 4;
  25762. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25763. const morphTarget = morphTargets[ i ];
  25764. const morphNormal = morphNormals[ i ];
  25765. const morphColor = morphColors[ i ];
  25766. const offset = width * height * 4 * i;
  25767. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25768. const stride = j * vertexDataStride;
  25769. if ( hasMorphPosition === true ) {
  25770. morphVec4.fromBufferAttribute( morphTarget, j );
  25771. buffer[ offset + stride + 0 ] = morphVec4.x;
  25772. buffer[ offset + stride + 1 ] = morphVec4.y;
  25773. buffer[ offset + stride + 2 ] = morphVec4.z;
  25774. buffer[ offset + stride + 3 ] = 0;
  25775. }
  25776. if ( hasMorphNormals === true ) {
  25777. morphVec4.fromBufferAttribute( morphNormal, j );
  25778. buffer[ offset + stride + 4 ] = morphVec4.x;
  25779. buffer[ offset + stride + 5 ] = morphVec4.y;
  25780. buffer[ offset + stride + 6 ] = morphVec4.z;
  25781. buffer[ offset + stride + 7 ] = 0;
  25782. }
  25783. if ( hasMorphColors === true ) {
  25784. morphVec4.fromBufferAttribute( morphColor, j );
  25785. buffer[ offset + stride + 8 ] = morphVec4.x;
  25786. buffer[ offset + stride + 9 ] = morphVec4.y;
  25787. buffer[ offset + stride + 10 ] = morphVec4.z;
  25788. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morphVec4.w : 1;
  25789. }
  25790. }
  25791. }
  25792. entry = {
  25793. count: morphTargetsCount,
  25794. texture: bufferTexture,
  25795. stride: vertexDataCount,
  25796. size: new Vector2( width, height )
  25797. };
  25798. morphTextures.set( geometry, entry );
  25799. function disposeTexture() {
  25800. bufferTexture.dispose();
  25801. morphTextures.delete( geometry );
  25802. geometry.removeEventListener( 'dispose', disposeTexture );
  25803. }
  25804. geometry.addEventListener( 'dispose', disposeTexture );
  25805. }
  25806. return entry;
  25807. }
  25808. class MorphNode extends Node {
  25809. constructor( mesh ) {
  25810. super( 'void' );
  25811. this.mesh = mesh;
  25812. this.morphBaseInfluence = uniform( 1 );
  25813. this.updateType = NodeUpdateType.OBJECT;
  25814. }
  25815. setup( builder ) {
  25816. const { geometry } = builder;
  25817. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25818. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25819. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25820. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25821. // nodes
  25822. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25823. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25824. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25825. const width = int( size.width );
  25826. loop( morphTargetsCount, ( { i } ) => {
  25827. const influence = float( 0 ).toVar();
  25828. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25829. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25830. } else {
  25831. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25832. }
  25833. if ( hasMorphPosition === true ) {
  25834. positionLocal.addAssign( getMorph( {
  25835. bufferMap,
  25836. influence,
  25837. stride,
  25838. width,
  25839. depth: i,
  25840. offset: int( 0 )
  25841. } ) );
  25842. }
  25843. if ( hasMorphNormals === true ) {
  25844. normalLocal.addAssign( getMorph( {
  25845. bufferMap,
  25846. influence,
  25847. stride,
  25848. width,
  25849. depth: i,
  25850. offset: int( 1 )
  25851. } ) );
  25852. }
  25853. } );
  25854. }
  25855. update() {
  25856. const morphBaseInfluence = this.morphBaseInfluence;
  25857. if ( this.mesh.geometry.morphTargetsRelative ) {
  25858. morphBaseInfluence.value = 1;
  25859. } else {
  25860. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25861. }
  25862. }
  25863. }
  25864. const morphReference = nodeProxy( MorphNode );
  25865. addNodeClass( 'MorphNode', MorphNode );
  25866. const reflectView = /*#__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  25867. const reflectVector = /*#__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25868. class CubeTextureNode extends TextureNode {
  25869. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  25870. super( value, uvNode, levelNode, biasNode );
  25871. this.isCubeTextureNode = true;
  25872. }
  25873. getInputType( /*builder*/ ) {
  25874. return 'cubeTexture';
  25875. }
  25876. getDefaultUV() {
  25877. return reflectVector;
  25878. }
  25879. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  25880. setupUV( builder, uvNode ) {
  25881. const texture = this.value;
  25882. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  25883. return vec3( uvNode.x.negate(), uvNode.yz );
  25884. } else {
  25885. return uvNode;
  25886. }
  25887. }
  25888. generateUV( builder, cubeUV ) {
  25889. return cubeUV.build( builder, 'vec3' );
  25890. }
  25891. }
  25892. const cubeTexture = nodeProxy( CubeTextureNode );
  25893. addNodeElement( 'cubeTexture', cubeTexture );
  25894. addNodeClass( 'CubeTextureNode', CubeTextureNode );
  25895. class LightingNode extends Node {
  25896. constructor() {
  25897. super( 'vec3' );
  25898. }
  25899. generate( /*builder*/ ) {
  25900. console.warn( 'Abstract function.' );
  25901. }
  25902. }
  25903. addNodeClass( 'LightingNode', LightingNode );
  25904. let overrideMaterial = null;
  25905. class AnalyticLightNode extends LightingNode {
  25906. constructor( light = null ) {
  25907. super();
  25908. this.updateType = NodeUpdateType.FRAME;
  25909. this.light = light;
  25910. this.rtt = null;
  25911. this.shadowNode = null;
  25912. this.shadowMaskNode = null;
  25913. this.color = new Color();
  25914. this._defaultColorNode = uniform( this.color );
  25915. this.colorNode = this._defaultColorNode;
  25916. this.isAnalyticLightNode = true;
  25917. }
  25918. getCacheKey() {
  25919. return super.getCacheKey() + '-' + ( this.light.id + '-' + ( this.light.castShadow ? '1' : '0' ) );
  25920. }
  25921. getHash() {
  25922. return this.light.uuid;
  25923. }
  25924. setupShadow( builder ) {
  25925. const { object } = builder;
  25926. if ( object.receiveShadow === false ) return;
  25927. let shadowNode = this.shadowNode;
  25928. if ( shadowNode === null ) {
  25929. if ( overrideMaterial === null ) {
  25930. overrideMaterial = builder.createNodeMaterial();
  25931. overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  25932. overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  25933. }
  25934. const shadow = this.light.shadow;
  25935. const rtt = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25936. const depthTexture = new DepthTexture();
  25937. depthTexture.minFilter = NearestFilter;
  25938. depthTexture.magFilter = NearestFilter;
  25939. depthTexture.image.width = shadow.mapSize.width;
  25940. depthTexture.image.height = shadow.mapSize.height;
  25941. depthTexture.compareFunction = LessCompare;
  25942. rtt.depthTexture = depthTexture;
  25943. shadow.camera.updateProjectionMatrix();
  25944. //
  25945. const shadowIntensity = reference( 'intensity', 'float', shadow );
  25946. const bias = reference( 'bias', 'float', shadow );
  25947. const normalBias = reference( 'normalBias', 'float', shadow );
  25948. const position = object.material.shadowPositionNode || positionWorld;
  25949. let shadowCoord = uniform( shadow.matrix ).mul( position.add( normalWorld.mul( normalBias ) ) );
  25950. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25951. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25952. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25953. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25954. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25955. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25956. let coordZ = shadowCoord.z.add( bias );
  25957. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25958. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  25959. }
  25960. shadowCoord = vec3(
  25961. shadowCoord.x,
  25962. shadowCoord.y.oneMinus(), // follow webgpu standards
  25963. coordZ
  25964. );
  25965. const textureCompare = ( depthTexture, shadowCoord, compare ) => texture( depthTexture, shadowCoord ).compare( compare );
  25966. //const textureCompare = ( depthTexture, shadowCoord, compare ) => compare.step( texture( depthTexture, shadowCoord ) );
  25967. // BasicShadowMap
  25968. shadowNode = textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z );
  25969. // PCFShadowMap
  25970. /*
  25971. const mapSize = reference( 'mapSize', 'vec2', shadow );
  25972. const radius = reference( 'radius', 'float', shadow );
  25973. const texelSize = vec2( 1 ).div( mapSize );
  25974. const dx0 = texelSize.x.negate().mul( radius );
  25975. const dy0 = texelSize.y.negate().mul( radius );
  25976. const dx1 = texelSize.x.mul( radius );
  25977. const dy1 = texelSize.y.mul( radius );
  25978. const dx2 = dx0.mul( 2 );
  25979. const dy2 = dy0.mul( 2 );
  25980. const dx3 = dx1.mul( 2 );
  25981. const dy3 = dy1.mul( 2 );
  25982. shadowNode = add(
  25983. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25984. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25985. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25986. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25987. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25988. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25989. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25990. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25991. textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z ),
  25992. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25993. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25994. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25995. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25996. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25997. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25998. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25999. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  26000. ).mul( 1 / 17 );
  26001. */
  26002. //
  26003. const shadowColor = texture( rtt.texture, shadowCoord );
  26004. const shadowMaskNode = frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) );
  26005. this.rtt = rtt;
  26006. this.colorNode = this.colorNode.mul( mix( 1, shadowMaskNode, shadowIntensity ) );
  26007. this.shadowNode = shadowNode;
  26008. this.shadowMaskNode = shadowMaskNode;
  26009. //
  26010. this.updateBeforeType = NodeUpdateType.RENDER;
  26011. }
  26012. }
  26013. setup( builder ) {
  26014. if ( this.light.castShadow ) this.setupShadow( builder );
  26015. else if ( this.shadowNode !== null ) this.disposeShadow();
  26016. }
  26017. updateShadow( frame ) {
  26018. const { rtt, light } = this;
  26019. const { renderer, scene, camera } = frame;
  26020. const currentOverrideMaterial = scene.overrideMaterial;
  26021. scene.overrideMaterial = overrideMaterial;
  26022. rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  26023. light.shadow.updateMatrices( light );
  26024. light.shadow.camera.layers.mask = camera.layers.mask;
  26025. const currentToneMapping = renderer.toneMapping;
  26026. const currentRenderTarget = renderer.getRenderTarget();
  26027. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26028. renderer.setRenderObjectFunction( ( object, ...params ) => {
  26029. if ( object.castShadow === true ) {
  26030. renderer.renderObject( object, ...params );
  26031. }
  26032. } );
  26033. renderer.setRenderTarget( rtt );
  26034. renderer.toneMapping = NoToneMapping;
  26035. renderer.render( scene, light.shadow.camera );
  26036. renderer.setRenderTarget( currentRenderTarget );
  26037. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26038. renderer.toneMapping = currentToneMapping;
  26039. scene.overrideMaterial = currentOverrideMaterial;
  26040. }
  26041. disposeShadow() {
  26042. this.rtt.dispose();
  26043. this.shadowNode = null;
  26044. this.shadowMaskNode = null;
  26045. this.rtt = null;
  26046. this.colorNode = this._defaultColorNode;
  26047. }
  26048. updateBefore( frame ) {
  26049. const { light } = this;
  26050. if ( light.castShadow ) this.updateShadow( frame );
  26051. }
  26052. update( /*frame*/ ) {
  26053. const { light } = this;
  26054. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26055. }
  26056. }
  26057. addNodeClass( 'AnalyticLightNode', AnalyticLightNode );
  26058. const LightNodes = new WeakMap();
  26059. const sortLights = ( lights ) => {
  26060. return lights.sort( ( a, b ) => a.id - b.id );
  26061. };
  26062. class LightsNode extends Node {
  26063. constructor( lightNodes = [] ) {
  26064. super( 'vec3' );
  26065. this.totalDiffuseNode = vec3().temp( 'totalDiffuse' );
  26066. this.totalSpecularNode = vec3().temp( 'totalSpecular' );
  26067. this.outgoingLightNode = vec3().temp( 'outgoingLight' );
  26068. this.lightNodes = lightNodes;
  26069. this._hash = null;
  26070. }
  26071. get hasLight() {
  26072. return this.lightNodes.length > 0;
  26073. }
  26074. getHash() {
  26075. if ( this._hash === null ) {
  26076. const hash = [];
  26077. for ( const lightNode of this.lightNodes ) {
  26078. hash.push( lightNode.getHash() );
  26079. }
  26080. this._hash = 'lights-' + hash.join( ',' );
  26081. }
  26082. return this._hash;
  26083. }
  26084. analyze( builder ) {
  26085. const properties = builder.getDataFromNode( this );
  26086. for ( const node of properties.nodes ) {
  26087. node.build( builder );
  26088. }
  26089. }
  26090. setup( builder ) {
  26091. const context = builder.context;
  26092. const lightingModel = context.lightingModel;
  26093. let outgoingLightNode = this.outgoingLightNode;
  26094. if ( lightingModel ) {
  26095. const { lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  26096. context.outgoingLight = outgoingLightNode;
  26097. const stack = builder.addStack();
  26098. //
  26099. const properties = builder.getDataFromNode( this );
  26100. properties.nodes = stack.nodes;
  26101. //
  26102. lightingModel.start( context, stack, builder );
  26103. // lights
  26104. for ( const lightNode of lightNodes ) {
  26105. lightNode.build( builder );
  26106. }
  26107. //
  26108. lightingModel.indirectDiffuse( context, stack, builder );
  26109. lightingModel.indirectSpecular( context, stack, builder );
  26110. lightingModel.ambientOcclusion( context, stack, builder );
  26111. //
  26112. const { backdrop, backdropAlpha } = context;
  26113. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26114. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26115. if ( backdrop !== null ) {
  26116. if ( backdropAlpha !== null ) {
  26117. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26118. } else {
  26119. totalDiffuse = vec3( backdrop );
  26120. }
  26121. context.material.transparent = true;
  26122. }
  26123. totalDiffuseNode.assign( totalDiffuse );
  26124. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26125. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26126. //
  26127. lightingModel.finish( context, stack, builder );
  26128. //
  26129. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26130. }
  26131. return outgoingLightNode;
  26132. }
  26133. _getLightNodeById( id ) {
  26134. for ( const lightNode of this.lightNodes ) {
  26135. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26136. return lightNode;
  26137. }
  26138. }
  26139. return null;
  26140. }
  26141. fromLights( lights = [] ) {
  26142. const lightNodes = [];
  26143. lights = sortLights( lights );
  26144. for ( const light of lights ) {
  26145. let lightNode = this._getLightNodeById( light.id );
  26146. if ( lightNode === null ) {
  26147. const lightClass = light.constructor;
  26148. const lightNodeClass = LightNodes.has( lightClass ) ? LightNodes.get( lightClass ) : AnalyticLightNode;
  26149. lightNode = nodeObject( new lightNodeClass( light ) );
  26150. }
  26151. lightNodes.push( lightNode );
  26152. }
  26153. this.lightNodes = lightNodes;
  26154. this._hash = null;
  26155. return this;
  26156. }
  26157. }
  26158. const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) );
  26159. const lightsNode = nodeProxy( LightsNode );
  26160. function addLightNode( lightClass, lightNodeClass ) {
  26161. if ( LightNodes.has( lightClass ) ) {
  26162. console.warn( `Redefinition of light node ${ lightNodeClass.type }` );
  26163. return;
  26164. }
  26165. if ( typeof lightClass !== 'function' ) throw new Error( `Light ${ lightClass.name } is not a class` );
  26166. if ( typeof lightNodeClass !== 'function' || ! lightNodeClass.type ) throw new Error( `Light node ${ lightNodeClass.type } is not a class` );
  26167. LightNodes.set( lightClass, lightNodeClass );
  26168. }
  26169. class AONode extends LightingNode {
  26170. constructor( aoNode = null ) {
  26171. super();
  26172. this.aoNode = aoNode;
  26173. }
  26174. setup( builder ) {
  26175. const aoIntensity = 1;
  26176. const aoNode = this.aoNode.x.sub( 1.0 ).mul( aoIntensity ).add( 1.0 );
  26177. builder.context.ambientOcclusion.mulAssign( aoNode );
  26178. }
  26179. }
  26180. addNodeClass( 'AONode', AONode );
  26181. class LightingContextNode extends ContextNode {
  26182. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26183. super( node );
  26184. this.lightingModel = lightingModel;
  26185. this.backdropNode = backdropNode;
  26186. this.backdropAlphaNode = backdropAlphaNode;
  26187. this._context = null;
  26188. }
  26189. getContext() {
  26190. const { backdropNode, backdropAlphaNode } = this;
  26191. const directDiffuse = vec3().temp( 'directDiffuse' ),
  26192. directSpecular = vec3().temp( 'directSpecular' ),
  26193. indirectDiffuse = vec3().temp( 'indirectDiffuse' ),
  26194. indirectSpecular = vec3().temp( 'indirectSpecular' );
  26195. const reflectedLight = {
  26196. directDiffuse,
  26197. directSpecular,
  26198. indirectDiffuse,
  26199. indirectSpecular
  26200. };
  26201. const context = {
  26202. radiance: vec3().temp( 'radiance' ),
  26203. irradiance: vec3().temp( 'irradiance' ),
  26204. iblIrradiance: vec3().temp( 'iblIrradiance' ),
  26205. ambientOcclusion: float( 1 ).temp( 'ambientOcclusion' ),
  26206. reflectedLight,
  26207. backdrop: backdropNode,
  26208. backdropAlpha: backdropAlphaNode
  26209. };
  26210. return context;
  26211. }
  26212. setup( builder ) {
  26213. this.context = this._context || ( this._context = this.getContext() );
  26214. this.context.lightingModel = this.lightingModel || builder.context.lightingModel;
  26215. return super.setup( builder );
  26216. }
  26217. }
  26218. const lightingContext = nodeProxy( LightingContextNode );
  26219. addNodeElement( 'lightingContext', lightingContext );
  26220. addNodeClass( 'LightingContextNode', LightingContextNode );
  26221. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  26222. const bitangentGeometry = /*#__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  26223. const bitangentLocal = /*#__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  26224. const bitangentView = /*#__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  26225. const bitangentWorld = /*#__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  26226. const transformedBitangentView = /*#__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  26227. const transformedBitangentWorld = /*#__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  26228. const TBNViewMatrix = mat3( tangentView, bitangentView, normalView );
  26229. const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  26230. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  26231. const transformedBentNormalView = ( () => {
  26232. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  26233. let bentNormal = anisotropyB.cross( positionViewDirection );
  26234. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  26235. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  26236. return bentNormal;
  26237. } )();
  26238. class CondNode extends Node {
  26239. constructor( condNode, ifNode, elseNode = null ) {
  26240. super();
  26241. this.condNode = condNode;
  26242. this.ifNode = ifNode;
  26243. this.elseNode = elseNode;
  26244. }
  26245. getNodeType( builder ) {
  26246. const ifType = this.ifNode.getNodeType( builder );
  26247. if ( this.elseNode !== null ) {
  26248. const elseType = this.elseNode.getNodeType( builder );
  26249. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  26250. return elseType;
  26251. }
  26252. }
  26253. return ifType;
  26254. }
  26255. setup( builder ) {
  26256. const properties = builder.getNodeProperties( this );
  26257. properties.condNode = this.condNode.cache();
  26258. properties.ifNode = this.ifNode.cache();
  26259. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  26260. }
  26261. generate( builder, output ) {
  26262. const type = this.getNodeType( builder );
  26263. const nodeData = builder.getDataFromNode( this );
  26264. if ( nodeData.nodeProperty !== undefined ) {
  26265. return nodeData.nodeProperty;
  26266. }
  26267. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  26268. const needsOutput = output !== 'void';
  26269. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  26270. nodeData.nodeProperty = nodeProperty;
  26271. const nodeSnippet = condNode.build( builder, 'bool' );
  26272. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  26273. let ifSnippet = ifNode.build( builder, type );
  26274. if ( ifSnippet ) {
  26275. if ( needsOutput ) {
  26276. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  26277. } else {
  26278. ifSnippet = 'return ' + ifSnippet + ';';
  26279. }
  26280. }
  26281. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  26282. if ( elseNode !== null ) {
  26283. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  26284. let elseSnippet = elseNode.build( builder, type );
  26285. if ( elseSnippet ) {
  26286. if ( needsOutput ) {
  26287. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  26288. } else {
  26289. elseSnippet = 'return ' + elseSnippet + ';';
  26290. }
  26291. }
  26292. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  26293. } else {
  26294. builder.addFlowCode( '\n\n' );
  26295. }
  26296. return builder.format( nodeProperty, type, output );
  26297. }
  26298. }
  26299. const cond = nodeProxy( CondNode );
  26300. addNodeElement( 'cond', cond );
  26301. addNodeClass( 'CondNode', CondNode );
  26302. // These defines must match with PMREMGenerator
  26303. const cubeUV_r0 = float( 1.0 );
  26304. const cubeUV_m0 = float( - 2.0 );
  26305. const cubeUV_r1 = float( 0.8 );
  26306. const cubeUV_m1 = float( - 1.0 );
  26307. const cubeUV_r4 = float( 0.4 );
  26308. const cubeUV_m4 = float( 2.0 );
  26309. const cubeUV_r5 = float( 0.305 );
  26310. const cubeUV_m5 = float( 3.0 );
  26311. const cubeUV_r6 = float( 0.21 );
  26312. const cubeUV_m6 = float( 4.0 );
  26313. const cubeUV_minMipLevel = float( 4.0 );
  26314. const cubeUV_minTileSize = float( 16.0 );
  26315. // These shader functions convert between the UV coordinates of a single face of
  26316. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  26317. // sampling a textureCube (not generally normalized ).
  26318. const getFace = tslFn( ( [ direction ] ) => {
  26319. const absDirection = vec3( abs( direction ) ).toVar();
  26320. const face = float( - 1.0 ).toVar();
  26321. If( absDirection.x.greaterThan( absDirection.z ), () => {
  26322. If( absDirection.x.greaterThan( absDirection.y ), () => {
  26323. face.assign( cond( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  26324. } ).else( () => {
  26325. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  26326. } );
  26327. } ).else( () => {
  26328. If( absDirection.z.greaterThan( absDirection.y ), () => {
  26329. face.assign( cond( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  26330. } ).else( () => {
  26331. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  26332. } );
  26333. } );
  26334. return face;
  26335. } ).setLayout( {
  26336. name: 'getFace',
  26337. type: 'float',
  26338. inputs: [
  26339. { name: 'direction', type: 'vec3' }
  26340. ]
  26341. } );
  26342. // RH coordinate system; PMREM face-indexing convention
  26343. const getUV = tslFn( ( [ direction, face ] ) => {
  26344. const uv = vec2().toVar();
  26345. If( face.equal( 0.0 ), () => {
  26346. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  26347. } ).elseif( face.equal( 1.0 ), () => {
  26348. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  26349. } ).elseif( face.equal( 2.0 ), () => {
  26350. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  26351. } ).elseif( face.equal( 3.0 ), () => {
  26352. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  26353. } ).elseif( face.equal( 4.0 ), () => {
  26354. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  26355. } ).else( () => {
  26356. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  26357. } );
  26358. return mul( 0.5, uv.add( 1.0 ) );
  26359. } ).setLayout( {
  26360. name: 'getUV',
  26361. type: 'vec2',
  26362. inputs: [
  26363. { name: 'direction', type: 'vec3' },
  26364. { name: 'face', type: 'float' }
  26365. ]
  26366. } );
  26367. const roughnessToMip = tslFn( ( [ roughness ] ) => {
  26368. const mip = float( 0.0 ).toVar();
  26369. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  26370. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  26371. } ).elseif( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  26372. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  26373. } ).elseif( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  26374. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  26375. } ).elseif( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  26376. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  26377. } ).else( () => {
  26378. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  26379. } );
  26380. return mip;
  26381. } ).setLayout( {
  26382. name: 'roughnessToMip',
  26383. type: 'float',
  26384. inputs: [
  26385. { name: 'roughness', type: 'float' }
  26386. ]
  26387. } );
  26388. // RH coordinate system; PMREM face-indexing convention
  26389. const getDirection = tslFn( ( [ uv_immutable, face ] ) => {
  26390. const uv = uv_immutable.toVar();
  26391. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  26392. const direction = vec3( uv, 1.0 ).toVar();
  26393. If( face.equal( 0.0 ), () => {
  26394. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  26395. } ).elseif( face.equal( 1.0 ), () => {
  26396. direction.assign( direction.xzy );
  26397. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  26398. } ).elseif( face.equal( 2.0 ), () => {
  26399. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  26400. } ).elseif( face.equal( 3.0 ), () => {
  26401. direction.assign( direction.zyx );
  26402. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  26403. } ).elseif( face.equal( 4.0 ), () => {
  26404. direction.assign( direction.xzy );
  26405. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  26406. } ).elseif( face.equal( 5.0 ), () => {
  26407. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  26408. } );
  26409. return direction;
  26410. } ).setLayout( {
  26411. name: 'getDirection',
  26412. type: 'vec3',
  26413. inputs: [
  26414. { name: 'uv', type: 'vec2' },
  26415. { name: 'face', type: 'float' }
  26416. ]
  26417. } );
  26418. //
  26419. const textureCubeUV = tslFn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  26420. const roughness = float( roughness_immutable );
  26421. const sampleDir = vec3( sampleDir_immutable );
  26422. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  26423. const mipF = fract( mip );
  26424. const mipInt = floor( mip );
  26425. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  26426. If( mipF.notEqual( 0.0 ), () => {
  26427. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  26428. color0.assign( mix( color0, color1, mipF ) );
  26429. } );
  26430. return color0;
  26431. } );
  26432. const bilinearCubeUV = tslFn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  26433. const mipInt = float( mipInt_immutable ).toVar();
  26434. const direction = vec3( direction_immutable );
  26435. const face = float( getFace( direction ) ).toVar();
  26436. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  26437. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  26438. const faceSize = float( exp2( mipInt ) ).toVar();
  26439. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  26440. If( face.greaterThan( 2.0 ), () => {
  26441. uv.y.addAssign( faceSize );
  26442. face.subAssign( 3.0 );
  26443. } );
  26444. uv.x.addAssign( face.mul( faceSize ) );
  26445. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  26446. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  26447. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  26448. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  26449. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  26450. } );
  26451. const getSample = tslFn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  26452. const cosTheta = cos( theta );
  26453. // Rodrigues' axis-angle rotation
  26454. const sampleDirection = outputDirection.mul( cosTheta )
  26455. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  26456. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  26457. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  26458. } );
  26459. const blur = tslFn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  26460. const axis = vec3( cond( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  26461. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  26462. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  26463. } );
  26464. axis.assign( normalize( axis ) );
  26465. const gl_FragColor = vec3().toVar();
  26466. 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 } ) ) );
  26467. loop( { start: int( 1 ), end: n }, ( { i } ) => {
  26468. If( i.greaterThanEqual( samples ), () => {
  26469. Break();
  26470. } );
  26471. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  26472. 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 } ) ) );
  26473. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  26474. } );
  26475. return vec4( gl_FragColor, 1 );
  26476. } );
  26477. let _generator = null;
  26478. const _cache = new WeakMap();
  26479. function _generateCubeUVSize( imageHeight ) {
  26480. const maxMip = Math.log2( imageHeight ) - 2;
  26481. const texelHeight = 1.0 / imageHeight;
  26482. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  26483. return { texelWidth, texelHeight, maxMip };
  26484. }
  26485. function _getPMREMFromTexture( texture ) {
  26486. let cacheTexture = _cache.get( texture );
  26487. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  26488. if ( pmremVersion !== texture.pmremVersion ) {
  26489. if ( texture.isCubeTexture ) {
  26490. if ( texture.source.data.some( ( texture ) => texture === undefined ) ) {
  26491. throw new Error( 'PMREMNode: Undefined texture in CubeTexture. Use onLoad callback or async loader' );
  26492. }
  26493. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  26494. } else {
  26495. if ( texture.image === undefined ) {
  26496. throw new Error( 'PMREMNode: Undefined image in Texture. Use onLoad callback or async loader' );
  26497. }
  26498. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  26499. }
  26500. cacheTexture.pmremVersion = texture.pmremVersion;
  26501. _cache.set( texture, cacheTexture );
  26502. }
  26503. return cacheTexture.texture;
  26504. }
  26505. class PMREMNode extends TempNode {
  26506. constructor( value, uvNode = null, levelNode = null ) {
  26507. super( 'vec3' );
  26508. this._value = value;
  26509. this._pmrem = null;
  26510. this.uvNode = uvNode;
  26511. this.levelNode = levelNode;
  26512. this._generator = null;
  26513. this._texture = texture( null );
  26514. this._width = uniform( 0 );
  26515. this._height = uniform( 0 );
  26516. this._maxMip = uniform( 0 );
  26517. this.updateBeforeType = NodeUpdateType.RENDER;
  26518. }
  26519. set value( value ) {
  26520. this._value = value;
  26521. this._pmrem = null;
  26522. }
  26523. get value() {
  26524. return this._value;
  26525. }
  26526. updateFromTexture( texture ) {
  26527. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  26528. this._texture.value = texture;
  26529. this._width.value = cubeUVSize.texelWidth;
  26530. this._height.value = cubeUVSize.texelHeight;
  26531. this._maxMip.value = cubeUVSize.maxMip;
  26532. }
  26533. updateBefore() {
  26534. let pmrem = this._pmrem;
  26535. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  26536. const texture = this._value;
  26537. if ( pmremVersion !== texture.pmremVersion ) {
  26538. if ( texture.isPMREMTexture === true ) {
  26539. pmrem = texture;
  26540. } else {
  26541. pmrem = _getPMREMFromTexture( texture );
  26542. }
  26543. this._pmrem = pmrem;
  26544. this.updateFromTexture( pmrem );
  26545. }
  26546. }
  26547. setup( builder ) {
  26548. if ( _generator === null ) {
  26549. _generator = builder.createPMREMGenerator();
  26550. }
  26551. //
  26552. this.updateBefore( builder );
  26553. //
  26554. let uvNode = this.uvNode;
  26555. if ( uvNode === null && builder.context.getUV ) {
  26556. uvNode = builder.context.getUV( this );
  26557. }
  26558. //
  26559. const texture = this.value;
  26560. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  26561. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  26562. }
  26563. //
  26564. let levelNode = this.levelNode;
  26565. if ( levelNode === null && builder.context.getTextureLevel ) {
  26566. levelNode = builder.context.getTextureLevel( this );
  26567. }
  26568. //
  26569. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  26570. }
  26571. }
  26572. const pmremTexture = nodeProxy( PMREMNode );
  26573. addNodeClass( 'PMREMNode', PMREMNode );
  26574. const envNodeCache = new WeakMap();
  26575. class EnvironmentNode extends LightingNode {
  26576. constructor( envNode = null ) {
  26577. super();
  26578. this.envNode = envNode;
  26579. }
  26580. setup( builder ) {
  26581. let envNode = this.envNode;
  26582. if ( envNode.isTextureNode ) {
  26583. let cacheEnvNode = envNodeCache.get( envNode.value );
  26584. if ( cacheEnvNode === undefined ) {
  26585. cacheEnvNode = pmremTexture( envNode.value );
  26586. envNodeCache.set( envNode.value, cacheEnvNode );
  26587. }
  26588. envNode = cacheEnvNode;
  26589. }
  26590. //
  26591. const { material } = builder;
  26592. const envMap = material.envMap;
  26593. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  26594. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  26595. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  26596. const radiance = context( envNode, createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  26597. const irradiance = context( envNode, createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  26598. const isolateRadiance = cache( radiance );
  26599. const isolateIrradiance = cache( irradiance );
  26600. //
  26601. builder.context.radiance.addAssign( isolateRadiance );
  26602. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  26603. //
  26604. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  26605. if ( clearcoatRadiance ) {
  26606. const clearcoatRadianceContext = context( envNode, createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  26607. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  26608. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  26609. }
  26610. }
  26611. }
  26612. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  26613. let reflectVec = null;
  26614. return {
  26615. getUV: () => {
  26616. if ( reflectVec === null ) {
  26617. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  26618. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  26619. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  26620. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  26621. }
  26622. return reflectVec;
  26623. },
  26624. getTextureLevel: () => {
  26625. return roughnessNode;
  26626. }
  26627. };
  26628. };
  26629. const createIrradianceContext = ( normalWorldNode ) => {
  26630. return {
  26631. getUV: () => {
  26632. return normalWorldNode;
  26633. },
  26634. getTextureLevel: () => {
  26635. return float( 1.0 );
  26636. }
  26637. };
  26638. };
  26639. addNodeClass( 'EnvironmentNode', EnvironmentNode );
  26640. class IrradianceNode extends LightingNode {
  26641. constructor( node ) {
  26642. super();
  26643. this.node = node;
  26644. }
  26645. setup( builder ) {
  26646. builder.context.irradiance.addAssign( this.node );
  26647. }
  26648. }
  26649. addNodeClass( 'IrradianceNode', IrradianceNode );
  26650. let resolution, viewportResult;
  26651. class ViewportNode extends Node {
  26652. constructor( scope ) {
  26653. super();
  26654. this.scope = scope;
  26655. this.isViewportNode = true;
  26656. }
  26657. getNodeType() {
  26658. if ( this.scope === ViewportNode.VIEWPORT ) return 'vec4';
  26659. else if ( this.scope === ViewportNode.COORDINATE ) return 'vec3';
  26660. else return 'vec2';
  26661. }
  26662. getUpdateType() {
  26663. let updateType = NodeUpdateType.NONE;
  26664. if ( this.scope === ViewportNode.RESOLUTION || this.scope === ViewportNode.VIEWPORT ) {
  26665. updateType = NodeUpdateType.RENDER;
  26666. }
  26667. this.updateType = updateType;
  26668. return updateType;
  26669. }
  26670. update( { renderer } ) {
  26671. if ( this.scope === ViewportNode.VIEWPORT ) {
  26672. renderer.getViewport( viewportResult );
  26673. } else {
  26674. renderer.getDrawingBufferSize( resolution );
  26675. }
  26676. }
  26677. setup( /*builder*/ ) {
  26678. const scope = this.scope;
  26679. let output = null;
  26680. if ( scope === ViewportNode.RESOLUTION ) {
  26681. output = uniform( resolution || ( resolution = new Vector2() ) );
  26682. } else if ( scope === ViewportNode.VIEWPORT ) {
  26683. output = uniform( viewportResult || ( viewportResult = new Vector4() ) );
  26684. } else {
  26685. output = viewportCoordinate.div( viewportResolution );
  26686. let outX = output.x;
  26687. let outY = output.y;
  26688. if ( /bottom/i.test( scope ) ) outY = outY.oneMinus();
  26689. if ( /right/i.test( scope ) ) outX = outX.oneMinus();
  26690. output = vec2( outX, outY );
  26691. }
  26692. return output;
  26693. }
  26694. generate( builder ) {
  26695. if ( this.scope === ViewportNode.COORDINATE ) {
  26696. let coord = builder.getFragCoord();
  26697. if ( builder.isFlipY() ) {
  26698. // follow webgpu standards
  26699. const resolution = builder.getNodeProperties( viewportResolution ).outputNode.build( builder );
  26700. coord = `${ builder.getType( 'vec3' ) }( ${ coord }.x, ${ resolution }.y - ${ coord }.y, ${ coord }.z )`;
  26701. }
  26702. return coord;
  26703. }
  26704. return super.generate( builder );
  26705. }
  26706. }
  26707. ViewportNode.COORDINATE = 'coordinate';
  26708. ViewportNode.RESOLUTION = 'resolution';
  26709. ViewportNode.VIEWPORT = 'viewport';
  26710. ViewportNode.TOP_LEFT = 'topLeft';
  26711. ViewportNode.BOTTOM_LEFT = 'bottomLeft';
  26712. ViewportNode.TOP_RIGHT = 'topRight';
  26713. ViewportNode.BOTTOM_RIGHT = 'bottomRight';
  26714. const viewportCoordinate = nodeImmutable( ViewportNode, ViewportNode.COORDINATE );
  26715. const viewportResolution = nodeImmutable( ViewportNode, ViewportNode.RESOLUTION );
  26716. const viewport = nodeImmutable( ViewportNode, ViewportNode.VIEWPORT );
  26717. const viewportTopLeft = nodeImmutable( ViewportNode, ViewportNode.TOP_LEFT );
  26718. const viewportBottomLeft = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_LEFT );
  26719. const viewportTopRight = nodeImmutable( ViewportNode, ViewportNode.TOP_RIGHT );
  26720. const viewportBottomRight = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_RIGHT );
  26721. addNodeClass( 'ViewportNode', ViewportNode );
  26722. const _size$5 = new Vector2();
  26723. class ViewportTextureNode extends TextureNode {
  26724. constructor( uvNode = viewportTopLeft, levelNode = null, framebufferTexture = null ) {
  26725. if ( framebufferTexture === null ) {
  26726. framebufferTexture = new FramebufferTexture();
  26727. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26728. }
  26729. super( framebufferTexture, uvNode, levelNode );
  26730. this.generateMipmaps = false;
  26731. this.isOutputTextureNode = true;
  26732. this.updateBeforeType = NodeUpdateType.FRAME;
  26733. }
  26734. updateBefore( frame ) {
  26735. const renderer = frame.renderer;
  26736. renderer.getDrawingBufferSize( _size$5 );
  26737. //
  26738. const framebufferTexture = this.value;
  26739. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  26740. framebufferTexture.image.width = _size$5.width;
  26741. framebufferTexture.image.height = _size$5.height;
  26742. framebufferTexture.needsUpdate = true;
  26743. }
  26744. //
  26745. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26746. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26747. renderer.copyFramebufferToTexture( framebufferTexture );
  26748. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26749. }
  26750. clone() {
  26751. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26752. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26753. return viewportTextureNode;
  26754. }
  26755. }
  26756. const viewportTexture = nodeProxy( ViewportTextureNode );
  26757. const viewportMipTexture = nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26758. addNodeElement( 'viewportTexture', viewportTexture );
  26759. addNodeElement( 'viewportMipTexture', viewportMipTexture );
  26760. addNodeClass( 'ViewportTextureNode', ViewportTextureNode );
  26761. let sharedDepthbuffer = null;
  26762. class ViewportDepthTextureNode extends ViewportTextureNode {
  26763. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  26764. if ( sharedDepthbuffer === null ) {
  26765. sharedDepthbuffer = new DepthTexture();
  26766. }
  26767. super( uvNode, levelNode, sharedDepthbuffer );
  26768. }
  26769. }
  26770. const viewportDepthTexture = nodeProxy( ViewportDepthTextureNode );
  26771. addNodeElement( 'viewportDepthTexture', viewportDepthTexture );
  26772. addNodeClass( 'ViewportDepthTextureNode', ViewportDepthTextureNode );
  26773. class ViewportDepthNode extends Node {
  26774. constructor( scope, valueNode = null ) {
  26775. super( 'float' );
  26776. this.scope = scope;
  26777. this.valueNode = valueNode;
  26778. this.isViewportDepthNode = true;
  26779. }
  26780. generate( builder ) {
  26781. const { scope } = this;
  26782. if ( scope === ViewportDepthNode.DEPTH ) {
  26783. return builder.getFragDepth();
  26784. }
  26785. return super.generate( builder );
  26786. }
  26787. setup( { camera } ) {
  26788. const { scope } = this;
  26789. const texture = this.valueNode;
  26790. let node = null;
  26791. if ( scope === ViewportDepthNode.DEPTH ) {
  26792. if ( texture !== null ) {
  26793. node = depthBase().assign( texture );
  26794. } else {
  26795. if ( camera.isPerspectiveCamera ) {
  26796. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26797. } else {
  26798. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26799. }
  26800. }
  26801. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26802. if ( texture !== null ) {
  26803. if ( camera.isPerspectiveCamera ) {
  26804. const viewZ = perspectiveDepthToViewZ( texture, cameraNear, cameraFar );
  26805. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26806. } else {
  26807. node = texture;
  26808. }
  26809. } else {
  26810. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26811. }
  26812. }
  26813. return node;
  26814. }
  26815. }
  26816. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26817. // -near maps to 0; -far maps to 1
  26818. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26819. // maps orthographic depth in [ 0, 1 ] to viewZ
  26820. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26821. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26822. // -near maps to 0; -far maps to 1
  26823. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26824. // maps perspective depth in [ 0, 1 ] to viewZ
  26825. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26826. ViewportDepthNode.DEPTH = 'depth';
  26827. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26828. const depthBase = nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26829. const depth = nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26830. const linearDepth = nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26831. const viewportLinearDepth = linearDepth( viewportDepthTexture() );
  26832. depth.assign = ( value ) => depthBase( value );
  26833. addNodeClass( 'ViewportDepthNode', ViewportDepthNode );
  26834. class ClippingNode extends Node {
  26835. constructor( scope = ClippingNode.DEFAULT ) {
  26836. super();
  26837. this.scope = scope;
  26838. }
  26839. setup( builder ) {
  26840. super.setup( builder );
  26841. const clippingContext = builder.clippingContext;
  26842. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26843. const numClippingPlanes = globalClippingCount + localClippingCount;
  26844. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26845. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26846. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26847. } else {
  26848. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26849. }
  26850. }
  26851. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26852. return tslFn( () => {
  26853. const clippingPlanes = uniforms( planes );
  26854. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26855. const distanceGradient = property( 'float', 'distanceToGradient' );
  26856. const clipOpacity = property( 'float', 'clipOpacity' );
  26857. clipOpacity.assign( 1 );
  26858. let plane;
  26859. loop( numUnionClippingPlanes, ( { i } ) => {
  26860. plane = clippingPlanes.element( i );
  26861. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26862. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26863. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26864. clipOpacity.equal( 0.0 ).discard();
  26865. } );
  26866. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26867. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26868. unionClipOpacity.assign( 1 );
  26869. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26870. plane = clippingPlanes.element( i );
  26871. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26872. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26873. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26874. } );
  26875. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26876. }
  26877. diffuseColor.a.mulAssign( clipOpacity );
  26878. diffuseColor.a.equal( 0.0 ).discard();
  26879. } )();
  26880. }
  26881. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26882. return tslFn( () => {
  26883. const clippingPlanes = uniforms( planes );
  26884. let plane;
  26885. loop( numUnionClippingPlanes, ( { i } ) => {
  26886. plane = clippingPlanes.element( i );
  26887. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26888. } );
  26889. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26890. const clipped = property( 'bool', 'clipped' );
  26891. clipped.assign( true );
  26892. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26893. plane = clippingPlanes.element( i );
  26894. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26895. } );
  26896. clipped.discard();
  26897. }
  26898. } )();
  26899. }
  26900. }
  26901. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26902. ClippingNode.DEFAULT = 'default';
  26903. const clipping = () => nodeObject( new ClippingNode() );
  26904. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26905. class FrontFacingNode extends Node {
  26906. constructor() {
  26907. super( 'bool' );
  26908. this.isFrontFacingNode = true;
  26909. }
  26910. generate( builder ) {
  26911. const { renderer, material } = builder;
  26912. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  26913. if ( material.side === BackSide ) {
  26914. return 'false';
  26915. }
  26916. }
  26917. return builder.getFrontFacing();
  26918. }
  26919. }
  26920. const frontFacing = nodeImmutable( FrontFacingNode );
  26921. const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  26922. addNodeClass( 'FrontFacingNode', FrontFacingNode );
  26923. const NodeMaterials = new Map();
  26924. class NodeMaterial extends Material {
  26925. constructor() {
  26926. super();
  26927. this.isNodeMaterial = true;
  26928. this.type = this.constructor.type;
  26929. this.forceSinglePass = false;
  26930. this.fog = true;
  26931. this.lights = true;
  26932. this.normals = true;
  26933. this.lightsNode = null;
  26934. this.envNode = null;
  26935. this.aoNode = null;
  26936. this.colorNode = null;
  26937. this.normalNode = null;
  26938. this.opacityNode = null;
  26939. this.backdropNode = null;
  26940. this.backdropAlphaNode = null;
  26941. this.alphaTestNode = null;
  26942. this.positionNode = null;
  26943. this.depthNode = null;
  26944. this.shadowNode = null;
  26945. this.shadowPositionNode = null;
  26946. this.outputNode = null;
  26947. this.fragmentNode = null;
  26948. this.vertexNode = null;
  26949. }
  26950. customProgramCacheKey() {
  26951. return this.type + getCacheKey( this );
  26952. }
  26953. build( builder ) {
  26954. this.setup( builder );
  26955. }
  26956. setup( builder ) {
  26957. // < VERTEX STAGE >
  26958. builder.addStack();
  26959. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26960. builder.addFlow( 'vertex', builder.removeStack() );
  26961. // < FRAGMENT STAGE >
  26962. builder.addStack();
  26963. let resultNode;
  26964. const clippingNode = this.setupClipping( builder );
  26965. if ( this.depthWrite === true ) this.setupDepth( builder );
  26966. if ( this.fragmentNode === null ) {
  26967. if ( this.normals === true ) this.setupNormal( builder );
  26968. this.setupDiffuseColor( builder );
  26969. this.setupVariants( builder );
  26970. const outgoingLightNode = this.setupLighting( builder );
  26971. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26972. // force unsigned floats - useful for RenderTargets
  26973. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26974. resultNode = this.setupOutput( builder, basicOutput );
  26975. // OUTPUT NODE
  26976. output.assign( resultNode );
  26977. //
  26978. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26979. } else {
  26980. let fragmentNode = this.fragmentNode;
  26981. if ( fragmentNode.isOutputStructNode !== true ) {
  26982. fragmentNode = vec4( fragmentNode );
  26983. }
  26984. resultNode = this.setupOutput( builder, fragmentNode );
  26985. }
  26986. builder.stack.outputNode = resultNode;
  26987. builder.addFlow( 'fragment', builder.removeStack() );
  26988. }
  26989. setupClipping( builder ) {
  26990. if ( builder.clippingContext === null ) return null;
  26991. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26992. let result = null;
  26993. if ( globalClippingCount || localClippingCount ) {
  26994. if ( this.alphaToCoverage ) {
  26995. // to be added to flow when the color/alpha value has been determined
  26996. result = clippingAlpha();
  26997. } else {
  26998. builder.stack.add( clipping() );
  26999. }
  27000. }
  27001. return result;
  27002. }
  27003. setupDepth( builder ) {
  27004. const { renderer } = builder;
  27005. // Depth
  27006. let depthNode = this.depthNode;
  27007. if ( depthNode === null && renderer.logarithmicDepthBuffer === true ) {
  27008. const fragDepth = modelViewProjection().w.add( 1 );
  27009. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  27010. }
  27011. if ( depthNode !== null ) {
  27012. depth.assign( depthNode ).append();
  27013. }
  27014. }
  27015. setupPosition( builder ) {
  27016. const { object } = builder;
  27017. const geometry = object.geometry;
  27018. builder.addStack();
  27019. // Vertex
  27020. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  27021. morphReference( object ).append();
  27022. }
  27023. if ( object.isSkinnedMesh === true ) {
  27024. skinningReference( object ).append();
  27025. }
  27026. if ( this.displacementMap ) {
  27027. const displacementMap = materialReference( 'displacementMap', 'texture' );
  27028. const displacementScale = materialReference( 'displacementScale', 'float' );
  27029. const displacementBias = materialReference( 'displacementBias', 'float' );
  27030. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  27031. }
  27032. if ( object.isBatchedMesh ) {
  27033. batch( object ).append();
  27034. }
  27035. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  27036. instance( object ).append();
  27037. }
  27038. if ( this.positionNode !== null ) {
  27039. positionLocal.assign( this.positionNode );
  27040. }
  27041. const mvp = modelViewProjection();
  27042. builder.context.vertex = builder.removeStack();
  27043. builder.context.mvp = mvp;
  27044. return mvp;
  27045. }
  27046. setupDiffuseColor( { object, geometry } ) {
  27047. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  27048. // VERTEX COLORS
  27049. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  27050. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  27051. }
  27052. // Instanced colors
  27053. if ( object.instanceColor ) {
  27054. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  27055. colorNode = instanceColor.mul( colorNode );
  27056. }
  27057. // COLOR
  27058. diffuseColor.assign( colorNode );
  27059. // OPACITY
  27060. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27061. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  27062. // ALPHA TEST
  27063. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  27064. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  27065. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  27066. }
  27067. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  27068. diffuseColor.a.assign( 1.0 );
  27069. }
  27070. }
  27071. setupVariants( /*builder*/ ) {
  27072. // Interface function.
  27073. }
  27074. setupNormal() {
  27075. // NORMAL VIEW
  27076. if ( this.flatShading === true ) {
  27077. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  27078. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  27079. } else {
  27080. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  27081. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  27082. }
  27083. }
  27084. getEnvNode( builder ) {
  27085. let node = null;
  27086. if ( this.envNode ) {
  27087. node = this.envNode;
  27088. } else if ( this.envMap ) {
  27089. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  27090. } else if ( builder.environmentNode ) {
  27091. node = builder.environmentNode;
  27092. }
  27093. return node;
  27094. }
  27095. setupLights( builder ) {
  27096. const envNode = this.getEnvNode( builder );
  27097. //
  27098. const materialLightsNode = [];
  27099. if ( envNode ) {
  27100. materialLightsNode.push( new EnvironmentNode( envNode ) );
  27101. }
  27102. if ( builder.material.lightMap ) {
  27103. materialLightsNode.push( new IrradianceNode( materialReference( 'lightMap', 'texture' ) ) );
  27104. }
  27105. if ( this.aoNode !== null || builder.material.aoMap ) {
  27106. const aoNode = this.aoNode !== null ? this.aoNode : texture( builder.material.aoMap );
  27107. materialLightsNode.push( new AONode( aoNode ) );
  27108. }
  27109. let lightsN = this.lightsNode || builder.lightsNode;
  27110. if ( materialLightsNode.length > 0 ) {
  27111. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  27112. }
  27113. return lightsN;
  27114. }
  27115. setupLightingModel( /*builder*/ ) {
  27116. // Interface function.
  27117. }
  27118. setupLighting( builder ) {
  27119. const { material } = builder;
  27120. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  27121. // OUTGOING LIGHT
  27122. const lights = this.lights === true || this.lightsNode !== null;
  27123. const lightsNode = lights ? this.setupLights( builder ) : null;
  27124. let outgoingLightNode = diffuseColor.rgb;
  27125. if ( lightsNode && lightsNode.hasLight !== false ) {
  27126. const lightingModel = this.setupLightingModel( builder );
  27127. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  27128. } else if ( backdropNode !== null ) {
  27129. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  27130. }
  27131. // EMISSIVE
  27132. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  27133. outgoingLightNode = outgoingLightNode.add( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  27134. }
  27135. return outgoingLightNode;
  27136. }
  27137. setupOutput( builder, outputNode ) {
  27138. // FOG
  27139. if ( this.fog === true ) {
  27140. const fogNode = builder.fogNode;
  27141. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  27142. }
  27143. return outputNode;
  27144. }
  27145. setDefaultValues( material ) {
  27146. // This approach is to reuse the native refreshUniforms*
  27147. // and turn available the use of features like transmission and environment in core
  27148. for ( const property in material ) {
  27149. const value = material[ property ];
  27150. if ( this[ property ] === undefined ) {
  27151. this[ property ] = value;
  27152. if ( value && value.clone ) this[ property ] = value.clone();
  27153. }
  27154. }
  27155. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  27156. for ( const key in descriptors ) {
  27157. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  27158. descriptors[ key ].get !== undefined ) {
  27159. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  27160. }
  27161. }
  27162. }
  27163. toJSON( meta ) {
  27164. const isRoot = ( meta === undefined || typeof meta === 'string' );
  27165. if ( isRoot ) {
  27166. meta = {
  27167. textures: {},
  27168. images: {},
  27169. nodes: {}
  27170. };
  27171. }
  27172. const data = Material.prototype.toJSON.call( this, meta );
  27173. const nodeChildren = getNodeChildren( this );
  27174. data.inputNodes = {};
  27175. for ( const { property, childNode } of nodeChildren ) {
  27176. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  27177. }
  27178. // TODO: Copied from Object3D.toJSON
  27179. function extractFromCache( cache ) {
  27180. const values = [];
  27181. for ( const key in cache ) {
  27182. const data = cache[ key ];
  27183. delete data.metadata;
  27184. values.push( data );
  27185. }
  27186. return values;
  27187. }
  27188. if ( isRoot ) {
  27189. const textures = extractFromCache( meta.textures );
  27190. const images = extractFromCache( meta.images );
  27191. const nodes = extractFromCache( meta.nodes );
  27192. if ( textures.length > 0 ) data.textures = textures;
  27193. if ( images.length > 0 ) data.images = images;
  27194. if ( nodes.length > 0 ) data.nodes = nodes;
  27195. }
  27196. return data;
  27197. }
  27198. copy( source ) {
  27199. this.lightsNode = source.lightsNode;
  27200. this.envNode = source.envNode;
  27201. this.colorNode = source.colorNode;
  27202. this.normalNode = source.normalNode;
  27203. this.opacityNode = source.opacityNode;
  27204. this.backdropNode = source.backdropNode;
  27205. this.backdropAlphaNode = source.backdropAlphaNode;
  27206. this.alphaTestNode = source.alphaTestNode;
  27207. this.positionNode = source.positionNode;
  27208. this.depthNode = source.depthNode;
  27209. this.shadowNode = source.shadowNode;
  27210. this.shadowPositionNode = source.shadowPositionNode;
  27211. this.outputNode = source.outputNode;
  27212. this.fragmentNode = source.fragmentNode;
  27213. this.vertexNode = source.vertexNode;
  27214. return super.copy( source );
  27215. }
  27216. static fromMaterial( material ) {
  27217. if ( material.isNodeMaterial === true ) { // is already a node material
  27218. return material;
  27219. }
  27220. const type = material.type.replace( 'Material', 'NodeMaterial' );
  27221. const nodeMaterial = createNodeMaterialFromType( type );
  27222. if ( nodeMaterial === undefined ) {
  27223. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  27224. }
  27225. for ( const key in material ) {
  27226. nodeMaterial[ key ] = material[ key ];
  27227. }
  27228. return nodeMaterial;
  27229. }
  27230. }
  27231. function addNodeMaterial( type, nodeMaterial ) {
  27232. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  27233. if ( NodeMaterials.has( type ) ) {
  27234. console.warn( `Redefinition of node material ${ type }` );
  27235. return;
  27236. }
  27237. NodeMaterials.set( type, nodeMaterial );
  27238. nodeMaterial.type = type;
  27239. }
  27240. function createNodeMaterialFromType( type ) {
  27241. const Material = NodeMaterials.get( type );
  27242. if ( Material !== undefined ) {
  27243. return new Material();
  27244. }
  27245. }
  27246. addNodeMaterial( 'NodeMaterial', NodeMaterial );
  27247. class Uniform {
  27248. constructor( name, value ) {
  27249. this.name = name;
  27250. this.value = value;
  27251. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  27252. this.itemSize = 0;
  27253. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  27254. }
  27255. setValue( value ) {
  27256. this.value = value;
  27257. }
  27258. getValue() {
  27259. return this.value;
  27260. }
  27261. }
  27262. class NumberUniform extends Uniform {
  27263. constructor( name, value = 0 ) {
  27264. super( name, value );
  27265. this.isNumberUniform = true;
  27266. this.boundary = 4;
  27267. this.itemSize = 1;
  27268. }
  27269. }
  27270. class Vector2Uniform extends Uniform {
  27271. constructor( name, value = new Vector2() ) {
  27272. super( name, value );
  27273. this.isVector2Uniform = true;
  27274. this.boundary = 8;
  27275. this.itemSize = 2;
  27276. }
  27277. }
  27278. class Vector3Uniform extends Uniform {
  27279. constructor( name, value = new Vector3() ) {
  27280. super( name, value );
  27281. this.isVector3Uniform = true;
  27282. this.boundary = 16;
  27283. this.itemSize = 3;
  27284. }
  27285. }
  27286. class Vector4Uniform extends Uniform {
  27287. constructor( name, value = new Vector4() ) {
  27288. super( name, value );
  27289. this.isVector4Uniform = true;
  27290. this.boundary = 16;
  27291. this.itemSize = 4;
  27292. }
  27293. }
  27294. class ColorUniform extends Uniform {
  27295. constructor( name, value = new Color() ) {
  27296. super( name, value );
  27297. this.isColorUniform = true;
  27298. this.boundary = 16;
  27299. this.itemSize = 3;
  27300. }
  27301. }
  27302. class Matrix3Uniform extends Uniform {
  27303. constructor( name, value = new Matrix3() ) {
  27304. super( name, value );
  27305. this.isMatrix3Uniform = true;
  27306. this.boundary = 48;
  27307. this.itemSize = 12;
  27308. }
  27309. }
  27310. class Matrix4Uniform extends Uniform {
  27311. constructor( name, value = new Matrix4() ) {
  27312. super( name, value );
  27313. this.isMatrix4Uniform = true;
  27314. this.boundary = 64;
  27315. this.itemSize = 16;
  27316. }
  27317. }
  27318. class NumberNodeUniform extends NumberUniform {
  27319. constructor( nodeUniform ) {
  27320. super( nodeUniform.name, nodeUniform.value );
  27321. this.nodeUniform = nodeUniform;
  27322. }
  27323. getValue() {
  27324. return this.nodeUniform.value;
  27325. }
  27326. }
  27327. class Vector2NodeUniform extends Vector2Uniform {
  27328. constructor( nodeUniform ) {
  27329. super( nodeUniform.name, nodeUniform.value );
  27330. this.nodeUniform = nodeUniform;
  27331. }
  27332. getValue() {
  27333. return this.nodeUniform.value;
  27334. }
  27335. }
  27336. class Vector3NodeUniform extends Vector3Uniform {
  27337. constructor( nodeUniform ) {
  27338. super( nodeUniform.name, nodeUniform.value );
  27339. this.nodeUniform = nodeUniform;
  27340. }
  27341. getValue() {
  27342. return this.nodeUniform.value;
  27343. }
  27344. }
  27345. class Vector4NodeUniform extends Vector4Uniform {
  27346. constructor( nodeUniform ) {
  27347. super( nodeUniform.name, nodeUniform.value );
  27348. this.nodeUniform = nodeUniform;
  27349. }
  27350. getValue() {
  27351. return this.nodeUniform.value;
  27352. }
  27353. }
  27354. class ColorNodeUniform extends ColorUniform {
  27355. constructor( nodeUniform ) {
  27356. super( nodeUniform.name, nodeUniform.value );
  27357. this.nodeUniform = nodeUniform;
  27358. }
  27359. getValue() {
  27360. return this.nodeUniform.value;
  27361. }
  27362. }
  27363. class Matrix3NodeUniform extends Matrix3Uniform {
  27364. constructor( nodeUniform ) {
  27365. super( nodeUniform.name, nodeUniform.value );
  27366. this.nodeUniform = nodeUniform;
  27367. }
  27368. getValue() {
  27369. return this.nodeUniform.value;
  27370. }
  27371. }
  27372. class Matrix4NodeUniform extends Matrix4Uniform {
  27373. constructor( nodeUniform ) {
  27374. super( nodeUniform.name, nodeUniform.value );
  27375. this.nodeUniform = nodeUniform;
  27376. }
  27377. getValue() {
  27378. return this.nodeUniform.value;
  27379. }
  27380. }
  27381. class StackNode extends Node {
  27382. constructor( parent = null ) {
  27383. super();
  27384. this.nodes = [];
  27385. this.outputNode = null;
  27386. this.parent = parent;
  27387. this._currentCond = null;
  27388. this.isStackNode = true;
  27389. }
  27390. getNodeType( builder ) {
  27391. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  27392. }
  27393. add( node ) {
  27394. this.nodes.push( node );
  27395. return this;
  27396. }
  27397. if( boolNode, method ) {
  27398. const methodNode = new ShaderNode( method );
  27399. this._currentCond = cond( boolNode, methodNode );
  27400. return this.add( this._currentCond );
  27401. }
  27402. elseif( boolNode, method ) {
  27403. const methodNode = new ShaderNode( method );
  27404. const ifNode = cond( boolNode, methodNode );
  27405. this._currentCond.elseNode = ifNode;
  27406. this._currentCond = ifNode;
  27407. return this;
  27408. }
  27409. else( method ) {
  27410. this._currentCond.elseNode = new ShaderNode( method );
  27411. return this;
  27412. }
  27413. build( builder, ...params ) {
  27414. const previousStack = getCurrentStack();
  27415. setCurrentStack( this );
  27416. for ( const node of this.nodes ) {
  27417. node.build( builder, 'void' );
  27418. }
  27419. setCurrentStack( previousStack );
  27420. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  27421. }
  27422. }
  27423. const stack = nodeProxy( StackNode );
  27424. addNodeClass( 'StackNode', StackNode );
  27425. class EquirectUVNode extends TempNode {
  27426. constructor( dirNode = positionWorldDirection ) {
  27427. super( 'vec2' );
  27428. this.dirNode = dirNode;
  27429. }
  27430. setup() {
  27431. const dir = this.dirNode;
  27432. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27433. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27434. return vec2( u, v );
  27435. }
  27436. }
  27437. const equirectUV = nodeProxy( EquirectUVNode );
  27438. addNodeClass( 'EquirectUVNode', EquirectUVNode );
  27439. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27440. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27441. constructor( size = 1, options = {} ) {
  27442. super( size, options );
  27443. this.isCubeRenderTarget = true;
  27444. }
  27445. fromEquirectangularTexture( renderer, texture$1 ) {
  27446. const currentMinFilter = texture$1.minFilter;
  27447. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27448. texture$1.generateMipmaps = true;
  27449. this.texture.type = texture$1.type;
  27450. this.texture.colorSpace = texture$1.colorSpace;
  27451. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27452. this.texture.minFilter = texture$1.minFilter;
  27453. this.texture.magFilter = texture$1.magFilter;
  27454. const geometry = new BoxGeometry( 5, 5, 5 );
  27455. const uvNode = equirectUV( positionWorldDirection );
  27456. const material = createNodeMaterialFromType( 'MeshBasicNodeMaterial' );
  27457. material.colorNode = texture( texture$1, uvNode, 0 );
  27458. material.side = BackSide;
  27459. material.blending = NoBlending;
  27460. const mesh = new Mesh( geometry, material );
  27461. const scene = new Scene();
  27462. scene.add( mesh );
  27463. // Avoid blurred poles
  27464. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27465. const camera = new CubeCamera( 1, 10, this );
  27466. camera.update( renderer, scene );
  27467. texture$1.minFilter = currentMinFilter;
  27468. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27469. mesh.geometry.dispose();
  27470. mesh.material.dispose();
  27471. return this;
  27472. }
  27473. }
  27474. const LOD_MIN = 4;
  27475. // The standard deviations (radians) associated with the extra mips. These are
  27476. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27477. // geometric shadowing function. These sigma values squared must match the
  27478. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27479. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27480. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27481. // samples and exit early, but not recompile the shader.
  27482. const MAX_SAMPLES = 20;
  27483. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  27484. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  27485. const _clearColor$1 = /*@__PURE__*/ new Color();
  27486. let _oldTarget = null;
  27487. let _oldActiveCubeFace = 0;
  27488. let _oldActiveMipmapLevel = 0;
  27489. // Golden Ratio
  27490. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27491. const INV_PHI = 1 / PHI;
  27492. // Vertices of a dodecahedron (except the opposites, which represent the
  27493. // same axis), used as axis directions evenly spread on a sphere.
  27494. const _axisDirections = [
  27495. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  27496. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27497. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27498. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27499. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27500. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27501. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27502. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27503. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27504. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  27505. ];
  27506. //
  27507. // WebGPU Face indices
  27508. const _faceLib = [
  27509. 3, 1, 5,
  27510. 0, 4, 2
  27511. ];
  27512. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  27513. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  27514. /**
  27515. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27516. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27517. * blur to be quickly accessed based on material roughness. It is packed into a
  27518. * special CubeUV format that allows us to perform custom interpolation so that
  27519. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27520. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27521. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27522. * higher roughness levels. In this way we maintain resolution to smoothly
  27523. * interpolate diffuse lighting while limiting sampling computation.
  27524. *
  27525. * Paper: Fast, Accurate Image-Based Lighting
  27526. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27527. */
  27528. class PMREMGenerator {
  27529. constructor( renderer ) {
  27530. this._renderer = renderer;
  27531. this._pingPongRenderTarget = null;
  27532. this._lodMax = 0;
  27533. this._cubeSize = 0;
  27534. this._lodPlanes = [];
  27535. this._sizeLods = [];
  27536. this._sigmas = [];
  27537. this._lodMeshes = [];
  27538. this._blurMaterial = null;
  27539. this._cubemapMaterial = null;
  27540. this._equirectMaterial = null;
  27541. this._backgroundBox = null;
  27542. }
  27543. /**
  27544. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27545. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27546. * in radians to be applied to the scene before PMREM generation. Optional near
  27547. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27548. * is placed at the origin).
  27549. */
  27550. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27551. _oldTarget = this._renderer.getRenderTarget();
  27552. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27553. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27554. this._setSize( 256 );
  27555. const cubeUVRenderTarget = this._allocateTargets();
  27556. cubeUVRenderTarget.depthBuffer = true;
  27557. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27558. if ( sigma > 0 ) {
  27559. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27560. }
  27561. this._applyPMREM( cubeUVRenderTarget );
  27562. this._cleanup( cubeUVRenderTarget );
  27563. return cubeUVRenderTarget;
  27564. }
  27565. /**
  27566. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27567. * or HDR. The ideal input image size is 1k (1024 x 512),
  27568. * as this matches best with the 256 x 256 cubemap output.
  27569. */
  27570. fromEquirectangular( equirectangular, renderTarget = null ) {
  27571. return this._fromTexture( equirectangular, renderTarget );
  27572. }
  27573. /**
  27574. * Generates a PMREM from an cubemap texture, which can be either LDR
  27575. * or HDR. The ideal input cube size is 256 x 256,
  27576. * as this matches best with the 256 x 256 cubemap output.
  27577. */
  27578. fromCubemap( cubemap, renderTarget = null ) {
  27579. return this._fromTexture( cubemap, renderTarget );
  27580. }
  27581. /**
  27582. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27583. * your texture's network fetch for increased concurrency.
  27584. */
  27585. compileCubemapShader() {
  27586. if ( this._cubemapMaterial === null ) {
  27587. this._cubemapMaterial = _getCubemapMaterial();
  27588. this._compileMaterial( this._cubemapMaterial );
  27589. }
  27590. }
  27591. /**
  27592. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27593. * your texture's network fetch for increased concurrency.
  27594. */
  27595. compileEquirectangularShader() {
  27596. if ( this._equirectMaterial === null ) {
  27597. this._equirectMaterial = _getEquirectMaterial();
  27598. this._compileMaterial( this._equirectMaterial );
  27599. }
  27600. }
  27601. /**
  27602. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27603. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27604. * one of them will cause any others to also become unusable.
  27605. */
  27606. dispose() {
  27607. this._dispose();
  27608. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  27609. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  27610. if ( this._backgroundBox !== null ) {
  27611. this._backgroundBox.geometry.dispose();
  27612. this._backgroundBox.material.dispose();
  27613. }
  27614. }
  27615. // private interface
  27616. _setSize( cubeSize ) {
  27617. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  27618. this._cubeSize = Math.pow( 2, this._lodMax );
  27619. }
  27620. _dispose() {
  27621. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  27622. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  27623. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  27624. this._lodPlanes[ i ].dispose();
  27625. }
  27626. }
  27627. _cleanup( outputTarget ) {
  27628. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  27629. outputTarget.scissorTest = false;
  27630. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27631. }
  27632. _fromTexture( texture, renderTarget ) {
  27633. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  27634. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  27635. } else { // Equirectangular
  27636. this._setSize( texture.image.width / 4 );
  27637. }
  27638. _oldTarget = this._renderer.getRenderTarget();
  27639. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27640. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27641. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  27642. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27643. this._applyPMREM( cubeUVRenderTarget );
  27644. this._cleanup( cubeUVRenderTarget );
  27645. return cubeUVRenderTarget;
  27646. }
  27647. _allocateTargets() {
  27648. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  27649. const height = 4 * this._cubeSize;
  27650. const params = {
  27651. magFilter: LinearFilter,
  27652. minFilter: LinearFilter,
  27653. generateMipmaps: false,
  27654. type: HalfFloatType,
  27655. format: RGBAFormat,
  27656. colorSpace: LinearSRGBColorSpace,
  27657. //depthBuffer: false
  27658. };
  27659. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  27660. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  27661. if ( this._pingPongRenderTarget !== null ) {
  27662. this._dispose();
  27663. }
  27664. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  27665. const { _lodMax } = this;
  27666. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  27667. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  27668. }
  27669. return cubeUVRenderTarget;
  27670. }
  27671. _compileMaterial( material ) {
  27672. const tmpMesh = this._lodMeshes[ 0 ];
  27673. tmpMesh.material = material;
  27674. this._renderer.compile( tmpMesh, _flatCamera );
  27675. }
  27676. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27677. const cubeCamera = _cubeCamera;
  27678. cubeCamera.near = near;
  27679. cubeCamera.far = far;
  27680. // px, py, pz, nx, ny, nz
  27681. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  27682. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27683. const renderer = this._renderer;
  27684. const originalAutoClear = renderer.autoClear;
  27685. renderer.getClearColor( _clearColor$1 );
  27686. renderer.autoClear = false;
  27687. let backgroundBox = this._backgroundBox;
  27688. if ( backgroundBox === null ) {
  27689. const backgroundMaterial = new MeshBasicMaterial( {
  27690. name: 'PMREM.Background',
  27691. side: BackSide,
  27692. depthWrite: false,
  27693. depthTest: false
  27694. } );
  27695. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27696. }
  27697. let useSolidColor = false;
  27698. const background = scene.background;
  27699. if ( background ) {
  27700. if ( background.isColor ) {
  27701. backgroundBox.material.color.copy( background );
  27702. scene.background = null;
  27703. useSolidColor = true;
  27704. }
  27705. } else {
  27706. backgroundBox.material.color.copy( _clearColor$1 );
  27707. useSolidColor = true;
  27708. }
  27709. renderer.setRenderTarget( cubeUVRenderTarget );
  27710. renderer.clear();
  27711. if ( useSolidColor ) {
  27712. renderer.render( backgroundBox, cubeCamera );
  27713. }
  27714. for ( let i = 0; i < 6; i ++ ) {
  27715. const col = i % 3;
  27716. if ( col === 0 ) {
  27717. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27718. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27719. } else if ( col === 1 ) {
  27720. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27721. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27722. } else {
  27723. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27724. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27725. }
  27726. const size = this._cubeSize;
  27727. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  27728. renderer.render( scene, cubeCamera );
  27729. }
  27730. renderer.autoClear = originalAutoClear;
  27731. scene.background = background;
  27732. }
  27733. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27734. const renderer = this._renderer;
  27735. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  27736. if ( isCubeTexture ) {
  27737. if ( this._cubemapMaterial === null ) {
  27738. this._cubemapMaterial = _getCubemapMaterial( texture );
  27739. }
  27740. } else {
  27741. if ( this._equirectMaterial === null ) {
  27742. this._equirectMaterial = _getEquirectMaterial( texture );
  27743. }
  27744. }
  27745. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  27746. material.fragmentNode.value = texture;
  27747. const mesh = this._lodMeshes[ 0 ];
  27748. mesh.material = material;
  27749. const size = this._cubeSize;
  27750. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  27751. renderer.setRenderTarget( cubeUVRenderTarget );
  27752. renderer.render( mesh, _flatCamera );
  27753. }
  27754. _applyPMREM( cubeUVRenderTarget ) {
  27755. const renderer = this._renderer;
  27756. const autoClear = renderer.autoClear;
  27757. renderer.autoClear = false;
  27758. const n = this._lodPlanes.length;
  27759. for ( let i = 1; i < n; i ++ ) {
  27760. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  27761. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  27762. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27763. }
  27764. renderer.autoClear = autoClear;
  27765. }
  27766. /**
  27767. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27768. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27769. * the blur latitudinally (around the poles), and then longitudinally (towards
  27770. * the poles) to approximate the orthogonally-separable blur. It is least
  27771. * accurate at the poles, but still does a decent job.
  27772. */
  27773. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27774. const pingPongRenderTarget = this._pingPongRenderTarget;
  27775. this._halfBlur(
  27776. cubeUVRenderTarget,
  27777. pingPongRenderTarget,
  27778. lodIn,
  27779. lodOut,
  27780. sigma,
  27781. 'latitudinal',
  27782. poleAxis );
  27783. this._halfBlur(
  27784. pingPongRenderTarget,
  27785. cubeUVRenderTarget,
  27786. lodOut,
  27787. lodOut,
  27788. sigma,
  27789. 'longitudinal',
  27790. poleAxis );
  27791. }
  27792. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27793. const renderer = this._renderer;
  27794. const blurMaterial = this._blurMaterial;
  27795. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27796. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  27797. }
  27798. // Number of standard deviations at which to cut off the discrete approximation.
  27799. const STANDARD_DEVIATIONS = 3;
  27800. const blurMesh = this._lodMeshes[ lodOut ];
  27801. blurMesh.material = blurMaterial;
  27802. const blurUniforms = blurMaterial.uniforms;
  27803. const pixels = this._sizeLods[ lodIn ] - 1;
  27804. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27805. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27806. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27807. if ( samples > MAX_SAMPLES ) {
  27808. console.warn( `sigmaRadians, ${
  27809. sigmaRadians}, is too large and will clip, as it requested ${
  27810. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27811. }
  27812. const weights = [];
  27813. let sum = 0;
  27814. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27815. const x = i / sigmaPixels;
  27816. const weight = Math.exp( - x * x / 2 );
  27817. weights.push( weight );
  27818. if ( i === 0 ) {
  27819. sum += weight;
  27820. } else if ( i < samples ) {
  27821. sum += 2 * weight;
  27822. }
  27823. }
  27824. for ( let i = 0; i < weights.length; i ++ ) {
  27825. weights[ i ] = weights[ i ] / sum;
  27826. }
  27827. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  27828. blurUniforms.envMap.value = targetIn.texture;
  27829. blurUniforms.samples.value = samples;
  27830. blurUniforms.weights.array = weights;
  27831. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  27832. if ( poleAxis ) {
  27833. blurUniforms.poleAxis.value = poleAxis;
  27834. }
  27835. const { _lodMax } = this;
  27836. blurUniforms.dTheta.value = radiansPerPixel;
  27837. blurUniforms.mipInt.value = _lodMax - lodIn;
  27838. const outputSize = this._sizeLods[ lodOut ];
  27839. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  27840. const y = 4 * ( this._cubeSize - outputSize );
  27841. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27842. renderer.setRenderTarget( targetOut );
  27843. renderer.render( blurMesh, _flatCamera );
  27844. }
  27845. }
  27846. function _createPlanes( lodMax ) {
  27847. const lodPlanes = [];
  27848. const sizeLods = [];
  27849. const sigmas = [];
  27850. const lodMeshes = [];
  27851. let lod = lodMax;
  27852. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27853. for ( let i = 0; i < totalLods; i ++ ) {
  27854. const sizeLod = Math.pow( 2, lod );
  27855. sizeLods.push( sizeLod );
  27856. let sigma = 1.0 / sizeLod;
  27857. if ( i > lodMax - LOD_MIN ) {
  27858. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  27859. } else if ( i === 0 ) {
  27860. sigma = 0;
  27861. }
  27862. sigmas.push( sigma );
  27863. const texelSize = 1.0 / ( sizeLod - 2 );
  27864. const min = - texelSize;
  27865. const max = 1 + texelSize;
  27866. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27867. const cubeFaces = 6;
  27868. const vertices = 6;
  27869. const positionSize = 3;
  27870. const uvSize = 2;
  27871. const faceIndexSize = 1;
  27872. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27873. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27874. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27875. for ( let face = 0; face < cubeFaces; face ++ ) {
  27876. const x = ( face % 3 ) * 2 / 3 - 1;
  27877. const y = face > 2 ? 0 : - 1;
  27878. const coordinates = [
  27879. x, y, 0,
  27880. x + 2 / 3, y, 0,
  27881. x + 2 / 3, y + 1, 0,
  27882. x, y, 0,
  27883. x + 2 / 3, y + 1, 0,
  27884. x, y + 1, 0
  27885. ];
  27886. const faceIdx = _faceLib[ face ];
  27887. position.set( coordinates, positionSize * vertices * faceIdx );
  27888. uv.set( uv1, uvSize * vertices * faceIdx );
  27889. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  27890. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  27891. }
  27892. const planes = new BufferGeometry();
  27893. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27894. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27895. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27896. lodPlanes.push( planes );
  27897. lodMeshes.push( new Mesh( planes, null ) );
  27898. if ( lod > LOD_MIN ) {
  27899. lod --;
  27900. }
  27901. }
  27902. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  27903. }
  27904. function _createRenderTarget( width, height, params ) {
  27905. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  27906. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27907. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27908. cubeUVRenderTarget.texture.isPMREMTexture = true;
  27909. cubeUVRenderTarget.scissorTest = true;
  27910. return cubeUVRenderTarget;
  27911. }
  27912. function _setViewport( target, x, y, width, height ) {
  27913. const viewY = target.height - height - y;
  27914. target.viewport.set( x, viewY, width, height );
  27915. target.scissor.set( x, viewY, width, height );
  27916. }
  27917. function _getMaterial() {
  27918. const material = new NodeMaterial();
  27919. material.depthTest = false;
  27920. material.depthWrite = false;
  27921. material.blending = NoBlending;
  27922. return material;
  27923. }
  27924. function _getBlurShader( lodMax, width, height ) {
  27925. const weights = uniforms( new Array( MAX_SAMPLES ).fill( 0 ) );
  27926. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  27927. const dTheta = uniform( 0 );
  27928. const n = float( MAX_SAMPLES );
  27929. const latitudinal = uniform( 0 ); // false, bool
  27930. const samples = uniform( 1 ); // int
  27931. const envMap = texture( null );
  27932. const mipInt = uniform( 0 ); // int
  27933. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  27934. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  27935. const CUBEUV_MAX_MIP = float( lodMax );
  27936. const materialUniforms = {
  27937. n,
  27938. latitudinal,
  27939. weights,
  27940. poleAxis,
  27941. outputDirection,
  27942. dTheta,
  27943. samples,
  27944. envMap,
  27945. mipInt,
  27946. CUBEUV_TEXEL_WIDTH,
  27947. CUBEUV_TEXEL_HEIGHT,
  27948. CUBEUV_MAX_MIP
  27949. };
  27950. const material = _getMaterial();
  27951. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  27952. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  27953. return material;
  27954. }
  27955. function _getCubemapMaterial( envTexture ) {
  27956. const material = _getMaterial();
  27957. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  27958. return material;
  27959. }
  27960. function _getEquirectMaterial( envTexture ) {
  27961. const material = _getMaterial();
  27962. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  27963. return material;
  27964. }
  27965. let _id$3 = 0;
  27966. class BindGroup {
  27967. constructor( name = '', bindings = [] ) {
  27968. this.name = name;
  27969. this.bindings = bindings;
  27970. this.id = _id$3 ++;
  27971. }
  27972. }
  27973. const rendererCache = new WeakMap();
  27974. const typeFromLength = new Map( [
  27975. [ 2, 'vec2' ],
  27976. [ 3, 'vec3' ],
  27977. [ 4, 'vec4' ],
  27978. [ 9, 'mat3' ],
  27979. [ 16, 'mat4' ]
  27980. ] );
  27981. const typeFromArray = new Map( [
  27982. [ Int8Array, 'int' ],
  27983. [ Int16Array, 'int' ],
  27984. [ Int32Array, 'int' ],
  27985. [ Uint8Array, 'uint' ],
  27986. [ Uint16Array, 'uint' ],
  27987. [ Uint32Array, 'uint' ],
  27988. [ Float32Array, 'float' ]
  27989. ] );
  27990. const toFloat = ( value ) => {
  27991. value = Number( value );
  27992. return value + ( value % 1 ? '' : '.0' );
  27993. };
  27994. class NodeBuilder {
  27995. constructor( object, renderer, parser ) {
  27996. this.object = object;
  27997. this.material = ( object && object.material ) || null;
  27998. this.geometry = ( object && object.geometry ) || null;
  27999. this.renderer = renderer;
  28000. this.parser = parser;
  28001. this.scene = null;
  28002. this.camera = null;
  28003. this.nodes = [];
  28004. this.updateNodes = [];
  28005. this.updateBeforeNodes = [];
  28006. this.updateAfterNodes = [];
  28007. this.hashNodes = {};
  28008. this.lightsNode = null;
  28009. this.environmentNode = null;
  28010. this.fogNode = null;
  28011. this.clippingContext = null;
  28012. this.vertexShader = null;
  28013. this.fragmentShader = null;
  28014. this.computeShader = null;
  28015. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  28016. this.flowCode = { vertex: '', fragment: '', compute: '' };
  28017. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  28018. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  28019. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  28020. this.bindingsIndexes = {};
  28021. this.bindGroups = null;
  28022. this.attributes = [];
  28023. this.bufferAttributes = [];
  28024. this.varyings = [];
  28025. this.codes = {};
  28026. this.vars = {};
  28027. this.flow = { code: '' };
  28028. this.chaining = [];
  28029. this.stack = stack();
  28030. this.stacks = [];
  28031. this.tab = '\t';
  28032. this.instanceBindGroups = true;
  28033. this.currentFunctionNode = null;
  28034. this.context = {
  28035. keywords: new NodeKeywords(),
  28036. material: this.material
  28037. };
  28038. this.cache = new NodeCache();
  28039. this.globalCache = this.cache;
  28040. this.flowsData = new WeakMap();
  28041. this.shaderStage = null;
  28042. this.buildStage = null;
  28043. }
  28044. getBingGroupsCache() {
  28045. let bindGroupsCache = rendererCache.get( this.renderer );
  28046. if ( bindGroupsCache === undefined ) {
  28047. bindGroupsCache = new ChainMap();
  28048. rendererCache.set( this.renderer, bindGroupsCache );
  28049. }
  28050. return bindGroupsCache;
  28051. }
  28052. createRenderTarget( width, height, options ) {
  28053. return new RenderTarget( width, height, options );
  28054. }
  28055. createCubeRenderTarget( size, options ) {
  28056. return new CubeRenderTarget( size, options );
  28057. }
  28058. createPMREMGenerator() {
  28059. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28060. return new PMREMGenerator( this.renderer );
  28061. }
  28062. includes( node ) {
  28063. return this.nodes.includes( node );
  28064. }
  28065. _getBindGroup( groupName, bindings ) {
  28066. const bindGroupsCache = this.getBingGroupsCache();
  28067. //
  28068. const bindingsArray = [];
  28069. let sharedGroup = true;
  28070. for ( const binding of bindings ) {
  28071. bindingsArray.push( binding );
  28072. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  28073. }
  28074. //
  28075. let bindGroup;
  28076. if ( sharedGroup ) {
  28077. bindGroup = bindGroupsCache.get( bindingsArray );
  28078. if ( bindGroup === undefined ) {
  28079. bindGroup = new BindGroup( groupName, bindingsArray );
  28080. bindGroupsCache.set( bindingsArray, bindGroup );
  28081. }
  28082. } else {
  28083. bindGroup = new BindGroup( groupName, bindingsArray );
  28084. }
  28085. return bindGroup;
  28086. }
  28087. getBindGroupArray( groupName, shaderStage ) {
  28088. const bindings = this.bindings[ shaderStage ];
  28089. let bindGroup = bindings[ groupName ];
  28090. if ( bindGroup === undefined ) {
  28091. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  28092. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  28093. }
  28094. bindings[ groupName ] = bindGroup = [];
  28095. }
  28096. return bindGroup;
  28097. }
  28098. getBindings() {
  28099. let bindingsGroups = this.bindGroups;
  28100. if ( bindingsGroups === null ) {
  28101. const groups = {};
  28102. const bindings = this.bindings;
  28103. for ( const shaderStage of shaderStages ) {
  28104. for ( const groupName in bindings[ shaderStage ] ) {
  28105. const uniforms = bindings[ shaderStage ][ groupName ];
  28106. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  28107. groupUniforms.push( ...uniforms );
  28108. }
  28109. }
  28110. bindingsGroups = [];
  28111. for ( const groupName in groups ) {
  28112. const group = groups[ groupName ];
  28113. const bindingsGroup = this._getBindGroup( groupName, group );
  28114. bindingsGroups.push( bindingsGroup );
  28115. }
  28116. this.bindGroups = bindingsGroups;
  28117. }
  28118. return bindingsGroups;
  28119. }
  28120. setHashNode( node, hash ) {
  28121. this.hashNodes[ hash ] = node;
  28122. }
  28123. addNode( node ) {
  28124. if ( this.nodes.includes( node ) === false ) {
  28125. this.nodes.push( node );
  28126. this.setHashNode( node, node.getHash( this ) );
  28127. }
  28128. }
  28129. buildUpdateNodes() {
  28130. for ( const node of this.nodes ) {
  28131. const updateType = node.getUpdateType();
  28132. const updateBeforeType = node.getUpdateBeforeType();
  28133. const updateAfterType = node.getUpdateAfterType();
  28134. if ( updateType !== NodeUpdateType.NONE ) {
  28135. this.updateNodes.push( node.getSelf() );
  28136. }
  28137. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  28138. this.updateBeforeNodes.push( node );
  28139. }
  28140. if ( updateAfterType !== NodeUpdateType.NONE ) {
  28141. this.updateAfterNodes.push( node );
  28142. }
  28143. }
  28144. }
  28145. get currentNode() {
  28146. return this.chaining[ this.chaining.length - 1 ];
  28147. }
  28148. isFilteredTexture( texture ) {
  28149. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  28150. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  28151. }
  28152. addChain( node ) {
  28153. /*
  28154. if ( this.chaining.indexOf( node ) !== - 1 ) {
  28155. console.warn( 'Recursive node: ', node );
  28156. }
  28157. */
  28158. this.chaining.push( node );
  28159. }
  28160. removeChain( node ) {
  28161. const lastChain = this.chaining.pop();
  28162. if ( lastChain !== node ) {
  28163. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  28164. }
  28165. }
  28166. getMethod( method ) {
  28167. return method;
  28168. }
  28169. getNodeFromHash( hash ) {
  28170. return this.hashNodes[ hash ];
  28171. }
  28172. addFlow( shaderStage, node ) {
  28173. this.flowNodes[ shaderStage ].push( node );
  28174. return node;
  28175. }
  28176. setContext( context ) {
  28177. this.context = context;
  28178. }
  28179. getContext() {
  28180. return this.context;
  28181. }
  28182. setCache( cache ) {
  28183. this.cache = cache;
  28184. }
  28185. getCache() {
  28186. return this.cache;
  28187. }
  28188. getCacheFromNode( node, parent = true ) {
  28189. const data = this.getDataFromNode( node );
  28190. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  28191. return data.cache;
  28192. }
  28193. isAvailable( /*name*/ ) {
  28194. return false;
  28195. }
  28196. getVertexIndex() {
  28197. console.warn( 'Abstract function.' );
  28198. }
  28199. getInstanceIndex() {
  28200. console.warn( 'Abstract function.' );
  28201. }
  28202. getDrawIndex() {
  28203. console.warn( 'Abstract function.' );
  28204. }
  28205. getFrontFacing() {
  28206. console.warn( 'Abstract function.' );
  28207. }
  28208. getFragCoord() {
  28209. console.warn( 'Abstract function.' );
  28210. }
  28211. isFlipY() {
  28212. return false;
  28213. }
  28214. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  28215. console.warn( 'Abstract function.' );
  28216. }
  28217. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  28218. console.warn( 'Abstract function.' );
  28219. }
  28220. generateConst( type, value = null ) {
  28221. if ( value === null ) {
  28222. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  28223. else if ( type === 'bool' ) value = false;
  28224. else if ( type === 'color' ) value = new Color();
  28225. else if ( type === 'vec2' ) value = new Vector2();
  28226. else if ( type === 'vec3' ) value = new Vector3();
  28227. else if ( type === 'vec4' ) value = new Vector4();
  28228. }
  28229. if ( type === 'float' ) return toFloat( value );
  28230. if ( type === 'int' ) return `${ Math.round( value ) }`;
  28231. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  28232. if ( type === 'bool' ) return value ? 'true' : 'false';
  28233. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  28234. const typeLength = this.getTypeLength( type );
  28235. const componentType = this.getComponentType( type );
  28236. const generateConst = value => this.generateConst( componentType, value );
  28237. if ( typeLength === 2 ) {
  28238. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  28239. } else if ( typeLength === 3 ) {
  28240. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  28241. } else if ( typeLength === 4 ) {
  28242. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  28243. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  28244. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  28245. } else if ( typeLength > 4 ) {
  28246. return `${ this.getType( type ) }()`;
  28247. }
  28248. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  28249. }
  28250. getType( type ) {
  28251. if ( type === 'color' ) return 'vec3';
  28252. return type;
  28253. }
  28254. hasGeometryAttribute( name ) {
  28255. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  28256. }
  28257. getAttribute( name, type ) {
  28258. const attributes = this.attributes;
  28259. // find attribute
  28260. for ( const attribute of attributes ) {
  28261. if ( attribute.name === name ) {
  28262. return attribute;
  28263. }
  28264. }
  28265. // create a new if no exist
  28266. const attribute = new NodeAttribute( name, type );
  28267. attributes.push( attribute );
  28268. return attribute;
  28269. }
  28270. getPropertyName( node/*, shaderStage*/ ) {
  28271. return node.name;
  28272. }
  28273. isVector( type ) {
  28274. return /vec\d/.test( type );
  28275. }
  28276. isMatrix( type ) {
  28277. return /mat\d/.test( type );
  28278. }
  28279. isReference( type ) {
  28280. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  28281. }
  28282. needsColorSpaceToLinear( /*texture*/ ) {
  28283. return false;
  28284. }
  28285. getComponentTypeFromTexture( texture ) {
  28286. const type = texture.type;
  28287. if ( texture.isDataTexture ) {
  28288. if ( type === IntType ) return 'int';
  28289. if ( type === UnsignedIntType ) return 'uint';
  28290. }
  28291. return 'float';
  28292. }
  28293. getElementType( type ) {
  28294. if ( type === 'mat2' ) return 'vec2';
  28295. if ( type === 'mat3' ) return 'vec3';
  28296. if ( type === 'mat4' ) return 'vec4';
  28297. return this.getComponentType( type );
  28298. }
  28299. getComponentType( type ) {
  28300. type = this.getVectorType( type );
  28301. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  28302. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  28303. if ( componentType === null ) return null;
  28304. if ( componentType[ 1 ] === 'b' ) return 'bool';
  28305. if ( componentType[ 1 ] === 'i' ) return 'int';
  28306. if ( componentType[ 1 ] === 'u' ) return 'uint';
  28307. return 'float';
  28308. }
  28309. getVectorType( type ) {
  28310. if ( type === 'color' ) return 'vec3';
  28311. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  28312. return type;
  28313. }
  28314. getTypeFromLength( length, componentType = 'float' ) {
  28315. if ( length === 1 ) return componentType;
  28316. const baseType = typeFromLength.get( length );
  28317. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  28318. return prefix + baseType;
  28319. }
  28320. getTypeFromArray( array ) {
  28321. return typeFromArray.get( array.constructor );
  28322. }
  28323. getTypeFromAttribute( attribute ) {
  28324. let dataAttribute = attribute;
  28325. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  28326. const array = dataAttribute.array;
  28327. const itemSize = attribute.itemSize;
  28328. const normalized = attribute.normalized;
  28329. let arrayType;
  28330. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  28331. arrayType = this.getTypeFromArray( array );
  28332. }
  28333. return this.getTypeFromLength( itemSize, arrayType );
  28334. }
  28335. getTypeLength( type ) {
  28336. const vecType = this.getVectorType( type );
  28337. const vecNum = /vec([2-4])/.exec( vecType );
  28338. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  28339. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  28340. if ( /mat2/.test( type ) === true ) return 4;
  28341. if ( /mat3/.test( type ) === true ) return 9;
  28342. if ( /mat4/.test( type ) === true ) return 16;
  28343. return 0;
  28344. }
  28345. getVectorFromMatrix( type ) {
  28346. return type.replace( 'mat', 'vec' );
  28347. }
  28348. changeComponentType( type, newComponentType ) {
  28349. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  28350. }
  28351. getIntegerType( type ) {
  28352. const componentType = this.getComponentType( type );
  28353. if ( componentType === 'int' || componentType === 'uint' ) return type;
  28354. return this.changeComponentType( type, 'int' );
  28355. }
  28356. addStack() {
  28357. this.stack = stack( this.stack );
  28358. this.stacks.push( getCurrentStack() || this.stack );
  28359. setCurrentStack( this.stack );
  28360. return this.stack;
  28361. }
  28362. removeStack() {
  28363. const lastStack = this.stack;
  28364. this.stack = lastStack.parent;
  28365. setCurrentStack( this.stacks.pop() );
  28366. return lastStack;
  28367. }
  28368. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  28369. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  28370. let nodeData = cache.getData( node );
  28371. if ( nodeData === undefined ) {
  28372. nodeData = {};
  28373. cache.setData( node, nodeData );
  28374. }
  28375. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  28376. return nodeData[ shaderStage ];
  28377. }
  28378. getNodeProperties( node, shaderStage = 'any' ) {
  28379. const nodeData = this.getDataFromNode( node, shaderStage );
  28380. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  28381. }
  28382. getBufferAttributeFromNode( node, type ) {
  28383. const nodeData = this.getDataFromNode( node );
  28384. let bufferAttribute = nodeData.bufferAttribute;
  28385. if ( bufferAttribute === undefined ) {
  28386. const index = this.uniforms.index ++;
  28387. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  28388. this.bufferAttributes.push( bufferAttribute );
  28389. nodeData.bufferAttribute = bufferAttribute;
  28390. }
  28391. return bufferAttribute;
  28392. }
  28393. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  28394. const nodeData = this.getDataFromNode( node, shaderStage );
  28395. if ( nodeData.structType === undefined ) {
  28396. const index = this.structs.index ++;
  28397. node.name = `StructType${ index }`;
  28398. this.structs[ shaderStage ].push( node );
  28399. nodeData.structType = node;
  28400. }
  28401. return node;
  28402. }
  28403. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  28404. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  28405. let nodeUniform = nodeData.uniform;
  28406. if ( nodeUniform === undefined ) {
  28407. const index = this.uniforms.index ++;
  28408. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  28409. this.uniforms[ shaderStage ].push( nodeUniform );
  28410. nodeData.uniform = nodeUniform;
  28411. }
  28412. return nodeUniform;
  28413. }
  28414. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  28415. const nodeData = this.getDataFromNode( node, shaderStage );
  28416. let nodeVar = nodeData.variable;
  28417. if ( nodeVar === undefined ) {
  28418. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  28419. if ( name === null ) name = 'nodeVar' + vars.length;
  28420. nodeVar = new NodeVar( name, type );
  28421. vars.push( nodeVar );
  28422. nodeData.variable = nodeVar;
  28423. }
  28424. return nodeVar;
  28425. }
  28426. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  28427. const nodeData = this.getDataFromNode( node, 'any' );
  28428. let nodeVarying = nodeData.varying;
  28429. if ( nodeVarying === undefined ) {
  28430. const varyings = this.varyings;
  28431. const index = varyings.length;
  28432. if ( name === null ) name = 'nodeVarying' + index;
  28433. nodeVarying = new NodeVarying( name, type );
  28434. varyings.push( nodeVarying );
  28435. nodeData.varying = nodeVarying;
  28436. }
  28437. return nodeVarying;
  28438. }
  28439. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  28440. const nodeData = this.getDataFromNode( node );
  28441. let nodeCode = nodeData.code;
  28442. if ( nodeCode === undefined ) {
  28443. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  28444. const index = codes.length;
  28445. nodeCode = new NodeCode( 'nodeCode' + index, type );
  28446. codes.push( nodeCode );
  28447. nodeData.code = nodeCode;
  28448. }
  28449. return nodeCode;
  28450. }
  28451. addLineFlowCode( code ) {
  28452. if ( code === '' ) return this;
  28453. code = this.tab + code;
  28454. if ( ! /;\s*$/.test( code ) ) {
  28455. code = code + ';\n';
  28456. }
  28457. this.flow.code += code;
  28458. return this;
  28459. }
  28460. addFlowCode( code ) {
  28461. this.flow.code += code;
  28462. return this;
  28463. }
  28464. addFlowTab() {
  28465. this.tab += '\t';
  28466. return this;
  28467. }
  28468. removeFlowTab() {
  28469. this.tab = this.tab.slice( 0, - 1 );
  28470. return this;
  28471. }
  28472. getFlowData( node/*, shaderStage*/ ) {
  28473. return this.flowsData.get( node );
  28474. }
  28475. flowNode( node ) {
  28476. const output = node.getNodeType( this );
  28477. const flowData = this.flowChildNode( node, output );
  28478. this.flowsData.set( node, flowData );
  28479. return flowData;
  28480. }
  28481. buildFunctionNode( shaderNode ) {
  28482. const fn = new FunctionNode();
  28483. const previous = this.currentFunctionNode;
  28484. this.currentFunctionNode = fn;
  28485. fn.code = this.buildFunctionCode( shaderNode );
  28486. this.currentFunctionNode = previous;
  28487. return fn;
  28488. }
  28489. flowShaderNode( shaderNode ) {
  28490. const layout = shaderNode.layout;
  28491. let inputs;
  28492. if ( shaderNode.isArrayInput ) {
  28493. inputs = [];
  28494. for ( const input of layout.inputs ) {
  28495. inputs.push( new ParameterNode( input.type, input.name ) );
  28496. }
  28497. } else {
  28498. inputs = {};
  28499. for ( const input of layout.inputs ) {
  28500. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  28501. }
  28502. }
  28503. //
  28504. shaderNode.layout = null;
  28505. const callNode = shaderNode.call( inputs );
  28506. const flowData = this.flowStagesNode( callNode, layout.type );
  28507. shaderNode.layout = layout;
  28508. return flowData;
  28509. }
  28510. flowStagesNode( node, output = null ) {
  28511. const previousFlow = this.flow;
  28512. const previousVars = this.vars;
  28513. const previousCache = this.cache;
  28514. const previousBuildStage = this.buildStage;
  28515. const previousStack = this.stack;
  28516. const flow = {
  28517. code: ''
  28518. };
  28519. this.flow = flow;
  28520. this.vars = {};
  28521. this.cache = new NodeCache();
  28522. this.stack = stack();
  28523. for ( const buildStage of defaultBuildStages ) {
  28524. this.setBuildStage( buildStage );
  28525. flow.result = node.build( this, output );
  28526. }
  28527. flow.vars = this.getVars( this.shaderStage );
  28528. this.flow = previousFlow;
  28529. this.vars = previousVars;
  28530. this.cache = previousCache;
  28531. this.stack = previousStack;
  28532. this.setBuildStage( previousBuildStage );
  28533. return flow;
  28534. }
  28535. getFunctionOperator() {
  28536. return null;
  28537. }
  28538. flowChildNode( node, output = null ) {
  28539. const previousFlow = this.flow;
  28540. const flow = {
  28541. code: ''
  28542. };
  28543. this.flow = flow;
  28544. flow.result = node.build( this, output );
  28545. this.flow = previousFlow;
  28546. return flow;
  28547. }
  28548. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  28549. const previousShaderStage = this.shaderStage;
  28550. this.setShaderStage( shaderStage );
  28551. const flowData = this.flowChildNode( node, output );
  28552. if ( propertyName !== null ) {
  28553. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  28554. }
  28555. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  28556. this.setShaderStage( previousShaderStage );
  28557. return flowData;
  28558. }
  28559. getAttributesArray() {
  28560. return this.attributes.concat( this.bufferAttributes );
  28561. }
  28562. getAttributes( /*shaderStage*/ ) {
  28563. console.warn( 'Abstract function.' );
  28564. }
  28565. getVaryings( /*shaderStage*/ ) {
  28566. console.warn( 'Abstract function.' );
  28567. }
  28568. getVar( type, name ) {
  28569. return `${ this.getType( type ) } ${ name }`;
  28570. }
  28571. getVars( shaderStage ) {
  28572. let snippet = '';
  28573. const vars = this.vars[ shaderStage ];
  28574. if ( vars !== undefined ) {
  28575. for ( const variable of vars ) {
  28576. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  28577. }
  28578. }
  28579. return snippet;
  28580. }
  28581. getUniforms( /*shaderStage*/ ) {
  28582. console.warn( 'Abstract function.' );
  28583. }
  28584. getCodes( shaderStage ) {
  28585. const codes = this.codes[ shaderStage ];
  28586. let code = '';
  28587. if ( codes !== undefined ) {
  28588. for ( const nodeCode of codes ) {
  28589. code += nodeCode.code + '\n';
  28590. }
  28591. }
  28592. return code;
  28593. }
  28594. getHash() {
  28595. return this.vertexShader + this.fragmentShader + this.computeShader;
  28596. }
  28597. setShaderStage( shaderStage ) {
  28598. this.shaderStage = shaderStage;
  28599. }
  28600. getShaderStage() {
  28601. return this.shaderStage;
  28602. }
  28603. setBuildStage( buildStage ) {
  28604. this.buildStage = buildStage;
  28605. }
  28606. getBuildStage() {
  28607. return this.buildStage;
  28608. }
  28609. buildCode() {
  28610. console.warn( 'Abstract function.' );
  28611. }
  28612. build() {
  28613. const { object, material } = this;
  28614. if ( material !== null ) {
  28615. NodeMaterial.fromMaterial( material ).build( this );
  28616. } else {
  28617. this.addFlow( 'compute', object );
  28618. }
  28619. // setup() -> stage 1: create possible new nodes and returns an output reference node
  28620. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  28621. // generate() -> stage 3: generate shader
  28622. for ( const buildStage of defaultBuildStages ) {
  28623. this.setBuildStage( buildStage );
  28624. if ( this.context.vertex && this.context.vertex.isNode ) {
  28625. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  28626. }
  28627. for ( const shaderStage of shaderStages ) {
  28628. this.setShaderStage( shaderStage );
  28629. const flowNodes = this.flowNodes[ shaderStage ];
  28630. for ( const node of flowNodes ) {
  28631. if ( buildStage === 'generate' ) {
  28632. this.flowNode( node );
  28633. } else {
  28634. node.build( this );
  28635. }
  28636. }
  28637. }
  28638. }
  28639. this.setBuildStage( null );
  28640. this.setShaderStage( null );
  28641. // stage 4: build code for a specific output
  28642. this.buildCode();
  28643. this.buildUpdateNodes();
  28644. return this;
  28645. }
  28646. getNodeUniform( uniformNode, type ) {
  28647. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  28648. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  28649. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  28650. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  28651. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  28652. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  28653. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  28654. throw new Error( `Uniform "${type}" not declared.` );
  28655. }
  28656. createNodeMaterial( type = 'NodeMaterial' ) {
  28657. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28658. return createNodeMaterialFromType( type );
  28659. }
  28660. format( snippet, fromType, toType ) {
  28661. fromType = this.getVectorType( fromType );
  28662. toType = this.getVectorType( toType );
  28663. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  28664. return snippet;
  28665. }
  28666. const fromTypeLength = this.getTypeLength( fromType );
  28667. const toTypeLength = this.getTypeLength( toType );
  28668. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  28669. // @TODO: ignore for now
  28670. return snippet;
  28671. }
  28672. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  28673. // @TODO: ignore for now
  28674. return snippet;
  28675. }
  28676. if ( fromTypeLength === toTypeLength ) {
  28677. return `${ this.getType( toType ) }( ${ snippet } )`;
  28678. }
  28679. if ( fromTypeLength > toTypeLength ) {
  28680. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  28681. }
  28682. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  28683. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  28684. }
  28685. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  28686. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  28687. }
  28688. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  28689. // convert a number value to vector type, e.g:
  28690. // vec3( 1u ) -> vec3( float( 1u ) )
  28691. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  28692. }
  28693. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  28694. }
  28695. getSignature() {
  28696. return `// Three.js r${ REVISION } - Node System\n`;
  28697. }
  28698. }
  28699. class NodeFrame {
  28700. constructor() {
  28701. this.time = 0;
  28702. this.deltaTime = 0;
  28703. this.frameId = 0;
  28704. this.renderId = 0;
  28705. this.startTime = null;
  28706. this.updateMap = new WeakMap();
  28707. this.updateBeforeMap = new WeakMap();
  28708. this.updateAfterMap = new WeakMap();
  28709. this.renderer = null;
  28710. this.material = null;
  28711. this.camera = null;
  28712. this.object = null;
  28713. this.scene = null;
  28714. }
  28715. _getMaps( referenceMap, nodeRef ) {
  28716. let maps = referenceMap.get( nodeRef );
  28717. if ( maps === undefined ) {
  28718. maps = {
  28719. renderMap: new WeakMap(),
  28720. frameMap: new WeakMap()
  28721. };
  28722. referenceMap.set( nodeRef, maps );
  28723. }
  28724. return maps;
  28725. }
  28726. updateBeforeNode( node ) {
  28727. const updateType = node.getUpdateBeforeType();
  28728. const reference = node.updateReference( this );
  28729. if ( updateType === NodeUpdateType.FRAME ) {
  28730. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  28731. if ( frameMap.get( reference ) !== this.frameId ) {
  28732. if ( node.updateBefore( this ) !== false ) {
  28733. frameMap.set( reference, this.frameId );
  28734. }
  28735. }
  28736. } else if ( updateType === NodeUpdateType.RENDER ) {
  28737. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  28738. if ( renderMap.get( reference ) !== this.renderId ) {
  28739. if ( node.updateBefore( this ) !== false ) {
  28740. renderMap.set( reference, this.renderId );
  28741. }
  28742. }
  28743. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28744. node.updateBefore( this );
  28745. }
  28746. }
  28747. updateAfterNode( node ) {
  28748. const updateType = node.getUpdateAfterType();
  28749. const reference = node.updateReference( this );
  28750. if ( updateType === NodeUpdateType.FRAME ) {
  28751. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  28752. if ( frameMap.get( reference ) !== this.frameId ) {
  28753. if ( node.updateAfter( this ) !== false ) {
  28754. frameMap.set( reference, this.frameId );
  28755. }
  28756. }
  28757. } else if ( updateType === NodeUpdateType.RENDER ) {
  28758. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  28759. if ( renderMap.get( reference ) !== this.renderId ) {
  28760. if ( node.updateAfter( this ) !== false ) {
  28761. renderMap.set( reference, this.renderId );
  28762. }
  28763. }
  28764. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28765. node.updateAfter( this );
  28766. }
  28767. }
  28768. updateNode( node ) {
  28769. const updateType = node.getUpdateType();
  28770. const reference = node.updateReference( this );
  28771. if ( updateType === NodeUpdateType.FRAME ) {
  28772. const { frameMap } = this._getMaps( this.updateMap, reference );
  28773. if ( frameMap.get( reference ) !== this.frameId ) {
  28774. if ( node.update( this ) !== false ) {
  28775. frameMap.set( reference, this.frameId );
  28776. }
  28777. }
  28778. } else if ( updateType === NodeUpdateType.RENDER ) {
  28779. const { renderMap } = this._getMaps( this.updateMap, reference );
  28780. if ( renderMap.get( reference ) !== this.renderId ) {
  28781. if ( node.update( this ) !== false ) {
  28782. renderMap.set( reference, this.renderId );
  28783. }
  28784. }
  28785. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28786. node.update( this );
  28787. }
  28788. }
  28789. update() {
  28790. this.frameId ++;
  28791. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  28792. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  28793. this.lastTime = performance.now();
  28794. this.time += this.deltaTime;
  28795. }
  28796. }
  28797. class NodeFunctionInput {
  28798. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  28799. this.type = type;
  28800. this.name = name;
  28801. this.count = count;
  28802. this.qualifier = qualifier;
  28803. this.isConst = isConst;
  28804. }
  28805. }
  28806. NodeFunctionInput.isNodeFunctionInput = true;
  28807. class StructTypeNode extends Node {
  28808. constructor( types ) {
  28809. super();
  28810. this.types = types;
  28811. this.isStructTypeNode = true;
  28812. }
  28813. getMemberTypes() {
  28814. return this.types;
  28815. }
  28816. }
  28817. addNodeClass( 'StructTypeNode', StructTypeNode );
  28818. class OutputStructNode extends Node {
  28819. constructor( ...members ) {
  28820. super();
  28821. this.members = members;
  28822. this.isOutputStructNode = true;
  28823. }
  28824. setup( builder ) {
  28825. super.setup( builder );
  28826. const members = this.members;
  28827. const types = [];
  28828. for ( let i = 0; i < members.length; i ++ ) {
  28829. types.push( members[ i ].getNodeType( builder ) );
  28830. }
  28831. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  28832. }
  28833. generate( builder, output ) {
  28834. const propertyName = builder.getOutputStructName();
  28835. const members = this.members;
  28836. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  28837. for ( let i = 0; i < members.length; i ++ ) {
  28838. const snippet = members[ i ].build( builder, output );
  28839. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  28840. }
  28841. return propertyName;
  28842. }
  28843. }
  28844. const outputStruct = nodeProxy( OutputStructNode );
  28845. addNodeClass( 'OutputStructNode', OutputStructNode );
  28846. class HashNode extends Node {
  28847. constructor( seedNode ) {
  28848. super();
  28849. this.seedNode = seedNode;
  28850. }
  28851. setup( /*builder*/ ) {
  28852. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  28853. const state = this.seedNode.toUint().mul( 747796405 ).add( 2891336453 );
  28854. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  28855. const result = word.shiftRight( 22 ).bitXor( word );
  28856. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  28857. }
  28858. }
  28859. const hash = nodeProxy( HashNode );
  28860. addNodeElement( 'hash', hash );
  28861. addNodeClass( 'HashNode', HashNode );
  28862. // remapping functions https://iquilezles.org/articles/functions/
  28863. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  28864. 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 ) );
  28865. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  28866. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  28867. addNodeElement( 'parabola', parabola );
  28868. addNodeElement( 'gain', gain );
  28869. addNodeElement( 'pcurve', pcurve );
  28870. addNodeElement( 'sinc', sinc );
  28871. // https://github.com/cabbibo/glsl-tri-noise-3d
  28872. const tri = tslFn( ( [ x ] ) => {
  28873. return x.fract().sub( .5 ).abs();
  28874. } );
  28875. const tri3 = tslFn( ( [ p ] ) => {
  28876. 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. ) ) ) ) );
  28877. } );
  28878. const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => {
  28879. const p = vec3( p_immutable ).toVar();
  28880. const z = float( 1.4 ).toVar();
  28881. const rz = float( 0.0 ).toVar();
  28882. const bp = vec3( p ).toVar();
  28883. loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  28884. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  28885. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  28886. bp.mulAssign( 1.8 );
  28887. z.mulAssign( 1.5 );
  28888. p.mulAssign( 1.2 );
  28889. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  28890. rz.addAssign( t.div( z ) );
  28891. bp.addAssign( 0.14 );
  28892. } );
  28893. return rz;
  28894. } );
  28895. // layouts
  28896. tri.setLayout( {
  28897. name: 'tri',
  28898. type: 'float',
  28899. inputs: [
  28900. { name: 'x', type: 'float' }
  28901. ]
  28902. } );
  28903. tri3.setLayout( {
  28904. name: 'tri3',
  28905. type: 'vec3',
  28906. inputs: [
  28907. { name: 'p', type: 'vec3' }
  28908. ]
  28909. } );
  28910. triNoise3D.setLayout( {
  28911. name: 'triNoise3D',
  28912. type: 'float',
  28913. inputs: [
  28914. { name: 'p', type: 'vec3' },
  28915. { name: 'spd', type: 'float' },
  28916. { name: 'time', type: 'float' }
  28917. ]
  28918. } );
  28919. let discardExpression;
  28920. class DiscardNode extends CondNode {
  28921. constructor( condNode ) {
  28922. discardExpression = discardExpression || expression( 'discard' );
  28923. super( condNode, discardExpression );
  28924. }
  28925. }
  28926. const inlineDiscard = nodeProxy( DiscardNode );
  28927. const discard = ( condNode ) => inlineDiscard( condNode ).append();
  28928. const Return = () => expression( 'return' ).append();
  28929. addNodeElement( 'discard', discard ); // @TODO: Check... this cause a little confusing using in chaining
  28930. addNodeClass( 'DiscardNode', DiscardNode );
  28931. class FunctionOverloadingNode extends Node {
  28932. constructor( functionNodes = [], ...parametersNodes ) {
  28933. super();
  28934. this.functionNodes = functionNodes;
  28935. this.parametersNodes = parametersNodes;
  28936. this._candidateFnCall = null;
  28937. this.global = true;
  28938. }
  28939. getNodeType() {
  28940. return this.functionNodes[ 0 ].shaderNode.layout.type;
  28941. }
  28942. setup( builder ) {
  28943. const params = this.parametersNodes;
  28944. let candidateFnCall = this._candidateFnCall;
  28945. if ( candidateFnCall === null ) {
  28946. let candidateFn = null;
  28947. let candidateScore = - 1;
  28948. for ( const functionNode of this.functionNodes ) {
  28949. const shaderNode = functionNode.shaderNode;
  28950. const layout = shaderNode.layout;
  28951. if ( layout === null ) {
  28952. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  28953. }
  28954. const inputs = layout.inputs;
  28955. if ( params.length === inputs.length ) {
  28956. let score = 0;
  28957. for ( let i = 0; i < params.length; i ++ ) {
  28958. const param = params[ i ];
  28959. const input = inputs[ i ];
  28960. if ( param.getNodeType( builder ) === input.type ) {
  28961. score ++;
  28962. } else {
  28963. score = 0;
  28964. }
  28965. }
  28966. if ( score > candidateScore ) {
  28967. candidateFn = functionNode;
  28968. candidateScore = score;
  28969. }
  28970. }
  28971. }
  28972. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  28973. }
  28974. return candidateFnCall;
  28975. }
  28976. }
  28977. const overloadingBaseFn = nodeProxy( FunctionOverloadingNode );
  28978. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  28979. addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode );
  28980. class MatcapUVNode extends TempNode {
  28981. constructor() {
  28982. super( 'vec2' );
  28983. }
  28984. setup() {
  28985. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28986. const y = positionViewDirection.cross( x );
  28987. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28988. }
  28989. }
  28990. const matcapUV = nodeImmutable( MatcapUVNode );
  28991. addNodeClass( 'MatcapUVNode', MatcapUVNode );
  28992. class TimerNode extends UniformNode {
  28993. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  28994. super( value );
  28995. this.scope = scope;
  28996. this.scale = scale;
  28997. this.updateType = NodeUpdateType.FRAME;
  28998. }
  28999. /*
  29000. @TODO:
  29001. getNodeType( builder ) {
  29002. const scope = this.scope;
  29003. if ( scope === TimerNode.FRAME ) {
  29004. return 'uint';
  29005. }
  29006. return 'float';
  29007. }
  29008. */
  29009. update( frame ) {
  29010. const scope = this.scope;
  29011. const scale = this.scale;
  29012. if ( scope === TimerNode.LOCAL ) {
  29013. this.value += frame.deltaTime * scale;
  29014. } else if ( scope === TimerNode.DELTA ) {
  29015. this.value = frame.deltaTime * scale;
  29016. } else if ( scope === TimerNode.FRAME ) {
  29017. this.value = frame.frameId;
  29018. } else {
  29019. // global
  29020. this.value = frame.time * scale;
  29021. }
  29022. }
  29023. serialize( data ) {
  29024. super.serialize( data );
  29025. data.scope = this.scope;
  29026. data.scale = this.scale;
  29027. }
  29028. deserialize( data ) {
  29029. super.deserialize( data );
  29030. this.scope = data.scope;
  29031. this.scale = data.scale;
  29032. }
  29033. }
  29034. TimerNode.LOCAL = 'local';
  29035. TimerNode.GLOBAL = 'global';
  29036. TimerNode.DELTA = 'delta';
  29037. TimerNode.FRAME = 'frame';
  29038. // @TODO: add support to use node in timeScale
  29039. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  29040. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  29041. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  29042. const frameId = nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  29043. addNodeClass( 'TimerNode', TimerNode );
  29044. class OscNode extends Node {
  29045. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  29046. super();
  29047. this.method = method;
  29048. this.timeNode = timeNode;
  29049. }
  29050. getNodeType( builder ) {
  29051. return this.timeNode.getNodeType( builder );
  29052. }
  29053. setup() {
  29054. const method = this.method;
  29055. const timeNode = nodeObject( this.timeNode );
  29056. let outputNode = null;
  29057. if ( method === OscNode.SINE ) {
  29058. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  29059. } else if ( method === OscNode.SQUARE ) {
  29060. outputNode = timeNode.fract().round();
  29061. } else if ( method === OscNode.TRIANGLE ) {
  29062. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  29063. } else if ( method === OscNode.SAWTOOTH ) {
  29064. outputNode = timeNode.fract();
  29065. }
  29066. return outputNode;
  29067. }
  29068. serialize( data ) {
  29069. super.serialize( data );
  29070. data.method = this.method;
  29071. }
  29072. deserialize( data ) {
  29073. super.deserialize( data );
  29074. this.method = data.method;
  29075. }
  29076. }
  29077. OscNode.SINE = 'sine';
  29078. OscNode.SQUARE = 'square';
  29079. OscNode.TRIANGLE = 'triangle';
  29080. OscNode.SAWTOOTH = 'sawtooth';
  29081. const oscSine = nodeProxy( OscNode, OscNode.SINE );
  29082. const oscSquare = nodeProxy( OscNode, OscNode.SQUARE );
  29083. const oscTriangle = nodeProxy( OscNode, OscNode.TRIANGLE );
  29084. const oscSawtooth = nodeProxy( OscNode, OscNode.SAWTOOTH );
  29085. addNodeClass( 'OscNode', OscNode );
  29086. class PackingNode extends TempNode {
  29087. constructor( scope, node ) {
  29088. super();
  29089. this.scope = scope;
  29090. this.node = node;
  29091. }
  29092. getNodeType( builder ) {
  29093. return this.node.getNodeType( builder );
  29094. }
  29095. setup() {
  29096. const { scope, node } = this;
  29097. let result = null;
  29098. if ( scope === PackingNode.DIRECTION_TO_COLOR ) {
  29099. result = node.mul( 0.5 ).add( 0.5 );
  29100. } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) {
  29101. result = node.mul( 2.0 ).sub( 1 );
  29102. }
  29103. return result;
  29104. }
  29105. }
  29106. PackingNode.DIRECTION_TO_COLOR = 'directionToColor';
  29107. PackingNode.COLOR_TO_DIRECTION = 'colorToDirection';
  29108. const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR );
  29109. const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION );
  29110. addNodeElement( 'directionToColor', directionToColor );
  29111. addNodeElement( 'colorToDirection', colorToDirection );
  29112. addNodeClass( 'PackingNode', PackingNode );
  29113. class RemapNode extends Node {
  29114. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  29115. super();
  29116. this.node = node;
  29117. this.inLowNode = inLowNode;
  29118. this.inHighNode = inHighNode;
  29119. this.outLowNode = outLowNode;
  29120. this.outHighNode = outHighNode;
  29121. this.doClamp = true;
  29122. }
  29123. setup() {
  29124. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  29125. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  29126. if ( doClamp === true ) t = t.clamp();
  29127. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  29128. }
  29129. }
  29130. const remap = nodeProxy( RemapNode, null, null, { doClamp: false } );
  29131. const remapClamp = nodeProxy( RemapNode );
  29132. addNodeElement( 'remap', remap );
  29133. addNodeElement( 'remapClamp', remapClamp );
  29134. addNodeClass( 'RemapNode', RemapNode );
  29135. class RotateUVNode extends TempNode {
  29136. constructor( uvNode, rotationNode, centerNode = vec2( 0.5 ) ) {
  29137. super( 'vec2' );
  29138. this.uvNode = uvNode;
  29139. this.rotationNode = rotationNode;
  29140. this.centerNode = centerNode;
  29141. }
  29142. setup() {
  29143. const { uvNode, rotationNode, centerNode } = this;
  29144. const vector = uvNode.sub( centerNode );
  29145. return vector.rotate( rotationNode ).add( centerNode );
  29146. }
  29147. }
  29148. const rotateUV = nodeProxy( RotateUVNode );
  29149. addNodeElement( 'rotateUV', rotateUV );
  29150. addNodeClass( 'RotateUVNode', RotateUVNode );
  29151. class RotateNode extends TempNode {
  29152. constructor( positionNode, rotationNode ) {
  29153. super();
  29154. this.positionNode = positionNode;
  29155. this.rotationNode = rotationNode;
  29156. }
  29157. getNodeType( builder ) {
  29158. return this.positionNode.getNodeType( builder );
  29159. }
  29160. setup( builder ) {
  29161. const { rotationNode, positionNode } = this;
  29162. const nodeType = this.getNodeType( builder );
  29163. if ( nodeType === 'vec2' ) {
  29164. const cosAngle = rotationNode.cos();
  29165. const sinAngle = rotationNode.sin();
  29166. const rotationMatrix = mat2(
  29167. cosAngle, sinAngle,
  29168. sinAngle.negate(), cosAngle
  29169. );
  29170. return rotationMatrix.mul( positionNode );
  29171. } else {
  29172. const rotation = rotationNode;
  29173. 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 ) );
  29174. 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 ) );
  29175. 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 ) );
  29176. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29177. }
  29178. }
  29179. }
  29180. const rotate = nodeProxy( RotateNode );
  29181. addNodeElement( 'rotate', rotate );
  29182. addNodeClass( 'RotateNode', RotateNode );
  29183. class SpriteSheetUVNode extends Node {
  29184. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  29185. super( 'vec2' );
  29186. this.countNode = countNode;
  29187. this.uvNode = uvNode;
  29188. this.frameNode = frameNode;
  29189. }
  29190. setup() {
  29191. const { frameNode, uvNode, countNode } = this;
  29192. const { width, height } = countNode;
  29193. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  29194. const column = frameNum.mod( width );
  29195. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  29196. const scale = countNode.reciprocal();
  29197. const uvFrameOffset = vec2( column, row );
  29198. return uvNode.add( uvFrameOffset ).mul( scale );
  29199. }
  29200. }
  29201. const spritesheetUV = nodeProxy( SpriteSheetUVNode );
  29202. addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode );
  29203. class StorageArrayElementNode extends ArrayElementNode {
  29204. constructor( storageBufferNode, indexNode ) {
  29205. super( storageBufferNode, indexNode );
  29206. this.isStorageArrayElementNode = true;
  29207. }
  29208. set storageBufferNode( value ) {
  29209. this.node = value;
  29210. }
  29211. get storageBufferNode() {
  29212. return this.node;
  29213. }
  29214. setup( builder ) {
  29215. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29216. if ( ! this.node.instanceIndex && this.node.bufferObject === true ) {
  29217. builder.setupPBO( this.node );
  29218. }
  29219. }
  29220. return super.setup( builder );
  29221. }
  29222. generate( builder, output ) {
  29223. let snippet;
  29224. const isAssignContext = builder.context.assign;
  29225. //
  29226. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29227. const { node } = this;
  29228. if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) {
  29229. snippet = builder.generatePBO( this );
  29230. } else {
  29231. snippet = node.build( builder );
  29232. }
  29233. } else {
  29234. snippet = super.generate( builder );
  29235. }
  29236. if ( isAssignContext !== true ) {
  29237. const type = this.getNodeType( builder );
  29238. snippet = builder.format( snippet, type, output );
  29239. }
  29240. return snippet;
  29241. }
  29242. }
  29243. const storageElement = nodeProxy( StorageArrayElementNode );
  29244. addNodeElement( 'storageElement', storageElement );
  29245. addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode );
  29246. class TriplanarTexturesNode extends Node {
  29247. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  29248. super( 'vec4' );
  29249. this.textureXNode = textureXNode;
  29250. this.textureYNode = textureYNode;
  29251. this.textureZNode = textureZNode;
  29252. this.scaleNode = scaleNode;
  29253. this.positionNode = positionNode;
  29254. this.normalNode = normalNode;
  29255. }
  29256. setup() {
  29257. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  29258. // Ref: https://github.com/keijiro/StandardTriplanar
  29259. // Blending factor of triplanar mapping
  29260. let bf = normalNode.abs().normalize();
  29261. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  29262. // Triplanar mapping
  29263. const tx = positionNode.yz.mul( scaleNode );
  29264. const ty = positionNode.zx.mul( scaleNode );
  29265. const tz = positionNode.xy.mul( scaleNode );
  29266. // Base color
  29267. const textureX = textureXNode.value;
  29268. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  29269. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  29270. const cx = texture( textureX, tx ).mul( bf.x );
  29271. const cy = texture( textureY, ty ).mul( bf.y );
  29272. const cz = texture( textureZ, tz ).mul( bf.z );
  29273. return add( cx, cy, cz );
  29274. }
  29275. }
  29276. const triplanarTextures = nodeProxy( TriplanarTexturesNode );
  29277. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  29278. addNodeElement( 'triplanarTexture', triplanarTexture );
  29279. addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode );
  29280. const _reflectorPlane = new Plane();
  29281. const _normal = new Vector3();
  29282. const _reflectorWorldPosition = new Vector3();
  29283. const _cameraWorldPosition = new Vector3();
  29284. const _rotationMatrix = new Matrix4();
  29285. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  29286. const clipPlane = new Vector4();
  29287. const _view = new Vector3();
  29288. const _target = new Vector3();
  29289. const _q = new Vector4();
  29290. const _size$4 = new Vector2();
  29291. const _defaultRT = new RenderTarget();
  29292. const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y );
  29293. let _inReflector = false;
  29294. class ReflectorNode extends TextureNode {
  29295. constructor( parameters = {} ) {
  29296. super( _defaultRT.texture, _defaultUV );
  29297. const {
  29298. target = new Object3D(),
  29299. resolution = 1,
  29300. generateMipmaps = false,
  29301. bounces = true
  29302. } = parameters;
  29303. //
  29304. this.target = target;
  29305. this.resolution = resolution;
  29306. this.generateMipmaps = generateMipmaps;
  29307. this.bounces = bounces;
  29308. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  29309. this.virtualCameras = new WeakMap();
  29310. this.renderTargets = new WeakMap();
  29311. }
  29312. _updateResolution( renderTarget, renderer ) {
  29313. const resolution = this.resolution;
  29314. renderer.getDrawingBufferSize( _size$4 );
  29315. renderTarget.setSize( Math.round( _size$4.width * resolution ), Math.round( _size$4.height * resolution ) );
  29316. }
  29317. setup( builder ) {
  29318. this._updateResolution( _defaultRT, builder.renderer );
  29319. return super.setup( builder );
  29320. }
  29321. getTextureNode() {
  29322. return this.textureNode;
  29323. }
  29324. getVirtualCamera( camera ) {
  29325. let virtualCamera = this.virtualCameras.get( camera );
  29326. if ( virtualCamera === undefined ) {
  29327. virtualCamera = camera.clone();
  29328. this.virtualCameras.set( camera, virtualCamera );
  29329. }
  29330. return virtualCamera;
  29331. }
  29332. getRenderTarget( camera ) {
  29333. let renderTarget = this.renderTargets.get( camera );
  29334. if ( renderTarget === undefined ) {
  29335. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  29336. if ( this.generateMipmaps === true ) {
  29337. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  29338. renderTarget.texture.generateMipmaps = true;
  29339. }
  29340. this.renderTargets.set( camera, renderTarget );
  29341. }
  29342. return renderTarget;
  29343. }
  29344. updateBefore( frame ) {
  29345. if ( this.bounces === false && _inReflector ) return false;
  29346. _inReflector = true;
  29347. const { scene, camera, renderer, material } = frame;
  29348. const { target } = this;
  29349. const virtualCamera = this.getVirtualCamera( camera );
  29350. const renderTarget = this.getRenderTarget( virtualCamera );
  29351. renderer.getDrawingBufferSize( _size$4 );
  29352. this._updateResolution( renderTarget, renderer );
  29353. //
  29354. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  29355. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  29356. _rotationMatrix.extractRotation( target.matrixWorld );
  29357. _normal.set( 0, 0, 1 );
  29358. _normal.applyMatrix4( _rotationMatrix );
  29359. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  29360. // Avoid rendering when reflector is facing away
  29361. if ( _view.dot( _normal ) > 0 ) return;
  29362. _view.reflect( _normal ).negate();
  29363. _view.add( _reflectorWorldPosition );
  29364. _rotationMatrix.extractRotation( camera.matrixWorld );
  29365. _lookAtPosition.set( 0, 0, - 1 );
  29366. _lookAtPosition.applyMatrix4( _rotationMatrix );
  29367. _lookAtPosition.add( _cameraWorldPosition );
  29368. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  29369. _target.reflect( _normal ).negate();
  29370. _target.add( _reflectorWorldPosition );
  29371. //
  29372. virtualCamera.coordinateSystem = camera.coordinateSystem;
  29373. virtualCamera.position.copy( _view );
  29374. virtualCamera.up.set( 0, 1, 0 );
  29375. virtualCamera.up.applyMatrix4( _rotationMatrix );
  29376. virtualCamera.up.reflect( _normal );
  29377. virtualCamera.lookAt( _target );
  29378. virtualCamera.near = camera.near;
  29379. virtualCamera.far = camera.far;
  29380. virtualCamera.updateMatrixWorld();
  29381. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  29382. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  29383. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  29384. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  29385. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  29386. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  29387. const projectionMatrix = virtualCamera.projectionMatrix;
  29388. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  29389. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  29390. _q.z = - 1.0;
  29391. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  29392. // Calculate the scaled plane vector
  29393. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  29394. const clipBias = 0;
  29395. // Replacing the third row of the projection matrix
  29396. projectionMatrix.elements[ 2 ] = clipPlane.x;
  29397. projectionMatrix.elements[ 6 ] = clipPlane.y;
  29398. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  29399. projectionMatrix.elements[ 14 ] = clipPlane.w;
  29400. //
  29401. this.value = renderTarget.texture;
  29402. material.visible = false;
  29403. const currentRenderTarget = renderer.getRenderTarget();
  29404. renderer.setRenderTarget( renderTarget );
  29405. renderer.render( scene, virtualCamera );
  29406. renderer.setRenderTarget( currentRenderTarget );
  29407. material.visible = true;
  29408. _inReflector = false;
  29409. }
  29410. }
  29411. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  29412. // Helper for passes that need to fill the viewport with a single quad.
  29413. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  29414. // https://github.com/mrdoob/three.js/pull/21358
  29415. class QuadGeometry extends BufferGeometry {
  29416. constructor( flipY = false ) {
  29417. super();
  29418. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  29419. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  29420. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  29421. }
  29422. }
  29423. const _geometry = new QuadGeometry();
  29424. class QuadMesh extends Mesh {
  29425. constructor( material = null ) {
  29426. super( _geometry, material );
  29427. this.camera = _camera;
  29428. }
  29429. renderAsync( renderer ) {
  29430. return renderer.renderAsync( this, _camera );
  29431. }
  29432. render( renderer ) {
  29433. renderer.render( this, _camera );
  29434. }
  29435. }
  29436. const _quadMesh = new QuadMesh( new NodeMaterial() );
  29437. const _size$3 = new Vector2();
  29438. class RTTNode extends TextureNode {
  29439. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  29440. const renderTarget = new RenderTarget( width, height, options );
  29441. super( renderTarget.texture, uv() );
  29442. this.node = node;
  29443. this.width = width;
  29444. this.height = height;
  29445. this.renderTarget = renderTarget;
  29446. this.textureNeedsUpdate = true;
  29447. this.autoUpdate = true;
  29448. this.updateMap = new WeakMap();
  29449. this.updateBeforeType = NodeUpdateType.RENDER;
  29450. }
  29451. get autoSize() {
  29452. return this.width === null;
  29453. }
  29454. setSize( width, height ) {
  29455. this.width = width;
  29456. this.height = height;
  29457. this.renderTarget.setSize( width, height );
  29458. this.textureNeedsUpdate = true;
  29459. }
  29460. updateBefore( { renderer } ) {
  29461. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  29462. this.textureNeedsUpdate = false;
  29463. //
  29464. if ( this.autoSize === true ) {
  29465. const size = renderer.getSize( _size$3 );
  29466. this.setSize( size.width, size.height );
  29467. }
  29468. //
  29469. _quadMesh.material.fragmentNode = this.node;
  29470. //
  29471. const currentRenderTarget = renderer.getRenderTarget();
  29472. renderer.setRenderTarget( this.renderTarget );
  29473. _quadMesh.render( renderer );
  29474. renderer.setRenderTarget( currentRenderTarget );
  29475. }
  29476. clone() {
  29477. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  29478. newNode.sampler = this.sampler;
  29479. newNode.referenceNode = this;
  29480. return newNode;
  29481. }
  29482. }
  29483. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  29484. addNodeElement( 'toTexture', ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ) );
  29485. addNodeClass( 'RTTNode', RTTNode );
  29486. class VertexColorNode extends AttributeNode {
  29487. constructor( index = 0 ) {
  29488. super( null, 'vec4' );
  29489. this.isVertexColorNode = true;
  29490. this.index = index;
  29491. }
  29492. getAttributeName( /*builder*/ ) {
  29493. const index = this.index;
  29494. return 'color' + ( index > 0 ? index : '' );
  29495. }
  29496. generate( builder ) {
  29497. const attributeName = this.getAttributeName( builder );
  29498. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  29499. let result;
  29500. if ( geometryAttribute === true ) {
  29501. result = super.generate( builder );
  29502. } else {
  29503. // Vertex color fallback should be white
  29504. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  29505. }
  29506. return result;
  29507. }
  29508. serialize( data ) {
  29509. super.serialize( data );
  29510. data.index = this.index;
  29511. }
  29512. deserialize( data ) {
  29513. super.deserialize( data );
  29514. this.index = data.index;
  29515. }
  29516. }
  29517. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  29518. addNodeClass( 'VertexColorNode', VertexColorNode );
  29519. class RendererReferenceNode extends ReferenceNode {
  29520. constructor( property, inputType, renderer = null ) {
  29521. super( property, inputType, renderer );
  29522. this.renderer = renderer;
  29523. }
  29524. updateReference( state ) {
  29525. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  29526. return this.reference;
  29527. }
  29528. }
  29529. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  29530. addNodeClass( 'RendererReferenceNode', RendererReferenceNode );
  29531. // Mipped Bicubic Texture Filtering by N8
  29532. // https://www.shadertoy.com/view/Dl2SDW
  29533. const bC = 1.0 / 6.0;
  29534. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  29535. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  29536. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  29537. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  29538. const g0 = ( a ) => w0( a ).add( w1( a ) );
  29539. const g1 = ( a ) => w2( a ).add( w3( a ) );
  29540. // h0 and h1 are the two offset functions
  29541. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  29542. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  29543. const bicubic = ( textureNode, texelSize, lod ) => {
  29544. const uv = textureNode.uvNode;
  29545. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  29546. const iuv = floor( uvScaled );
  29547. const fuv = fract( uvScaled );
  29548. const g0x = g0( fuv.x );
  29549. const g1x = g1( fuv.x );
  29550. const h0x = h0( fuv.x );
  29551. const h1x = h1( fuv.x );
  29552. const h0y = h0( fuv.y );
  29553. const h1y = h1( fuv.y );
  29554. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29555. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29556. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29557. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29558. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  29559. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  29560. return a.add( b );
  29561. };
  29562. const textureBicubicMethod = ( textureNode, lodNode ) => {
  29563. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  29564. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  29565. const fLodSizeInv = div( 1.0, fLodSize );
  29566. const cLodSizeInv = div( 1.0, cLodSize );
  29567. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  29568. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  29569. return fract( lodNode ).mix( fSample, cSample );
  29570. };
  29571. class TextureBicubicNode extends TempNode {
  29572. constructor( textureNode, blurNode = float( 3 ) ) {
  29573. super( 'vec4' );
  29574. this.textureNode = textureNode;
  29575. this.blurNode = blurNode;
  29576. }
  29577. setup() {
  29578. return textureBicubicMethod( this.textureNode, this.blurNode );
  29579. }
  29580. }
  29581. const textureBicubic = nodeProxy( TextureBicubicNode );
  29582. addNodeElement( 'bicubic', textureBicubic );
  29583. addNodeClass( 'TextureBicubicNode', TextureBicubicNode );
  29584. class PointUVNode extends Node {
  29585. constructor() {
  29586. super( 'vec2' );
  29587. this.isPointUVNode = true;
  29588. }
  29589. generate( /*builder*/ ) {
  29590. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  29591. }
  29592. }
  29593. const pointUV = nodeImmutable( PointUVNode );
  29594. addNodeClass( 'PointUVNode', PointUVNode );
  29595. class SceneNode extends Node {
  29596. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  29597. super();
  29598. this.scope = scope;
  29599. this.scene = scene;
  29600. }
  29601. setup( builder ) {
  29602. const scope = this.scope;
  29603. const scene = this.scene !== null ? this.scene : builder.scene;
  29604. let output;
  29605. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  29606. output = reference( 'backgroundBlurriness', 'float', scene );
  29607. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  29608. output = reference( 'backgroundIntensity', 'float', scene );
  29609. } else {
  29610. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  29611. }
  29612. return output;
  29613. }
  29614. }
  29615. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  29616. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  29617. const backgroundBlurriness = nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  29618. const backgroundIntensity = nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  29619. addNodeClass( 'SceneNode', SceneNode );
  29620. const GPUPrimitiveTopology = {
  29621. PointList: 'point-list',
  29622. LineList: 'line-list',
  29623. LineStrip: 'line-strip',
  29624. TriangleList: 'triangle-list',
  29625. TriangleStrip: 'triangle-strip',
  29626. };
  29627. const GPUCompareFunction = {
  29628. Never: 'never',
  29629. Less: 'less',
  29630. Equal: 'equal',
  29631. LessEqual: 'less-equal',
  29632. Greater: 'greater',
  29633. NotEqual: 'not-equal',
  29634. GreaterEqual: 'greater-equal',
  29635. Always: 'always'
  29636. };
  29637. const GPUStoreOp = {
  29638. Store: 'store',
  29639. Discard: 'discard'
  29640. };
  29641. const GPULoadOp = {
  29642. Load: 'load',
  29643. Clear: 'clear'
  29644. };
  29645. const GPUFrontFace = {
  29646. CCW: 'ccw',
  29647. CW: 'cw'
  29648. };
  29649. const GPUCullMode = {
  29650. None: 'none',
  29651. Front: 'front',
  29652. Back: 'back'
  29653. };
  29654. const GPUIndexFormat = {
  29655. Uint16: 'uint16',
  29656. Uint32: 'uint32'
  29657. };
  29658. const GPUTextureFormat = {
  29659. // 8-bit formats
  29660. R8Unorm: 'r8unorm',
  29661. R8Snorm: 'r8snorm',
  29662. R8Uint: 'r8uint',
  29663. R8Sint: 'r8sint',
  29664. // 16-bit formats
  29665. R16Uint: 'r16uint',
  29666. R16Sint: 'r16sint',
  29667. R16Float: 'r16float',
  29668. RG8Unorm: 'rg8unorm',
  29669. RG8Snorm: 'rg8snorm',
  29670. RG8Uint: 'rg8uint',
  29671. RG8Sint: 'rg8sint',
  29672. // 32-bit formats
  29673. R32Uint: 'r32uint',
  29674. R32Sint: 'r32sint',
  29675. R32Float: 'r32float',
  29676. RG16Uint: 'rg16uint',
  29677. RG16Sint: 'rg16sint',
  29678. RG16Float: 'rg16float',
  29679. RGBA8Unorm: 'rgba8unorm',
  29680. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  29681. RGBA8Snorm: 'rgba8snorm',
  29682. RGBA8Uint: 'rgba8uint',
  29683. RGBA8Sint: 'rgba8sint',
  29684. BGRA8Unorm: 'bgra8unorm',
  29685. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  29686. // Packed 32-bit formats
  29687. RGB9E5UFloat: 'rgb9e5ufloat',
  29688. RGB10A2Unorm: 'rgb10a2unorm',
  29689. RG11B10uFloat: 'rgb10a2unorm',
  29690. // 64-bit formats
  29691. RG32Uint: 'rg32uint',
  29692. RG32Sint: 'rg32sint',
  29693. RG32Float: 'rg32float',
  29694. RGBA16Uint: 'rgba16uint',
  29695. RGBA16Sint: 'rgba16sint',
  29696. RGBA16Float: 'rgba16float',
  29697. // 128-bit formats
  29698. RGBA32Uint: 'rgba32uint',
  29699. RGBA32Sint: 'rgba32sint',
  29700. RGBA32Float: 'rgba32float',
  29701. // Depth and stencil formats
  29702. Stencil8: 'stencil8',
  29703. Depth16Unorm: 'depth16unorm',
  29704. Depth24Plus: 'depth24plus',
  29705. Depth24PlusStencil8: 'depth24plus-stencil8',
  29706. Depth32Float: 'depth32float',
  29707. // 'depth32float-stencil8' extension
  29708. Depth32FloatStencil8: 'depth32float-stencil8',
  29709. // BC compressed formats usable if 'texture-compression-bc' is both
  29710. // supported by the device/user agent and enabled in requestDevice.
  29711. BC1RGBAUnorm: 'bc1-rgba-unorm',
  29712. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  29713. BC2RGBAUnorm: 'bc2-rgba-unorm',
  29714. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  29715. BC3RGBAUnorm: 'bc3-rgba-unorm',
  29716. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  29717. BC4RUnorm: 'bc4-r-unorm',
  29718. BC4RSnorm: 'bc4-r-snorm',
  29719. BC5RGUnorm: 'bc5-rg-unorm',
  29720. BC5RGSnorm: 'bc5-rg-snorm',
  29721. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  29722. BC6HRGBFloat: 'bc6h-rgb-float',
  29723. BC7RGBAUnorm: 'bc7-rgba-unorm',
  29724. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  29725. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  29726. // supported by the device/user agent and enabled in requestDevice.
  29727. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  29728. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  29729. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  29730. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  29731. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  29732. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  29733. EACR11Unorm: 'eac-r11unorm',
  29734. EACR11Snorm: 'eac-r11snorm',
  29735. EACRG11Unorm: 'eac-rg11unorm',
  29736. EACRG11Snorm: 'eac-rg11snorm',
  29737. // ASTC compressed formats usable if 'texture-compression-astc' is both
  29738. // supported by the device/user agent and enabled in requestDevice.
  29739. ASTC4x4Unorm: 'astc-4x4-unorm',
  29740. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  29741. ASTC5x4Unorm: 'astc-5x4-unorm',
  29742. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  29743. ASTC5x5Unorm: 'astc-5x5-unorm',
  29744. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  29745. ASTC6x5Unorm: 'astc-6x5-unorm',
  29746. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  29747. ASTC6x6Unorm: 'astc-6x6-unorm',
  29748. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  29749. ASTC8x5Unorm: 'astc-8x5-unorm',
  29750. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  29751. ASTC8x6Unorm: 'astc-8x6-unorm',
  29752. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  29753. ASTC8x8Unorm: 'astc-8x8-unorm',
  29754. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  29755. ASTC10x5Unorm: 'astc-10x5-unorm',
  29756. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  29757. ASTC10x6Unorm: 'astc-10x6-unorm',
  29758. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  29759. ASTC10x8Unorm: 'astc-10x8-unorm',
  29760. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  29761. ASTC10x10Unorm: 'astc-10x10-unorm',
  29762. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  29763. ASTC12x10Unorm: 'astc-12x10-unorm',
  29764. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  29765. ASTC12x12Unorm: 'astc-12x12-unorm',
  29766. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  29767. };
  29768. const GPUAddressMode = {
  29769. ClampToEdge: 'clamp-to-edge',
  29770. Repeat: 'repeat',
  29771. MirrorRepeat: 'mirror-repeat'
  29772. };
  29773. const GPUFilterMode = {
  29774. Linear: 'linear',
  29775. Nearest: 'nearest'
  29776. };
  29777. const GPUBlendFactor = {
  29778. Zero: 'zero',
  29779. One: 'one',
  29780. Src: 'src',
  29781. OneMinusSrc: 'one-minus-src',
  29782. SrcAlpha: 'src-alpha',
  29783. OneMinusSrcAlpha: 'one-minus-src-alpha',
  29784. Dst: 'dst',
  29785. OneMinusDstColor: 'one-minus-dst',
  29786. DstAlpha: 'dst-alpha',
  29787. OneMinusDstAlpha: 'one-minus-dst-alpha',
  29788. SrcAlphaSaturated: 'src-alpha-saturated',
  29789. Constant: 'constant',
  29790. OneMinusConstant: 'one-minus-constant'
  29791. };
  29792. const GPUBlendOperation = {
  29793. Add: 'add',
  29794. Subtract: 'subtract',
  29795. ReverseSubtract: 'reverse-subtract',
  29796. Min: 'min',
  29797. Max: 'max'
  29798. };
  29799. const GPUColorWriteFlags = {
  29800. None: 0,
  29801. Red: 0x1,
  29802. Green: 0x2,
  29803. Blue: 0x4,
  29804. Alpha: 0x8,
  29805. All: 0xF
  29806. };
  29807. const GPUStencilOperation = {
  29808. Keep: 'keep',
  29809. Zero: 'zero',
  29810. Replace: 'replace',
  29811. Invert: 'invert',
  29812. IncrementClamp: 'increment-clamp',
  29813. DecrementClamp: 'decrement-clamp',
  29814. IncrementWrap: 'increment-wrap',
  29815. DecrementWrap: 'decrement-wrap'
  29816. };
  29817. const GPUBufferBindingType = {
  29818. Uniform: 'uniform',
  29819. Storage: 'storage',
  29820. ReadOnlyStorage: 'read-only-storage'
  29821. };
  29822. const GPUStorageTextureAccess = {
  29823. WriteOnly: 'write-only',
  29824. ReadOnly: 'read-only',
  29825. ReadWrite: 'read-write',
  29826. };
  29827. const GPUTextureSampleType = {
  29828. Float: 'float',
  29829. UnfilterableFloat: 'unfilterable-float',
  29830. Depth: 'depth',
  29831. SInt: 'sint',
  29832. UInt: 'uint'
  29833. };
  29834. const GPUTextureDimension = {
  29835. OneD: '1d',
  29836. TwoD: '2d',
  29837. ThreeD: '3d'
  29838. };
  29839. const GPUTextureViewDimension = {
  29840. OneD: '1d',
  29841. TwoD: '2d',
  29842. TwoDArray: '2d-array',
  29843. Cube: 'cube',
  29844. CubeArray: 'cube-array',
  29845. ThreeD: '3d'
  29846. };
  29847. const GPUTextureAspect = {
  29848. All: 'all',
  29849. StencilOnly: 'stencil-only',
  29850. DepthOnly: 'depth-only'
  29851. };
  29852. const GPUInputStepMode = {
  29853. Vertex: 'vertex',
  29854. Instance: 'instance'
  29855. };
  29856. const GPUFeatureName = {
  29857. DepthClipControl: 'depth-clip-control',
  29858. Depth32FloatStencil8: 'depth32float-stencil8',
  29859. TextureCompressionBC: 'texture-compression-bc',
  29860. TextureCompressionETC2: 'texture-compression-etc2',
  29861. TextureCompressionASTC: 'texture-compression-astc',
  29862. TimestampQuery: 'timestamp-query',
  29863. IndirectFirstInstance: 'indirect-first-instance',
  29864. ShaderF16: 'shader-f16',
  29865. RG11B10UFloat: 'rg11b10ufloat-renderable',
  29866. BGRA8UNormStorage: 'bgra8unorm-storage',
  29867. Float32Filterable: 'float32-filterable'
  29868. };
  29869. class StorageBufferNode extends BufferNode {
  29870. constructor( value, bufferType, bufferCount = 0 ) {
  29871. super( value, bufferType, bufferCount );
  29872. this.isStorageBufferNode = true;
  29873. this.access = GPUBufferBindingType.Storage;
  29874. this.bufferObject = false;
  29875. this.bufferCount = bufferCount;
  29876. this._attribute = null;
  29877. this._varying = null;
  29878. this.global = true;
  29879. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  29880. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  29881. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  29882. else value.isStorageBufferAttribute = true;
  29883. }
  29884. }
  29885. getHash( builder ) {
  29886. if ( this.bufferCount === 0 ) {
  29887. let bufferData = builder.globalCache.getData( this.value );
  29888. if ( bufferData === undefined ) {
  29889. bufferData = {
  29890. node: this
  29891. };
  29892. builder.globalCache.setData( this.value, bufferData );
  29893. }
  29894. return bufferData.node.uuid;
  29895. }
  29896. return this.uuid;
  29897. }
  29898. getInputType( /*builder*/ ) {
  29899. return 'storageBuffer';
  29900. }
  29901. element( indexNode ) {
  29902. return storageElement( this, indexNode );
  29903. }
  29904. setBufferObject( value ) {
  29905. this.bufferObject = value;
  29906. return this;
  29907. }
  29908. setAccess( value ) {
  29909. this.access = value;
  29910. return this;
  29911. }
  29912. toReadOnly() {
  29913. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  29914. }
  29915. generate( builder ) {
  29916. if ( builder.isAvailable( 'storageBuffer' ) ) {
  29917. return super.generate( builder );
  29918. }
  29919. const nodeType = this.getNodeType( builder );
  29920. if ( this._attribute === null ) {
  29921. this._attribute = bufferAttribute( this.value );
  29922. this._varying = varying( this._attribute );
  29923. }
  29924. const output = this._varying.build( builder, nodeType );
  29925. builder.registerTransform( output, this._attribute );
  29926. return output;
  29927. }
  29928. }
  29929. // Read-Write Storage
  29930. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  29931. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  29932. addNodeClass( 'StorageBufferNode', StorageBufferNode );
  29933. class StorageTextureNode extends TextureNode {
  29934. constructor( value, uvNode, storeNode = null ) {
  29935. super( value, uvNode );
  29936. this.storeNode = storeNode;
  29937. this.isStorageTextureNode = true;
  29938. this.access = GPUStorageTextureAccess.WriteOnly;
  29939. }
  29940. getInputType( /*builder*/ ) {
  29941. return 'storageTexture';
  29942. }
  29943. setup( builder ) {
  29944. super.setup( builder );
  29945. const properties = builder.getNodeProperties( this );
  29946. properties.storeNode = this.storeNode;
  29947. }
  29948. setAccess( value ) {
  29949. this.access = value;
  29950. return this;
  29951. }
  29952. generate( builder, output ) {
  29953. let snippet;
  29954. if ( this.storeNode !== null ) {
  29955. snippet = this.generateStore( builder );
  29956. } else {
  29957. snippet = super.generate( builder, output );
  29958. }
  29959. return snippet;
  29960. }
  29961. toReadOnly() {
  29962. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  29963. }
  29964. toWriteOnly() {
  29965. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  29966. }
  29967. generateStore( builder ) {
  29968. const properties = builder.getNodeProperties( this );
  29969. const { uvNode, storeNode } = properties;
  29970. const textureProperty = super.generate( builder, 'property' );
  29971. const uvSnippet = uvNode.build( builder, 'uvec2' );
  29972. const storeSnippet = storeNode.build( builder, 'vec4' );
  29973. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  29974. builder.addLineFlowCode( snippet );
  29975. }
  29976. }
  29977. const storageTexture = nodeProxy( StorageTextureNode );
  29978. const textureStore = ( value, uvNode, storeNode ) => {
  29979. const node = storageTexture( value, uvNode, storeNode );
  29980. if ( storeNode !== null ) node.append();
  29981. return node;
  29982. };
  29983. addNodeClass( 'StorageTextureNode', StorageTextureNode );
  29984. const normal = tslFn( ( { texture, uv } ) => {
  29985. const epsilon = 0.0001;
  29986. const ret = vec3().temp();
  29987. If( uv.x.lessThan( epsilon ), () => {
  29988. ret.assign( vec3( 1, 0, 0 ) );
  29989. } ).elseif( uv.y.lessThan( epsilon ), () => {
  29990. ret.assign( vec3( 0, 1, 0 ) );
  29991. } ).elseif( uv.z.lessThan( epsilon ), () => {
  29992. ret.assign( vec3( 0, 0, 1 ) );
  29993. } ).elseif( uv.x.greaterThan( 1 - epsilon ), () => {
  29994. ret.assign( vec3( - 1, 0, 0 ) );
  29995. } ).elseif( uv.y.greaterThan( 1 - epsilon ), () => {
  29996. ret.assign( vec3( 0, - 1, 0 ) );
  29997. } ).elseif( uv.z.greaterThan( 1 - epsilon ), () => {
  29998. ret.assign( vec3( 0, 0, - 1 ) );
  29999. } ).else( () => {
  30000. const step = 0.01;
  30001. 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 );
  30002. 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 );
  30003. 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 );
  30004. ret.assign( vec3( x, y, z ) );
  30005. } );
  30006. return ret.normalize();
  30007. } );
  30008. class Texture3DNode extends TextureNode {
  30009. constructor( value, uvNode = null, levelNode = null ) {
  30010. super( value, uvNode, levelNode );
  30011. this.isTexture3DNode = true;
  30012. }
  30013. getInputType( /*builder*/ ) {
  30014. return 'texture3D';
  30015. }
  30016. getDefaultUV() {
  30017. return vec3( 0.5, 0.5, 0.5 );
  30018. }
  30019. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  30020. setupUV( builder, uvNode ) {
  30021. return uvNode;
  30022. }
  30023. generateUV( builder, uvNode ) {
  30024. return uvNode.build( builder, 'vec3' );
  30025. }
  30026. normal( uvNode ) {
  30027. return normal( { texture: this, uv: uvNode } );
  30028. }
  30029. }
  30030. const texture3D = nodeProxy( Texture3DNode );
  30031. addNodeClass( 'Texture3DNode', Texture3DNode );
  30032. class UserDataNode extends ReferenceNode {
  30033. constructor( property, inputType, userData = null ) {
  30034. super( property, inputType, userData );
  30035. this.userData = userData;
  30036. }
  30037. update( frame ) {
  30038. this.reference = this.userData !== null ? this.userData : frame.object.userData;
  30039. super.update( frame );
  30040. }
  30041. }
  30042. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  30043. addNodeClass( 'UserDataNode', UserDataNode );
  30044. const BurnNode = tslFn( ( { base, blend } ) => {
  30045. const fn = ( c ) => blend[ c ].lessThan( EPSILON ).cond( blend[ c ], base[ c ].oneMinus().div( blend[ c ] ).oneMinus().max( 0 ) );
  30046. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30047. } ).setLayout( {
  30048. name: 'burnColor',
  30049. type: 'vec3',
  30050. inputs: [
  30051. { name: 'base', type: 'vec3' },
  30052. { name: 'blend', type: 'vec3' }
  30053. ]
  30054. } );
  30055. const DodgeNode = tslFn( ( { base, blend } ) => {
  30056. const fn = ( c ) => blend[ c ].equal( 1.0 ).cond( blend[ c ], base[ c ].div( blend[ c ].oneMinus() ).max( 0 ) );
  30057. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30058. } ).setLayout( {
  30059. name: 'dodgeColor',
  30060. type: 'vec3',
  30061. inputs: [
  30062. { name: 'base', type: 'vec3' },
  30063. { name: 'blend', type: 'vec3' }
  30064. ]
  30065. } );
  30066. const ScreenNode = tslFn( ( { base, blend } ) => {
  30067. const fn = ( c ) => base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus();
  30068. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30069. } ).setLayout( {
  30070. name: 'screenColor',
  30071. type: 'vec3',
  30072. inputs: [
  30073. { name: 'base', type: 'vec3' },
  30074. { name: 'blend', type: 'vec3' }
  30075. ]
  30076. } );
  30077. const OverlayNode = tslFn( ( { base, blend } ) => {
  30078. const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() );
  30079. //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) );
  30080. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30081. } ).setLayout( {
  30082. name: 'overlayColor',
  30083. type: 'vec3',
  30084. inputs: [
  30085. { name: 'base', type: 'vec3' },
  30086. { name: 'blend', type: 'vec3' }
  30087. ]
  30088. } );
  30089. class BlendModeNode extends TempNode {
  30090. constructor( blendMode, baseNode, blendNode ) {
  30091. super();
  30092. this.blendMode = blendMode;
  30093. this.baseNode = baseNode;
  30094. this.blendNode = blendNode;
  30095. }
  30096. setup() {
  30097. const { blendMode, baseNode, blendNode } = this;
  30098. const params = { base: baseNode, blend: blendNode };
  30099. let outputNode = null;
  30100. if ( blendMode === BlendModeNode.BURN ) {
  30101. outputNode = BurnNode( params );
  30102. } else if ( blendMode === BlendModeNode.DODGE ) {
  30103. outputNode = DodgeNode( params );
  30104. } else if ( blendMode === BlendModeNode.SCREEN ) {
  30105. outputNode = ScreenNode( params );
  30106. } else if ( blendMode === BlendModeNode.OVERLAY ) {
  30107. outputNode = OverlayNode( params );
  30108. }
  30109. return outputNode;
  30110. }
  30111. }
  30112. BlendModeNode.BURN = 'burn';
  30113. BlendModeNode.DODGE = 'dodge';
  30114. BlendModeNode.SCREEN = 'screen';
  30115. BlendModeNode.OVERLAY = 'overlay';
  30116. const burn = nodeProxy( BlendModeNode, BlendModeNode.BURN );
  30117. const dodge = nodeProxy( BlendModeNode, BlendModeNode.DODGE );
  30118. const overlay = nodeProxy( BlendModeNode, BlendModeNode.OVERLAY );
  30119. const screen = nodeProxy( BlendModeNode, BlendModeNode.SCREEN );
  30120. addNodeElement( 'burn', burn );
  30121. addNodeElement( 'dodge', dodge );
  30122. addNodeElement( 'overlay', overlay );
  30123. addNodeElement( 'screen', screen );
  30124. addNodeClass( 'BlendModeNode', BlendModeNode );
  30125. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  30126. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  30127. const dHdxy_fwd = tslFn( ( { textureNode, bumpScale } ) => {
  30128. // It's used to preserve the same TextureNode instance
  30129. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  30130. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  30131. return vec2(
  30132. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  30133. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  30134. ).mul( bumpScale );
  30135. } );
  30136. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  30137. const perturbNormalArb = tslFn( ( inputs ) => {
  30138. const { surf_pos, surf_norm, dHdxy } = inputs;
  30139. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  30140. const vSigmaX = surf_pos.dFdx().normalize();
  30141. const vSigmaY = surf_pos.dFdy().normalize();
  30142. const vN = surf_norm; // normalized
  30143. const R1 = vSigmaY.cross( vN );
  30144. const R2 = vN.cross( vSigmaX );
  30145. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  30146. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  30147. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  30148. } );
  30149. class BumpMapNode extends TempNode {
  30150. constructor( textureNode, scaleNode = null ) {
  30151. super( 'vec3' );
  30152. this.textureNode = textureNode;
  30153. this.scaleNode = scaleNode;
  30154. }
  30155. setup() {
  30156. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  30157. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  30158. return perturbNormalArb( {
  30159. surf_pos: positionView,
  30160. surf_norm: normalView,
  30161. dHdxy
  30162. } );
  30163. }
  30164. }
  30165. const bumpMap = nodeProxy( BumpMapNode );
  30166. addNodeElement( 'bumpMap', bumpMap );
  30167. addNodeClass( 'BumpMapNode', BumpMapNode );
  30168. const saturationNode = tslFn( ( { color, adjustment } ) => {
  30169. return adjustment.mix( luminance( color.rgb ), color.rgb );
  30170. } );
  30171. const vibranceNode = tslFn( ( { color, adjustment } ) => {
  30172. const average = add( color.r, color.g, color.b ).div( 3.0 );
  30173. const mx = color.r.max( color.g.max( color.b ) );
  30174. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  30175. return mix( color.rgb, mx, amt );
  30176. } );
  30177. const hueNode = tslFn( ( { color, adjustment } ) => {
  30178. const k = vec3( 0.57735, 0.57735, 0.57735 );
  30179. const cosAngle = adjustment.cos();
  30180. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  30181. } );
  30182. class ColorAdjustmentNode extends TempNode {
  30183. constructor( method, colorNode, adjustmentNode = float( 1 ) ) {
  30184. super( 'vec3' );
  30185. this.method = method;
  30186. this.colorNode = colorNode;
  30187. this.adjustmentNode = adjustmentNode;
  30188. }
  30189. setup() {
  30190. const { method, colorNode, adjustmentNode } = this;
  30191. const callParams = { color: colorNode, adjustment: adjustmentNode };
  30192. let outputNode = null;
  30193. if ( method === ColorAdjustmentNode.SATURATION ) {
  30194. outputNode = saturationNode( callParams );
  30195. } else if ( method === ColorAdjustmentNode.VIBRANCE ) {
  30196. outputNode = vibranceNode( callParams );
  30197. } else if ( method === ColorAdjustmentNode.HUE ) {
  30198. outputNode = hueNode( callParams );
  30199. } else {
  30200. console.error( `${ this.type }: Method "${ this.method }" not supported!` );
  30201. }
  30202. return outputNode;
  30203. }
  30204. }
  30205. ColorAdjustmentNode.SATURATION = 'saturation';
  30206. ColorAdjustmentNode.VIBRANCE = 'vibrance';
  30207. ColorAdjustmentNode.HUE = 'hue';
  30208. const saturation = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.SATURATION );
  30209. const vibrance = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.VIBRANCE );
  30210. const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE );
  30211. const lumaCoeffs = vec3( 0.2125, 0.7154, 0.0721 );
  30212. const luminance = ( color, luma = lumaCoeffs ) => dot( color, luma );
  30213. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  30214. addNodeElement( 'saturation', saturation );
  30215. addNodeElement( 'vibrance', vibrance );
  30216. addNodeElement( 'hue', hue );
  30217. addNodeElement( 'threshold', threshold );
  30218. addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode );
  30219. // Normal Mapping Without Precomputed Tangents
  30220. // http://www.thetenthplanet.de/archives/1180
  30221. const perturbNormal2Arb = tslFn( ( inputs ) => {
  30222. const { eye_pos, surf_norm, mapN, uv } = inputs;
  30223. const q0 = eye_pos.dFdx();
  30224. const q1 = eye_pos.dFdy();
  30225. const st0 = uv.dFdx();
  30226. const st1 = uv.dFdy();
  30227. const N = surf_norm; // normalized
  30228. const q1perp = q1.cross( N );
  30229. const q0perp = N.cross( q0 );
  30230. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  30231. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  30232. const det = T.dot( T ).max( B.dot( B ) );
  30233. const scale = faceDirection.mul( det.inverseSqrt() );
  30234. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  30235. } );
  30236. class NormalMapNode extends TempNode {
  30237. constructor( node, scaleNode = null ) {
  30238. super( 'vec3' );
  30239. this.node = node;
  30240. this.scaleNode = scaleNode;
  30241. this.normalMapType = TangentSpaceNormalMap;
  30242. }
  30243. setup( builder ) {
  30244. const { normalMapType, scaleNode } = this;
  30245. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  30246. if ( scaleNode !== null ) {
  30247. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  30248. }
  30249. let outputNode = null;
  30250. if ( normalMapType === ObjectSpaceNormalMap ) {
  30251. outputNode = modelNormalMatrix.mul( normalMap ).normalize();
  30252. } else if ( normalMapType === TangentSpaceNormalMap ) {
  30253. const tangent = builder.hasGeometryAttribute( 'tangent' );
  30254. if ( tangent === true ) {
  30255. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  30256. } else {
  30257. outputNode = perturbNormal2Arb( {
  30258. eye_pos: positionView,
  30259. surf_norm: normalView,
  30260. mapN: normalMap,
  30261. uv: uv()
  30262. } );
  30263. }
  30264. }
  30265. return outputNode;
  30266. }
  30267. }
  30268. const normalMap = nodeProxy( NormalMapNode );
  30269. addNodeElement( 'normalMap', normalMap );
  30270. addNodeClass( 'NormalMapNode', NormalMapNode );
  30271. class PosterizeNode extends TempNode {
  30272. constructor( sourceNode, stepsNode ) {
  30273. super();
  30274. this.sourceNode = sourceNode;
  30275. this.stepsNode = stepsNode;
  30276. }
  30277. setup() {
  30278. const { sourceNode, stepsNode } = this;
  30279. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  30280. }
  30281. }
  30282. const posterize = nodeProxy( PosterizeNode );
  30283. addNodeElement( 'posterize', posterize );
  30284. addNodeClass( 'PosterizeNode', PosterizeNode );
  30285. // exposure only
  30286. const LinearToneMappingNode = tslFn( ( { color, exposure } ) => {
  30287. return color.mul( exposure ).clamp();
  30288. } );
  30289. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  30290. const ReinhardToneMappingNode = tslFn( ( { color, exposure } ) => {
  30291. color = color.mul( exposure );
  30292. return color.div( color.add( 1.0 ) ).clamp();
  30293. } );
  30294. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  30295. const OptimizedCineonToneMappingNode = tslFn( ( { color, exposure } ) => {
  30296. // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
  30297. color = color.mul( exposure );
  30298. color = color.sub( 0.004 ).max( 0.0 );
  30299. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  30300. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  30301. return a.div( b ).pow( 2.2 );
  30302. } );
  30303. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30304. const RRTAndODTFit = tslFn( ( { color } ) => {
  30305. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  30306. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  30307. return a.div( b );
  30308. } );
  30309. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30310. const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => {
  30311. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  30312. const ACESInputMat = mat3(
  30313. 0.59719, 0.35458, 0.04823,
  30314. 0.07600, 0.90834, 0.01566,
  30315. 0.02840, 0.13383, 0.83777
  30316. );
  30317. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  30318. const ACESOutputMat = mat3(
  30319. 1.60475, - 0.53108, - 0.07367,
  30320. - 0.10208, 1.10813, - 0.00605,
  30321. - 0.00327, - 0.07276, 1.07602
  30322. );
  30323. color = color.mul( exposure ).div( 0.6 );
  30324. color = ACESInputMat.mul( color );
  30325. // Apply RRT and ODT
  30326. color = RRTAndODTFit( { color } );
  30327. color = ACESOutputMat.mul( color );
  30328. // Clamp to [0, 1]
  30329. return color.clamp();
  30330. } );
  30331. const LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  30332. const LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  30333. const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => {
  30334. const x = vec3( x_immutable ).toVar();
  30335. const x2 = vec3( x.mul( x ) ).toVar();
  30336. const x4 = vec3( x2.mul( x2 ) ).toVar();
  30337. 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 ) ) ) );
  30338. } );
  30339. const AGXToneMappingNode = tslFn( ( { color, exposure } ) => {
  30340. const colortone = vec3( color ).toVar();
  30341. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  30342. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  30343. const AgxMinEv = float( - 12.47393 );
  30344. const AgxMaxEv = float( 4.026069 );
  30345. colortone.mulAssign( exposure );
  30346. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  30347. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  30348. colortone.assign( max$1( colortone, 1e-10 ) );
  30349. colortone.assign( log2( colortone ) );
  30350. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  30351. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30352. colortone.assign( agxDefaultContrastApprox( colortone ) );
  30353. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  30354. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  30355. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  30356. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30357. return colortone;
  30358. } );
  30359. // https://modelviewer.dev/examples/tone-mapping
  30360. const NeutralToneMappingNode = tslFn( ( { color, exposure } ) => {
  30361. const StartCompression = float( 0.8 - 0.04 );
  30362. const Desaturation = float( 0.15 );
  30363. color = color.mul( exposure );
  30364. const x = min$1( color.r, min$1( color.g, color.b ) );
  30365. const offset = cond( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  30366. color.subAssign( offset );
  30367. const peak = max$1( color.r, max$1( color.g, color.b ) );
  30368. If( peak.lessThan( StartCompression ), () => {
  30369. return color;
  30370. } );
  30371. const d = sub( 1, StartCompression );
  30372. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  30373. color.mulAssign( newPeak.div( peak ) );
  30374. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  30375. return mix( color, vec3( newPeak ), g );
  30376. } ).setLayout( {
  30377. name: 'NeutralToneMapping',
  30378. type: 'vec3',
  30379. inputs: [
  30380. { name: 'color', type: 'vec3' },
  30381. { name: 'exposure', type: 'float' }
  30382. ]
  30383. } );
  30384. const toneMappingLib = {
  30385. [ LinearToneMapping ]: LinearToneMappingNode,
  30386. [ ReinhardToneMapping ]: ReinhardToneMappingNode,
  30387. [ CineonToneMapping ]: OptimizedCineonToneMappingNode,
  30388. [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode,
  30389. [ AgXToneMapping ]: AGXToneMappingNode,
  30390. [ NeutralToneMapping ]: NeutralToneMappingNode
  30391. };
  30392. class ToneMappingNode extends TempNode {
  30393. constructor( toneMapping = NoToneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  30394. super( 'vec3' );
  30395. this.toneMapping = toneMapping;
  30396. this.exposureNode = exposureNode;
  30397. this.colorNode = colorNode;
  30398. }
  30399. getCacheKey() {
  30400. let cacheKey = super.getCacheKey();
  30401. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  30402. return cacheKey;
  30403. }
  30404. setup( builder ) {
  30405. const colorNode = this.colorNode || builder.context.color;
  30406. const toneMapping = this.toneMapping;
  30407. if ( toneMapping === NoToneMapping ) return colorNode;
  30408. const toneMappingParams = { exposure: this.exposureNode, color: colorNode };
  30409. const toneMappingNode = toneMappingLib[ toneMapping ];
  30410. let outputNode = null;
  30411. if ( toneMappingNode ) {
  30412. outputNode = toneMappingNode( toneMappingParams );
  30413. } else {
  30414. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  30415. outputNode = colorNode;
  30416. }
  30417. return outputNode;
  30418. }
  30419. }
  30420. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  30421. const toneMappingExposure = rendererReference( 'toneMappingExposure', 'float' );
  30422. addNodeElement( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  30423. addNodeClass( 'ToneMappingNode', ToneMappingNode );
  30424. let _sharedFramebuffer = null;
  30425. class ViewportSharedTextureNode extends ViewportTextureNode {
  30426. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  30427. if ( _sharedFramebuffer === null ) {
  30428. _sharedFramebuffer = new FramebufferTexture();
  30429. }
  30430. super( uvNode, levelNode, _sharedFramebuffer );
  30431. }
  30432. updateReference() {
  30433. return this;
  30434. }
  30435. }
  30436. const viewportSharedTexture = nodeProxy( ViewportSharedTextureNode );
  30437. addNodeElement( 'viewportSharedTexture', viewportSharedTexture );
  30438. addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode );
  30439. const _size$2 = new Vector2();
  30440. class PassTextureNode extends TextureNode {
  30441. constructor( passNode, texture ) {
  30442. super( texture );
  30443. this.passNode = passNode;
  30444. this.setUpdateMatrix( false );
  30445. }
  30446. setup( builder ) {
  30447. this.passNode.build( builder );
  30448. return super.setup( builder );
  30449. }
  30450. clone() {
  30451. return new this.constructor( this.passNode, this.value );
  30452. }
  30453. }
  30454. class PassNode extends TempNode {
  30455. constructor( scope, scene, camera ) {
  30456. super( 'vec4' );
  30457. this.scope = scope;
  30458. this.scene = scene;
  30459. this.camera = camera;
  30460. this._pixelRatio = 1;
  30461. this._width = 1;
  30462. this._height = 1;
  30463. const depthTexture = new DepthTexture();
  30464. depthTexture.isRenderTargetTexture = true;
  30465. //depthTexture.type = FloatType;
  30466. depthTexture.name = 'PostProcessingDepth';
  30467. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType } );
  30468. renderTarget.texture.name = 'PostProcessing';
  30469. renderTarget.depthTexture = depthTexture;
  30470. this.renderTarget = renderTarget;
  30471. this.updateBeforeType = NodeUpdateType.FRAME;
  30472. this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) );
  30473. this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) );
  30474. this._linearDepthNode = null;
  30475. this._viewZNode = null;
  30476. this._cameraNear = uniform( 0 );
  30477. this._cameraFar = uniform( 0 );
  30478. this.isPassNode = true;
  30479. }
  30480. isGlobal() {
  30481. return true;
  30482. }
  30483. getTextureNode() {
  30484. return this._textureNode;
  30485. }
  30486. getTextureDepthNode() {
  30487. return this._depthTextureNode;
  30488. }
  30489. getViewZNode() {
  30490. if ( this._viewZNode === null ) {
  30491. const cameraNear = this._cameraNear;
  30492. const cameraFar = this._cameraFar;
  30493. this._viewZNode = perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar );
  30494. }
  30495. return this._viewZNode;
  30496. }
  30497. getLinearDepthNode() {
  30498. if ( this._linearDepthNode === null ) {
  30499. const cameraNear = this._cameraNear;
  30500. const cameraFar = this._cameraFar;
  30501. // TODO: just if ( builder.camera.isPerspectiveCamera )
  30502. this._linearDepthNode = viewZToOrthographicDepth( this.getViewZNode(), cameraNear, cameraFar );
  30503. }
  30504. return this._linearDepthNode;
  30505. }
  30506. setup() {
  30507. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  30508. }
  30509. updateBefore( frame ) {
  30510. const { renderer } = frame;
  30511. const { scene, camera } = this;
  30512. this._pixelRatio = renderer.getPixelRatio();
  30513. const size = renderer.getSize( _size$2 );
  30514. this.setSize( size.width, size.height );
  30515. const currentRenderTarget = renderer.getRenderTarget();
  30516. this._cameraNear.value = camera.near;
  30517. this._cameraFar.value = camera.far;
  30518. renderer.setRenderTarget( this.renderTarget );
  30519. renderer.render( scene, camera );
  30520. renderer.setRenderTarget( currentRenderTarget );
  30521. }
  30522. setSize( width, height ) {
  30523. this._width = width;
  30524. this._height = height;
  30525. const effectiveWidth = this._width * this._pixelRatio;
  30526. const effectiveHeight = this._height * this._pixelRatio;
  30527. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  30528. }
  30529. setPixelRatio( pixelRatio ) {
  30530. this._pixelRatio = pixelRatio;
  30531. this.setSize( this._width, this._height );
  30532. }
  30533. dispose() {
  30534. this.renderTarget.dispose();
  30535. }
  30536. }
  30537. PassNode.COLOR = 'color';
  30538. PassNode.DEPTH = 'depth';
  30539. const pass = ( scene, camera ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera ) );
  30540. const texturePass = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  30541. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  30542. addNodeClass( 'PassNode', PassNode );
  30543. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  30544. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  30545. const quadMesh1 = new QuadMesh();
  30546. const quadMesh2 = new QuadMesh();
  30547. class GaussianBlurNode extends TempNode {
  30548. constructor( textureNode, directionNode = null, sigma = 2 ) {
  30549. super( 'vec4' );
  30550. this.textureNode = textureNode;
  30551. this.directionNode = directionNode;
  30552. this.sigma = sigma;
  30553. this._invSize = uniform( new Vector2() );
  30554. this._passDirection = uniform( new Vector2() );
  30555. this._horizontalRT = new RenderTarget();
  30556. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  30557. this._verticalRT = new RenderTarget();
  30558. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  30559. this._textureNode = texturePass( this, this._verticalRT.texture );
  30560. this.updateBeforeType = NodeUpdateType.RENDER;
  30561. this.resolution = new Vector2( 1, 1 );
  30562. }
  30563. setSize( width, height ) {
  30564. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30565. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30566. this._invSize.value.set( 1 / width, 1 / height );
  30567. this._horizontalRT.setSize( width, height );
  30568. this._verticalRT.setSize( width, height );
  30569. }
  30570. updateBefore( frame ) {
  30571. const { renderer } = frame;
  30572. const textureNode = this.textureNode;
  30573. const map = textureNode.value;
  30574. const currentRenderTarget = renderer.getRenderTarget();
  30575. const currentTexture = textureNode.value;
  30576. quadMesh1.material = this._material;
  30577. quadMesh2.material = this._material;
  30578. this.setSize( map.image.width, map.image.height );
  30579. const textureType = map.type;
  30580. this._horizontalRT.texture.type = textureType;
  30581. this._verticalRT.texture.type = textureType;
  30582. // horizontal
  30583. renderer.setRenderTarget( this._horizontalRT );
  30584. this._passDirection.value.set( 1, 0 );
  30585. quadMesh1.render( renderer );
  30586. // vertical
  30587. textureNode.value = this._horizontalRT.texture;
  30588. renderer.setRenderTarget( this._verticalRT );
  30589. this._passDirection.value.set( 0, 1 );
  30590. quadMesh2.render( renderer );
  30591. // restore
  30592. renderer.setRenderTarget( currentRenderTarget );
  30593. textureNode.value = currentTexture;
  30594. }
  30595. getTextureNode() {
  30596. return this._textureNode;
  30597. }
  30598. setup( builder ) {
  30599. const textureNode = this.textureNode;
  30600. if ( textureNode.isTextureNode !== true ) {
  30601. console.error( 'GaussianBlurNode requires a TextureNode.' );
  30602. return vec4();
  30603. }
  30604. //
  30605. const uvNode = textureNode.uvNode || uv();
  30606. const directionNode = vec2( this.directionNode || 1 );
  30607. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30608. const blur = tslFn( () => {
  30609. const kernelSize = 3 + ( 2 * this.sigma );
  30610. const gaussianCoefficients = this._getCoefficients( kernelSize );
  30611. const invSize = this._invSize;
  30612. const direction = directionNode.mul( this._passDirection );
  30613. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  30614. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  30615. for ( let i = 1; i < kernelSize; i ++ ) {
  30616. const x = float( i );
  30617. const w = float( gaussianCoefficients[ i ] );
  30618. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  30619. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  30620. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  30621. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  30622. weightSum.addAssign( mul( 2.0, w ) );
  30623. }
  30624. return diffuseSum.div( weightSum );
  30625. } );
  30626. //
  30627. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30628. material.fragmentNode = blur();
  30629. //
  30630. const properties = builder.getNodeProperties( this );
  30631. properties.textureNode = textureNode;
  30632. //
  30633. return this._textureNode;
  30634. }
  30635. _getCoefficients( kernelRadius ) {
  30636. const coefficients = [];
  30637. for ( let i = 0; i < kernelRadius; i ++ ) {
  30638. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  30639. }
  30640. return coefficients;
  30641. }
  30642. }
  30643. const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( nodeObject( node ).toTexture(), directionNode, sigma ) );
  30644. addNodeElement( 'gaussianBlur', gaussianBlur );
  30645. const _size$1 = new Vector2();
  30646. const quadMeshComp = new QuadMesh();
  30647. class AfterImageNode extends TempNode {
  30648. constructor( textureNode, damp = 0.96 ) {
  30649. super( textureNode );
  30650. this.textureNode = textureNode;
  30651. this.textureNodeOld = texture();
  30652. this.damp = uniform( damp );
  30653. this._compRT = new RenderTarget();
  30654. this._compRT.texture.name = 'AfterImageNode.comp';
  30655. this._oldRT = new RenderTarget();
  30656. this._oldRT.texture.name = 'AfterImageNode.old';
  30657. this._textureNode = texturePass( this, this._compRT.texture );
  30658. this.updateBeforeType = NodeUpdateType.RENDER;
  30659. }
  30660. getTextureNode() {
  30661. return this._textureNode;
  30662. }
  30663. setSize( width, height ) {
  30664. this._compRT.setSize( width, height );
  30665. this._oldRT.setSize( width, height );
  30666. }
  30667. updateBefore( frame ) {
  30668. const { renderer } = frame;
  30669. const textureNode = this.textureNode;
  30670. const map = textureNode.value;
  30671. const textureType = map.type;
  30672. this._compRT.texture.type = textureType;
  30673. this._oldRT.texture.type = textureType;
  30674. renderer.getDrawingBufferSize( _size$1 );
  30675. this.setSize( _size$1.x, _size$1.y );
  30676. const currentRenderTarget = renderer.getRenderTarget();
  30677. const currentTexture = textureNode.value;
  30678. this.textureNodeOld.value = this._oldRT.texture;
  30679. // comp
  30680. renderer.setRenderTarget( this._compRT );
  30681. quadMeshComp.render( renderer );
  30682. // Swap the textures
  30683. const temp = this._oldRT;
  30684. this._oldRT = this._compRT;
  30685. this._compRT = temp;
  30686. renderer.setRenderTarget( currentRenderTarget );
  30687. textureNode.value = currentTexture;
  30688. }
  30689. setup( builder ) {
  30690. const textureNode = this.textureNode;
  30691. const textureNodeOld = this.textureNodeOld;
  30692. //
  30693. const uvNode = textureNode.uvNode || uv();
  30694. textureNodeOld.uvNode = uvNode;
  30695. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30696. const when_gt = tslFn( ( [ x_immutable, y_immutable ] ) => {
  30697. const y = float( y_immutable ).toVar();
  30698. const x = vec4( x_immutable ).toVar();
  30699. return max$1( sign( x.sub( y ) ), 0.0 );
  30700. } );
  30701. const afterImg = tslFn( () => {
  30702. const texelOld = vec4( textureNodeOld );
  30703. const texelNew = vec4( sampleTexture( uvNode ) );
  30704. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  30705. return max$1( texelNew, texelOld );
  30706. } );
  30707. //
  30708. const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() );
  30709. materialComposed.fragmentNode = afterImg();
  30710. quadMeshComp.material = materialComposed;
  30711. //
  30712. const properties = builder.getNodeProperties( this );
  30713. properties.textureNode = textureNode;
  30714. //
  30715. return this._textureNode;
  30716. }
  30717. }
  30718. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( node ).toTexture(), damp ) );
  30719. addNodeElement( 'afterImage', afterImage );
  30720. const quadMesh$1 = new QuadMesh();
  30721. class AnamorphicNode extends TempNode {
  30722. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  30723. super( 'vec4' );
  30724. this.textureNode = textureNode;
  30725. this.tresholdNode = tresholdNode;
  30726. this.scaleNode = scaleNode;
  30727. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  30728. this.samples = samples;
  30729. this.resolution = new Vector2( 1, 1 );
  30730. this._renderTarget = new RenderTarget();
  30731. this._renderTarget.texture.name = 'anamorphic';
  30732. this._invSize = uniform( new Vector2() );
  30733. this._textureNode = texturePass( this, this._renderTarget.texture );
  30734. this.updateBeforeType = NodeUpdateType.RENDER;
  30735. }
  30736. getTextureNode() {
  30737. return this._textureNode;
  30738. }
  30739. setSize( width, height ) {
  30740. this._invSize.value.set( 1 / width, 1 / height );
  30741. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30742. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30743. this._renderTarget.setSize( width, height );
  30744. }
  30745. updateBefore( frame ) {
  30746. const { renderer } = frame;
  30747. const textureNode = this.textureNode;
  30748. const map = textureNode.value;
  30749. this._renderTarget.texture.type = map.type;
  30750. const currentRenderTarget = renderer.getRenderTarget();
  30751. const currentTexture = textureNode.value;
  30752. quadMesh$1.material = this._material;
  30753. this.setSize( map.image.width, map.image.height );
  30754. // render
  30755. renderer.setRenderTarget( this._renderTarget );
  30756. quadMesh$1.render( renderer );
  30757. // restore
  30758. renderer.setRenderTarget( currentRenderTarget );
  30759. textureNode.value = currentTexture;
  30760. }
  30761. setup( builder ) {
  30762. const textureNode = this.textureNode;
  30763. const uvNode = textureNode.uvNode || uv();
  30764. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30765. const anamorph = tslFn( () => {
  30766. const samples = this.samples;
  30767. const halfSamples = Math.floor( samples / 2 );
  30768. const total = vec3( 0 ).toVar();
  30769. loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  30770. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  30771. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  30772. const color = sampleTexture( uv );
  30773. const pass = threshold( color, this.tresholdNode ).mul( softness );
  30774. total.addAssign( pass );
  30775. } );
  30776. return total.mul( this.colorNode );
  30777. } );
  30778. //
  30779. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30780. material.fragmentNode = anamorph();
  30781. //
  30782. const properties = builder.getNodeProperties( this );
  30783. properties.textureNode = textureNode;
  30784. //
  30785. return this._textureNode;
  30786. }
  30787. }
  30788. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ).toTexture(), nodeObject( threshold ), nodeObject( scale ), samples ) );
  30789. addNodeElement( 'anamorphic', anamorphic );
  30790. class SobelOperatorNode extends TempNode {
  30791. constructor( textureNode ) {
  30792. super();
  30793. this.textureNode = textureNode;
  30794. this.updateBeforeType = NodeUpdateType.RENDER;
  30795. this._invSize = uniform( new Vector2() );
  30796. }
  30797. updateBefore() {
  30798. const map = this.textureNode.value;
  30799. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  30800. }
  30801. setup() {
  30802. const { textureNode } = this;
  30803. const uvNode = textureNode.uvNode || uv();
  30804. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30805. const sobel = tslFn( () => {
  30806. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  30807. const texel = this._invSize;
  30808. // kernel definition (in glsl matrices are filled in column-major order)
  30809. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  30810. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  30811. // fetch the 3x3 neighbourhood of a fragment
  30812. // first column
  30813. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  30814. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  30815. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  30816. // second column
  30817. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  30818. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  30819. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  30820. // third column
  30821. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  30822. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  30823. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  30824. // gradient value in x direction
  30825. const valueGx = add(
  30826. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  30827. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  30828. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  30829. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  30830. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  30831. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  30832. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  30833. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  30834. Gx[ 2 ][ 2 ].mul( tx2y2 )
  30835. );
  30836. // gradient value in y direction
  30837. const valueGy = add(
  30838. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  30839. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  30840. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  30841. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  30842. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  30843. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  30844. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  30845. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  30846. Gy[ 2 ][ 2 ].mul( tx2y2 )
  30847. );
  30848. // magnitute of the total gradient
  30849. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  30850. return vec4( vec3( G ), 1 );
  30851. } );
  30852. const outputNode = sobel();
  30853. return outputNode;
  30854. }
  30855. }
  30856. const sobel = ( node ) => nodeObject( new SobelOperatorNode( nodeObject( node ).toTexture() ) );
  30857. addNodeElement( 'sobel', sobel );
  30858. class DepthOfFieldNode extends TempNode {
  30859. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  30860. super();
  30861. this.textureNode = textureNode;
  30862. this.viewZNode = viewZNode;
  30863. this.focusNode = focusNode;
  30864. this.apertureNode = apertureNode;
  30865. this.maxblurNode = maxblurNode;
  30866. this._aspect = uniform( 0 );
  30867. this.updateBeforeType = NodeUpdateType.RENDER;
  30868. }
  30869. updateBefore() {
  30870. const map = this.textureNode.value;
  30871. this._aspect.value = map.image.width / map.image.height;
  30872. }
  30873. setup() {
  30874. const textureNode = this.textureNode;
  30875. const uvNode = textureNode.uvNode || uv();
  30876. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30877. const dof = tslFn( () => {
  30878. const aspectcorrect = vec2( 1.0, this._aspect );
  30879. const factor = this.focusNode.add( this.viewZNode );
  30880. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  30881. const dofblur9 = dofblur.mul( 0.9 );
  30882. const dofblur7 = dofblur.mul( 0.7 );
  30883. const dofblur4 = dofblur.mul( 0.4 );
  30884. let col = vec4( 0.0 );
  30885. col = col.add( sampleTexture( uvNode ) );
  30886. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30887. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30888. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30889. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30890. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30891. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30892. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30893. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30894. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30895. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30896. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30897. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30898. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30899. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30900. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30901. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30902. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30903. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30904. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30905. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30906. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30907. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30908. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30909. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30910. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30911. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30912. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30913. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30914. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30915. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30916. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30917. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30918. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30919. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30920. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30921. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30922. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30923. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30924. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30925. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30926. col = col.div( 41 );
  30927. col.a = 1;
  30928. return vec4( col );
  30929. } );
  30930. const outputNode = dof();
  30931. return outputNode;
  30932. }
  30933. }
  30934. const dof = ( node, viewZNode, focus = 1, aperture = 0.025, maxblur = 1 ) => nodeObject( new DepthOfFieldNode( nodeObject( node ).toTexture(), nodeObject( viewZNode ), nodeObject( focus ), nodeObject( aperture ), nodeObject( maxblur ) ) );
  30935. addNodeElement( 'dof', dof );
  30936. class DotScreenNode extends TempNode {
  30937. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  30938. super( 'vec4' );
  30939. this.inputNode = inputNode;
  30940. this.center = uniform( center );
  30941. this.angle = uniform( angle );
  30942. this.scale = uniform( scale );
  30943. this._size = uniform( new Vector2() );
  30944. this.updateBeforeType = NodeUpdateType.RENDER;
  30945. }
  30946. updateBefore() {
  30947. const map = this.inputNode.value;
  30948. this._size.value.set( map.image.width, map.image.height );
  30949. }
  30950. setup() {
  30951. const inputNode = this.inputNode;
  30952. const pattern = tslFn( () => {
  30953. const s = sin( this.angle );
  30954. const c = cos( this.angle );
  30955. const tex = uv().mul( this._size ).sub( this.center );
  30956. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  30957. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  30958. } );
  30959. const dotScreen = tslFn( () => {
  30960. const color = inputNode;
  30961. const average = add( color.r, color.g, color.b ).div( 3 );
  30962. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  30963. } );
  30964. const outputNode = dotScreen();
  30965. return outputNode;
  30966. }
  30967. }
  30968. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  30969. addNodeElement( 'dotScreen', dotScreen );
  30970. class RGBShiftNode extends TempNode {
  30971. constructor( textureNode, amount = 0.005, angle = 0 ) {
  30972. super( 'vec4' );
  30973. this.textureNode = textureNode;
  30974. this.amount = uniform( amount );
  30975. this.angle = uniform( angle );
  30976. }
  30977. setup() {
  30978. const { textureNode } = this;
  30979. const uvNode = textureNode.uvNode || uv();
  30980. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30981. const rgbShift = tslFn( () => {
  30982. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  30983. const cr = sampleTexture( uvNode.add( offset ) );
  30984. const cga = sampleTexture( uvNode );
  30985. const cb = sampleTexture( uvNode.sub( offset ) );
  30986. return vec4( cr.r, cga.g, cb.b, cga.a );
  30987. } );
  30988. return rgbShift();
  30989. }
  30990. }
  30991. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( nodeObject( node ).toTexture(), amount, angle ) );
  30992. addNodeElement( 'rgbShift', rgbShift );
  30993. class FilmNode extends TempNode {
  30994. constructor( inputNode, intensityNode = null, uvNode = null ) {
  30995. super();
  30996. this.inputNode = inputNode;
  30997. this.intensityNode = intensityNode;
  30998. this.uvNode = uvNode;
  30999. }
  31000. setup() {
  31001. const uvNode = this.uvNode || uv();
  31002. const film = tslFn( () => {
  31003. const base = this.inputNode.rgb;
  31004. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  31005. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  31006. if ( this.intensityNode !== null ) {
  31007. color = mix( base, color, this.intensityNode );
  31008. }
  31009. return vec4( color, this.inputNode.a );
  31010. } );
  31011. const outputNode = film();
  31012. return outputNode;
  31013. }
  31014. }
  31015. const film = nodeProxy( FilmNode );
  31016. addNodeElement( 'film', film );
  31017. class Lut3DNode extends TempNode {
  31018. constructor( inputNode, lutNode, size, intensityNode ) {
  31019. super();
  31020. this.inputNode = inputNode;
  31021. this.lutNode = lutNode;
  31022. this.size = uniform( size );
  31023. this.intensityNode = intensityNode;
  31024. }
  31025. setup() {
  31026. const { inputNode, lutNode } = this;
  31027. const sampleLut = ( uv ) => lutNode.uv( uv );
  31028. const lut3D = tslFn( () => {
  31029. const base = inputNode;
  31030. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  31031. const pixelWidth = float( 1.0 ).div( this.size );
  31032. const halfPixelWidth = float( 0.5 ).div( this.size );
  31033. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  31034. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  31035. return vec4( mix( base, lutValue, this.intensityNode ) );
  31036. } );
  31037. const outputNode = lut3D();
  31038. return outputNode;
  31039. }
  31040. }
  31041. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  31042. addNodeElement( 'lut3D', lut3D );
  31043. class RenderOutputNode extends TempNode {
  31044. constructor( colorNode, toneMapping, outputColorSpace ) {
  31045. super( 'vec4' );
  31046. this.colorNode = colorNode;
  31047. this.toneMapping = toneMapping;
  31048. this.outputColorSpace = outputColorSpace;
  31049. this.isRenderOutput = true;
  31050. }
  31051. setup( { context } ) {
  31052. let outputNode = this.colorNode || context.color;
  31053. // tone mapping
  31054. const toneMapping = this.toneMapping !== null ? this.toneMapping : context.toneMapping;
  31055. const outputColorSpace = this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace;
  31056. if ( toneMapping !== NoToneMapping ) {
  31057. outputNode = outputNode.toneMapping( toneMapping );
  31058. }
  31059. // output color space
  31060. if ( outputColorSpace === SRGBColorSpace ) {
  31061. outputNode = outputNode.linearToColorSpace( outputColorSpace );
  31062. }
  31063. return outputNode;
  31064. }
  31065. }
  31066. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  31067. addNodeElement( 'renderOutput', renderOutput );
  31068. addNodeClass( 'RenderOutputNode', RenderOutputNode );
  31069. class FunctionCallNode extends TempNode {
  31070. constructor( functionNode = null, parameters = {} ) {
  31071. super();
  31072. this.functionNode = functionNode;
  31073. this.parameters = parameters;
  31074. }
  31075. setParameters( parameters ) {
  31076. this.parameters = parameters;
  31077. return this;
  31078. }
  31079. getParameters() {
  31080. return this.parameters;
  31081. }
  31082. getNodeType( builder ) {
  31083. return this.functionNode.getNodeType( builder );
  31084. }
  31085. generate( builder ) {
  31086. const params = [];
  31087. const functionNode = this.functionNode;
  31088. const inputs = functionNode.getInputs( builder );
  31089. const parameters = this.parameters;
  31090. if ( Array.isArray( parameters ) ) {
  31091. for ( let i = 0; i < parameters.length; i ++ ) {
  31092. const inputNode = inputs[ i ];
  31093. const node = parameters[ i ];
  31094. params.push( node.build( builder, inputNode.type ) );
  31095. }
  31096. } else {
  31097. for ( const inputNode of inputs ) {
  31098. const node = parameters[ inputNode.name ];
  31099. if ( node !== undefined ) {
  31100. params.push( node.build( builder, inputNode.type ) );
  31101. } else {
  31102. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  31103. }
  31104. }
  31105. }
  31106. const functionName = functionNode.build( builder, 'property' );
  31107. return `${functionName}( ${params.join( ', ' )} )`;
  31108. }
  31109. }
  31110. const call = ( func, ...params ) => {
  31111. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  31112. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  31113. };
  31114. addNodeElement( 'call', call );
  31115. addNodeClass( 'FunctionCallNode', FunctionCallNode );
  31116. class ScriptableValueNode extends Node {
  31117. constructor( value = null ) {
  31118. super();
  31119. this._value = value;
  31120. this._cache = null;
  31121. this.inputType = null;
  31122. this.outpuType = null;
  31123. this.events = new EventDispatcher();
  31124. this.isScriptableValueNode = true;
  31125. }
  31126. get isScriptableOutputNode() {
  31127. return this.outputType !== null;
  31128. }
  31129. set value( val ) {
  31130. if ( this._value === val ) return;
  31131. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  31132. URL.revokeObjectURL( this._cache );
  31133. this._cache = null;
  31134. }
  31135. this._value = val;
  31136. this.events.dispatchEvent( { type: 'change' } );
  31137. this.refresh();
  31138. }
  31139. get value() {
  31140. return this._value;
  31141. }
  31142. refresh() {
  31143. this.events.dispatchEvent( { type: 'refresh' } );
  31144. }
  31145. getValue() {
  31146. const value = this.value;
  31147. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  31148. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  31149. } else if ( value && value.value !== null && value.value !== undefined && (
  31150. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  31151. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  31152. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  31153. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  31154. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  31155. ( this.inputType === 'Color' && value.value.isColor ) ||
  31156. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  31157. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  31158. ) ) {
  31159. return value.value;
  31160. }
  31161. return this._cache || value;
  31162. }
  31163. getNodeType( builder ) {
  31164. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  31165. }
  31166. setup() {
  31167. return this.value && this.value.isNode ? this.value : float();
  31168. }
  31169. serialize( data ) {
  31170. super.serialize( data );
  31171. if ( this.value !== null ) {
  31172. if ( this.inputType === 'ArrayBuffer' ) {
  31173. data.value = arrayBufferToBase64( this.value );
  31174. } else {
  31175. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  31176. }
  31177. } else {
  31178. data.value = null;
  31179. }
  31180. data.inputType = this.inputType;
  31181. data.outputType = this.outputType;
  31182. }
  31183. deserialize( data ) {
  31184. super.deserialize( data );
  31185. let value = null;
  31186. if ( data.value !== null ) {
  31187. if ( data.inputType === 'ArrayBuffer' ) {
  31188. value = base64ToArrayBuffer( data.value );
  31189. } else if ( data.inputType === 'Texture' ) {
  31190. value = data.meta.textures[ data.value ];
  31191. } else {
  31192. value = data.meta.nodes[ data.value ] || null;
  31193. }
  31194. }
  31195. this.value = value;
  31196. this.inputType = data.inputType;
  31197. this.outputType = data.outputType;
  31198. }
  31199. }
  31200. const scriptableValue = nodeProxy( ScriptableValueNode );
  31201. addNodeElement( 'scriptableValue', scriptableValue );
  31202. addNodeClass( 'ScriptableValueNode', ScriptableValueNode );
  31203. class Resources extends Map {
  31204. get( key, callback = null, ...params ) {
  31205. if ( this.has( key ) ) return super.get( key );
  31206. if ( callback !== null ) {
  31207. const value = callback( ...params );
  31208. this.set( key, value );
  31209. return value;
  31210. }
  31211. }
  31212. }
  31213. class Parameters {
  31214. constructor( scriptableNode ) {
  31215. this.scriptableNode = scriptableNode;
  31216. }
  31217. get parameters() {
  31218. return this.scriptableNode.parameters;
  31219. }
  31220. get layout() {
  31221. return this.scriptableNode.getLayout();
  31222. }
  31223. getInputLayout( id ) {
  31224. return this.scriptableNode.getInputLayout( id );
  31225. }
  31226. get( name ) {
  31227. const param = this.parameters[ name ];
  31228. const value = param ? param.getValue() : null;
  31229. return value;
  31230. }
  31231. }
  31232. const global = new Resources();
  31233. class ScriptableNode extends Node {
  31234. constructor( codeNode = null, parameters = {} ) {
  31235. super();
  31236. this.codeNode = codeNode;
  31237. this.parameters = parameters;
  31238. this._local = new Resources();
  31239. this._output = scriptableValue();
  31240. this._outputs = {};
  31241. this._source = this.source;
  31242. this._method = null;
  31243. this._object = null;
  31244. this._value = null;
  31245. this._needsOutputUpdate = true;
  31246. this.onRefresh = this.onRefresh.bind( this );
  31247. this.isScriptableNode = true;
  31248. }
  31249. get source() {
  31250. return this.codeNode ? this.codeNode.code : '';
  31251. }
  31252. setLocal( name, value ) {
  31253. return this._local.set( name, value );
  31254. }
  31255. getLocal( name ) {
  31256. return this._local.get( name );
  31257. }
  31258. onRefresh() {
  31259. this._refresh();
  31260. }
  31261. getInputLayout( id ) {
  31262. for ( const element of this.getLayout() ) {
  31263. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  31264. return element;
  31265. }
  31266. }
  31267. }
  31268. getOutputLayout( id ) {
  31269. for ( const element of this.getLayout() ) {
  31270. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  31271. return element;
  31272. }
  31273. }
  31274. }
  31275. setOutput( name, value ) {
  31276. const outputs = this._outputs;
  31277. if ( outputs[ name ] === undefined ) {
  31278. outputs[ name ] = scriptableValue( value );
  31279. } else {
  31280. outputs[ name ].value = value;
  31281. }
  31282. return this;
  31283. }
  31284. getOutput( name ) {
  31285. return this._outputs[ name ];
  31286. }
  31287. getParameter( name ) {
  31288. return this.parameters[ name ];
  31289. }
  31290. setParameter( name, value ) {
  31291. const parameters = this.parameters;
  31292. if ( value && value.isScriptableNode ) {
  31293. this.deleteParameter( name );
  31294. parameters[ name ] = value;
  31295. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  31296. } else if ( value && value.isScriptableValueNode ) {
  31297. this.deleteParameter( name );
  31298. parameters[ name ] = value;
  31299. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31300. } else if ( parameters[ name ] === undefined ) {
  31301. parameters[ name ] = scriptableValue( value );
  31302. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31303. } else {
  31304. parameters[ name ].value = value;
  31305. }
  31306. return this;
  31307. }
  31308. getValue() {
  31309. return this.getDefaultOutput().getValue();
  31310. }
  31311. deleteParameter( name ) {
  31312. let valueNode = this.parameters[ name ];
  31313. if ( valueNode ) {
  31314. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31315. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  31316. }
  31317. return this;
  31318. }
  31319. clearParameters() {
  31320. for ( const name of Object.keys( this.parameters ) ) {
  31321. this.deleteParameter( name );
  31322. }
  31323. this.needsUpdate = true;
  31324. return this;
  31325. }
  31326. call( name, ...params ) {
  31327. const object = this.getObject();
  31328. const method = object[ name ];
  31329. if ( typeof method === 'function' ) {
  31330. return method( ...params );
  31331. }
  31332. }
  31333. async callAsync( name, ...params ) {
  31334. const object = this.getObject();
  31335. const method = object[ name ];
  31336. if ( typeof method === 'function' ) {
  31337. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  31338. }
  31339. }
  31340. getNodeType( builder ) {
  31341. return this.getDefaultOutputNode().getNodeType( builder );
  31342. }
  31343. refresh( output = null ) {
  31344. if ( output !== null ) {
  31345. this.getOutput( output ).refresh();
  31346. } else {
  31347. this._refresh();
  31348. }
  31349. }
  31350. getObject() {
  31351. if ( this.needsUpdate ) this.dispose();
  31352. if ( this._object !== null ) return this._object;
  31353. //
  31354. const refresh = () => this.refresh();
  31355. const setOutput = ( id, value ) => this.setOutput( id, value );
  31356. const parameters = new Parameters( this );
  31357. const THREE = global.get( 'THREE' );
  31358. const TSL = global.get( 'TSL' );
  31359. const method = this.getMethod( this.codeNode );
  31360. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  31361. this._object = method( ...params );
  31362. const layout = this._object.layout;
  31363. if ( layout ) {
  31364. if ( layout.cache === false ) {
  31365. this._local.clear();
  31366. }
  31367. // default output
  31368. this._output.outputType = layout.outputType || null;
  31369. if ( Array.isArray( layout.elements ) ) {
  31370. for ( const element of layout.elements ) {
  31371. const id = element.id || element.name;
  31372. if ( element.inputType ) {
  31373. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  31374. this.getParameter( id ).inputType = element.inputType;
  31375. }
  31376. if ( element.outputType ) {
  31377. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  31378. this.getOutput( id ).outputType = element.outputType;
  31379. }
  31380. }
  31381. }
  31382. }
  31383. return this._object;
  31384. }
  31385. deserialize( data ) {
  31386. super.deserialize( data );
  31387. for ( const name in this.parameters ) {
  31388. let valueNode = this.parameters[ name ];
  31389. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31390. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  31391. }
  31392. }
  31393. getLayout() {
  31394. return this.getObject().layout;
  31395. }
  31396. getDefaultOutputNode() {
  31397. const output = this.getDefaultOutput().value;
  31398. if ( output && output.isNode ) {
  31399. return output;
  31400. }
  31401. return float();
  31402. }
  31403. getDefaultOutput() {
  31404. return this._exec()._output;
  31405. }
  31406. getMethod() {
  31407. if ( this.needsUpdate ) this.dispose();
  31408. if ( this._method !== null ) return this._method;
  31409. //
  31410. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  31411. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  31412. const properties = interfaceProps.join( ', ' );
  31413. const declarations = 'var ' + properties + '; var output = {};\n';
  31414. const returns = '\nreturn { ...output, ' + properties + ' };';
  31415. const code = declarations + this.codeNode.code + returns;
  31416. //
  31417. this._method = new Function( ...parametersProps, code );
  31418. return this._method;
  31419. }
  31420. dispose() {
  31421. if ( this._method === null ) return;
  31422. if ( this._object && typeof this._object.dispose === 'function' ) {
  31423. this._object.dispose();
  31424. }
  31425. this._method = null;
  31426. this._object = null;
  31427. this._source = null;
  31428. this._value = null;
  31429. this._needsOutputUpdate = true;
  31430. this._output.value = null;
  31431. this._outputs = {};
  31432. }
  31433. setup() {
  31434. return this.getDefaultOutputNode();
  31435. }
  31436. set needsUpdate( value ) {
  31437. if ( value === true ) this.dispose();
  31438. }
  31439. get needsUpdate() {
  31440. return this.source !== this._source;
  31441. }
  31442. _exec() {
  31443. if ( this.codeNode === null ) return this;
  31444. if ( this._needsOutputUpdate === true ) {
  31445. this._value = this.call( 'main' );
  31446. this._needsOutputUpdate = false;
  31447. }
  31448. this._output.value = this._value;
  31449. return this;
  31450. }
  31451. _refresh() {
  31452. this.needsUpdate = true;
  31453. this._exec();
  31454. this._output.refresh();
  31455. }
  31456. }
  31457. const scriptable = nodeProxy( ScriptableNode );
  31458. addNodeElement( 'scriptable', scriptable );
  31459. addNodeClass( 'ScriptableNode', ScriptableNode );
  31460. class FogNode extends Node {
  31461. constructor( colorNode, factorNode ) {
  31462. super( 'float' );
  31463. this.isFogNode = true;
  31464. this.colorNode = colorNode;
  31465. this.factorNode = factorNode;
  31466. }
  31467. getViewZNode( builder ) {
  31468. let viewZ;
  31469. const getViewZ = builder.context.getViewZ;
  31470. if ( getViewZ !== undefined ) {
  31471. viewZ = getViewZ( this );
  31472. }
  31473. return ( viewZ || positionView.z ).negate();
  31474. }
  31475. setup() {
  31476. return this.factorNode;
  31477. }
  31478. }
  31479. const fog = nodeProxy( FogNode );
  31480. addNodeElement( 'fog', fog );
  31481. addNodeClass( 'FogNode', FogNode );
  31482. class FogRangeNode extends FogNode {
  31483. constructor( colorNode, nearNode, farNode ) {
  31484. super( colorNode );
  31485. this.isFogRangeNode = true;
  31486. this.nearNode = nearNode;
  31487. this.farNode = farNode;
  31488. }
  31489. setup( builder ) {
  31490. const viewZ = this.getViewZNode( builder );
  31491. return smoothstep( this.nearNode, this.farNode, viewZ );
  31492. }
  31493. }
  31494. const rangeFog = nodeProxy( FogRangeNode );
  31495. addNodeElement( 'rangeFog', rangeFog );
  31496. addNodeClass( 'FogRangeNode', FogRangeNode );
  31497. class FogExp2Node extends FogNode {
  31498. constructor( colorNode, densityNode ) {
  31499. super( colorNode );
  31500. this.isFogExp2Node = true;
  31501. this.densityNode = densityNode;
  31502. }
  31503. setup( builder ) {
  31504. const viewZ = this.getViewZNode( builder );
  31505. const density = this.densityNode;
  31506. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  31507. }
  31508. }
  31509. const densityFog = nodeProxy( FogExp2Node );
  31510. addNodeElement( 'densityFog', densityFog );
  31511. addNodeClass( 'FogExp2Node', FogExp2Node );
  31512. let min = null;
  31513. let max = null;
  31514. class RangeNode extends Node {
  31515. constructor( minNode = float(), maxNode = float() ) {
  31516. super();
  31517. this.minNode = minNode;
  31518. this.maxNode = maxNode;
  31519. }
  31520. getVectorLength( builder ) {
  31521. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  31522. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  31523. return minLength > maxLength ? minLength : maxLength;
  31524. }
  31525. getNodeType( builder ) {
  31526. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  31527. }
  31528. setup( builder ) {
  31529. const object = builder.object;
  31530. let output = null;
  31531. if ( object.count > 1 ) {
  31532. const minValue = this.minNode.value;
  31533. const maxValue = this.maxNode.value;
  31534. const minLength = builder.getTypeLength( getValueType( minValue ) );
  31535. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  31536. min = min || new Vector4();
  31537. max = max || new Vector4();
  31538. min.setScalar( 0 );
  31539. max.setScalar( 0 );
  31540. if ( minLength === 1 ) min.setScalar( minValue );
  31541. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  31542. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  31543. if ( maxLength === 1 ) max.setScalar( maxValue );
  31544. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  31545. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  31546. const stride = 4;
  31547. const length = stride * object.count;
  31548. const array = new Float32Array( length );
  31549. for ( let i = 0; i < length; i ++ ) {
  31550. const index = i % stride;
  31551. const minElementValue = min.getComponent( index );
  31552. const maxElementValue = max.getComponent( index );
  31553. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  31554. }
  31555. const nodeType = this.getNodeType( builder );
  31556. if ( object.count <= 4096 ) {
  31557. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  31558. } else {
  31559. // TODO: Improve anonymous buffer attribute creation removing this part
  31560. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  31561. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  31562. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  31563. }
  31564. } else {
  31565. output = float( 0 );
  31566. }
  31567. return output;
  31568. }
  31569. }
  31570. const range = nodeProxy( RangeNode );
  31571. addNodeClass( 'RangeNode', RangeNode );
  31572. class ComputeNode extends Node {
  31573. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  31574. super( 'void' );
  31575. this.isComputeNode = true;
  31576. this.computeNode = computeNode;
  31577. this.count = count;
  31578. this.workgroupSize = workgroupSize;
  31579. this.dispatchCount = 0;
  31580. this.version = 1;
  31581. this.updateBeforeType = NodeUpdateType.OBJECT;
  31582. this.updateDispatchCount();
  31583. }
  31584. dispose() {
  31585. this.dispatchEvent( { type: 'dispose' } );
  31586. }
  31587. set needsUpdate( value ) {
  31588. if ( value === true ) this.version ++;
  31589. }
  31590. updateDispatchCount() {
  31591. const { count, workgroupSize } = this;
  31592. let size = workgroupSize[ 0 ];
  31593. for ( let i = 1; i < workgroupSize.length; i ++ )
  31594. size *= workgroupSize[ i ];
  31595. this.dispatchCount = Math.ceil( count / size );
  31596. }
  31597. onInit() { }
  31598. updateBefore( { renderer } ) {
  31599. renderer.compute( this );
  31600. }
  31601. generate( builder ) {
  31602. const { shaderStage } = builder;
  31603. if ( shaderStage === 'compute' ) {
  31604. const snippet = this.computeNode.build( builder, 'void' );
  31605. if ( snippet !== '' ) {
  31606. builder.addLineFlowCode( snippet );
  31607. }
  31608. }
  31609. }
  31610. }
  31611. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  31612. addNodeElement( 'compute', compute );
  31613. addNodeClass( 'ComputeNode', ComputeNode );
  31614. class LightNode extends Node {
  31615. constructor( scope = LightNode.TARGET_DIRECTION, light = null ) {
  31616. super();
  31617. this.scope = scope;
  31618. this.light = light;
  31619. }
  31620. setup() {
  31621. const { scope, light } = this;
  31622. let output = null;
  31623. if ( scope === LightNode.TARGET_DIRECTION ) {
  31624. output = cameraViewMatrix.transformDirection( objectPosition( light ).sub( objectPosition( light.target ) ) );
  31625. }
  31626. return output;
  31627. }
  31628. serialize( data ) {
  31629. super.serialize( data );
  31630. data.scope = this.scope;
  31631. }
  31632. deserialize( data ) {
  31633. super.deserialize( data );
  31634. this.scope = data.scope;
  31635. }
  31636. }
  31637. LightNode.TARGET_DIRECTION = 'targetDirection';
  31638. const lightTargetDirection = nodeProxy( LightNode, LightNode.TARGET_DIRECTION );
  31639. addNodeClass( 'LightNode', LightNode );
  31640. const getDistanceAttenuation = tslFn( ( inputs ) => {
  31641. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  31642. // based upon Frostbite 3 Moving to Physically-based Rendering
  31643. // page 32, equation 26: E[window1]
  31644. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31645. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31646. return cutoffDistance.greaterThan( 0 ).cond(
  31647. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31648. distanceFalloff
  31649. );
  31650. } ); // validated
  31651. class PointLightNode extends AnalyticLightNode {
  31652. constructor( light = null ) {
  31653. super( light );
  31654. this.cutoffDistanceNode = uniform( 0 );
  31655. this.decayExponentNode = uniform( 0 );
  31656. }
  31657. update( frame ) {
  31658. const { light } = this;
  31659. super.update( frame );
  31660. this.cutoffDistanceNode.value = light.distance;
  31661. this.decayExponentNode.value = light.decay;
  31662. }
  31663. setup( builder ) {
  31664. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31665. const lightingModel = builder.context.lightingModel;
  31666. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31667. const lightDirection = lVector.normalize();
  31668. const lightDistance = lVector.length();
  31669. const lightAttenuation = getDistanceAttenuation( {
  31670. lightDistance,
  31671. cutoffDistance: cutoffDistanceNode,
  31672. decayExponent: decayExponentNode
  31673. } );
  31674. const lightColor = colorNode.mul( lightAttenuation );
  31675. const reflectedLight = builder.context.reflectedLight;
  31676. lightingModel.direct( {
  31677. lightDirection,
  31678. lightColor,
  31679. reflectedLight,
  31680. shadowMask: this.shadowMaskNode
  31681. }, builder.stack, builder );
  31682. }
  31683. }
  31684. addNodeClass( 'PointLightNode', PointLightNode );
  31685. addLightNode( PointLight, PointLightNode );
  31686. class DirectionalLightNode extends AnalyticLightNode {
  31687. constructor( light = null ) {
  31688. super( light );
  31689. }
  31690. setup( builder ) {
  31691. super.setup( builder );
  31692. const lightingModel = builder.context.lightingModel;
  31693. const lightColor = this.colorNode;
  31694. const lightDirection = lightTargetDirection( this.light );
  31695. const reflectedLight = builder.context.reflectedLight;
  31696. lightingModel.direct( {
  31697. lightDirection,
  31698. lightColor,
  31699. reflectedLight,
  31700. shadowMask: this.shadowMaskNode
  31701. }, builder.stack, builder );
  31702. }
  31703. }
  31704. addNodeClass( 'DirectionalLightNode', DirectionalLightNode );
  31705. addLightNode( DirectionalLight, DirectionalLightNode );
  31706. const _matrix41 = new Matrix4();
  31707. const _matrix42 = new Matrix4();
  31708. let ltcLib = null;
  31709. class RectAreaLightNode extends AnalyticLightNode {
  31710. constructor( light = null ) {
  31711. super( light );
  31712. this.halfHeight = uniform( new Vector3() );
  31713. this.halfWidth = uniform( new Vector3() );
  31714. }
  31715. update( frame ) {
  31716. super.update( frame );
  31717. const { light } = this;
  31718. const viewMatrix = frame.camera.matrixWorldInverse;
  31719. _matrix42.identity();
  31720. _matrix41.copy( light.matrixWorld );
  31721. _matrix41.premultiply( viewMatrix );
  31722. _matrix42.extractRotation( _matrix41 );
  31723. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31724. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31725. this.halfWidth.value.applyMatrix4( _matrix42 );
  31726. this.halfHeight.value.applyMatrix4( _matrix42 );
  31727. }
  31728. setup( builder ) {
  31729. super.setup( builder );
  31730. let ltc_1, ltc_2;
  31731. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31732. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  31733. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  31734. } else {
  31735. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  31736. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  31737. }
  31738. const { colorNode, light } = this;
  31739. const lightingModel = builder.context.lightingModel;
  31740. const lightPosition = objectViewPosition( light );
  31741. const reflectedLight = builder.context.reflectedLight;
  31742. lightingModel.directRectArea( {
  31743. lightColor: colorNode,
  31744. lightPosition,
  31745. halfWidth: this.halfWidth,
  31746. halfHeight: this.halfHeight,
  31747. reflectedLight,
  31748. ltc_1,
  31749. ltc_2
  31750. }, builder.stack, builder );
  31751. }
  31752. static setLTC( ltc ) {
  31753. ltcLib = ltc;
  31754. }
  31755. }
  31756. addNodeClass( 'RectAreaLightNode', RectAreaLightNode );
  31757. addLightNode( RectAreaLight, RectAreaLightNode );
  31758. class SpotLightNode extends AnalyticLightNode {
  31759. constructor( light = null ) {
  31760. super( light );
  31761. this.coneCosNode = uniform( 0 );
  31762. this.penumbraCosNode = uniform( 0 );
  31763. this.cutoffDistanceNode = uniform( 0 );
  31764. this.decayExponentNode = uniform( 0 );
  31765. }
  31766. update( frame ) {
  31767. super.update( frame );
  31768. const { light } = this;
  31769. this.coneCosNode.value = Math.cos( light.angle );
  31770. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31771. this.cutoffDistanceNode.value = light.distance;
  31772. this.decayExponentNode.value = light.decay;
  31773. }
  31774. getSpotAttenuation( angleCosine ) {
  31775. const { coneCosNode, penumbraCosNode } = this;
  31776. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31777. }
  31778. setup( builder ) {
  31779. super.setup( builder );
  31780. const lightingModel = builder.context.lightingModel;
  31781. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31782. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31783. const lightDirection = lVector.normalize();
  31784. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31785. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31786. const lightDistance = lVector.length();
  31787. const lightAttenuation = getDistanceAttenuation( {
  31788. lightDistance,
  31789. cutoffDistance: cutoffDistanceNode,
  31790. decayExponent: decayExponentNode
  31791. } );
  31792. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31793. const reflectedLight = builder.context.reflectedLight;
  31794. lightingModel.direct( {
  31795. lightDirection,
  31796. lightColor,
  31797. reflectedLight,
  31798. shadowMask: this.shadowMaskNode
  31799. }, builder.stack, builder );
  31800. }
  31801. }
  31802. addNodeClass( 'SpotLightNode', SpotLightNode );
  31803. addLightNode( SpotLight, SpotLightNode );
  31804. class IESSpotLight extends SpotLight {
  31805. constructor( color, intensity, distance, angle, penumbra, decay ) {
  31806. super( color, intensity, distance, angle, penumbra, decay );
  31807. this.iesMap = null;
  31808. }
  31809. copy( source, recursive ) {
  31810. super.copy( source, recursive );
  31811. this.iesMap = source.iesMap;
  31812. return this;
  31813. }
  31814. }
  31815. class IESSpotLightNode extends SpotLightNode {
  31816. getSpotAttenuation( angleCosine ) {
  31817. const iesMap = this.light.iesMap;
  31818. let spotAttenuation = null;
  31819. if ( iesMap && iesMap.isTexture === true ) {
  31820. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31821. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31822. } else {
  31823. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31824. }
  31825. return spotAttenuation;
  31826. }
  31827. }
  31828. addNodeClass( 'IESSpotLightNode', IESSpotLightNode );
  31829. addLightNode( IESSpotLight, IESSpotLightNode );
  31830. class AmbientLightNode extends AnalyticLightNode {
  31831. constructor( light = null ) {
  31832. super( light );
  31833. }
  31834. setup( { context } ) {
  31835. context.irradiance.addAssign( this.colorNode );
  31836. }
  31837. }
  31838. addNodeClass( 'AmbientLightNode', AmbientLightNode );
  31839. addLightNode( AmbientLight, AmbientLightNode );
  31840. class HemisphereLightNode extends AnalyticLightNode {
  31841. constructor( light = null ) {
  31842. super( light );
  31843. this.lightPositionNode = objectPosition( light );
  31844. this.lightDirectionNode = this.lightPositionNode.normalize();
  31845. this.groundColorNode = uniform( new Color() );
  31846. }
  31847. update( frame ) {
  31848. const { light } = this;
  31849. super.update( frame );
  31850. this.lightPositionNode.object3d = light;
  31851. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31852. }
  31853. setup( builder ) {
  31854. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31855. const dotNL = normalView.dot( lightDirectionNode );
  31856. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31857. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31858. builder.context.irradiance.addAssign( irradiance );
  31859. }
  31860. }
  31861. addNodeClass( 'HemisphereLightNode', HemisphereLightNode );
  31862. addLightNode( HemisphereLight, HemisphereLightNode );
  31863. const checkerShaderNode = tslFn( ( inputs ) => {
  31864. const uv = inputs.uv.mul( 2.0 );
  31865. const cx = uv.x.floor();
  31866. const cy = uv.y.floor();
  31867. const result = cx.add( cy ).mod( 2.0 );
  31868. return result.sign();
  31869. } );
  31870. class CheckerNode extends TempNode {
  31871. constructor( uvNode = uv() ) {
  31872. super( 'float' );
  31873. this.uvNode = uvNode;
  31874. }
  31875. setup() {
  31876. return checkerShaderNode( { uv: this.uvNode } );
  31877. }
  31878. }
  31879. const checker = nodeProxy( CheckerNode );
  31880. addNodeElement( 'checker', checker );
  31881. addNodeClass( 'CheckerNode', CheckerNode );
  31882. class NodeLoader extends Loader {
  31883. constructor( manager ) {
  31884. super( manager );
  31885. this.textures = {};
  31886. }
  31887. load( url, onLoad, onProgress, onError ) {
  31888. const loader = new FileLoader( this.manager );
  31889. loader.setPath( this.path );
  31890. loader.setRequestHeader( this.requestHeader );
  31891. loader.setWithCredentials( this.withCredentials );
  31892. loader.load( url, ( text ) => {
  31893. try {
  31894. onLoad( this.parse( JSON.parse( text ) ) );
  31895. } catch ( e ) {
  31896. if ( onError ) {
  31897. onError( e );
  31898. } else {
  31899. console.error( e );
  31900. }
  31901. this.manager.itemError( url );
  31902. }
  31903. }, onProgress, onError );
  31904. }
  31905. parseNodes( json ) {
  31906. const nodes = {};
  31907. if ( json !== undefined ) {
  31908. for ( const nodeJSON of json ) {
  31909. const { uuid, type } = nodeJSON;
  31910. nodes[ uuid ] = nodeObject( createNodeFromType( type ) ); // @TODO: Maybe nodeObjectify the node in createNodeFromType?
  31911. nodes[ uuid ].uuid = uuid;
  31912. }
  31913. const meta = { nodes, textures: this.textures };
  31914. for ( const nodeJSON of json ) {
  31915. nodeJSON.meta = meta;
  31916. const node = nodes[ nodeJSON.uuid ];
  31917. node.deserialize( nodeJSON );
  31918. delete nodeJSON.meta;
  31919. }
  31920. }
  31921. return nodes;
  31922. }
  31923. parse( json ) {
  31924. const node = nodeObject( createNodeFromType( json.type ) );
  31925. node.uuid = json.uuid;
  31926. const nodes = this.parseNodes( json.nodes );
  31927. const meta = { nodes, textures: this.textures };
  31928. json.meta = meta;
  31929. node.deserialize( json );
  31930. delete json.meta;
  31931. return node;
  31932. }
  31933. setTextures( value ) {
  31934. this.textures = value;
  31935. return this;
  31936. }
  31937. }
  31938. const defaultValues$e = new PointsMaterial();
  31939. class InstancedPointsNodeMaterial extends NodeMaterial {
  31940. constructor( params = {} ) {
  31941. super();
  31942. this.normals = false;
  31943. this.lights = false;
  31944. this.useAlphaToCoverage = true;
  31945. this.useColor = params.vertexColors;
  31946. this.pointWidth = 1;
  31947. this.pointColorNode = null;
  31948. this.setDefaultValues( defaultValues$e );
  31949. this.setupShaders();
  31950. this.setValues( params );
  31951. }
  31952. setupShaders() {
  31953. const useAlphaToCoverage = this.alphaToCoverage;
  31954. const useColor = this.useColor;
  31955. this.vertexNode = tslFn( () => {
  31956. //vUv = uv;
  31957. varying( vec2(), 'vUv' ).assign( uv() ); // @TODO: Analyze other way to do this
  31958. const instancePosition = attribute( 'instancePosition' );
  31959. // camera space
  31960. const mvPos = property( 'vec4', 'mvPos' );
  31961. mvPos.assign( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  31962. const aspect = viewport.z.div( viewport.w );
  31963. // clip space
  31964. const clipPos = cameraProjectionMatrix.mul( mvPos );
  31965. // offset in ndc space
  31966. const offset = property( 'vec2', 'offset' );
  31967. offset.assign( positionGeometry.xy );
  31968. offset.assign( offset.mul( materialPointWidth ) );
  31969. offset.assign( offset.div( viewport.z ) );
  31970. offset.y.assign( offset.y.mul( aspect ) );
  31971. // back to clip space
  31972. offset.assign( offset.mul( clipPos.w ) );
  31973. //clipPos.xy += offset;
  31974. clipPos.assign( clipPos.add( vec4( offset, 0, 0 ) ) );
  31975. return clipPos;
  31976. //vec4 mvPosition = mvPos; // this was used for somethihng...
  31977. } )();
  31978. this.fragmentNode = tslFn( () => {
  31979. const vUv = varying( vec2(), 'vUv' );
  31980. // force assignment into correct place in flow
  31981. const alpha = property( 'float', 'alpha' );
  31982. alpha.assign( 1 );
  31983. const a = vUv.x;
  31984. const b = vUv.y;
  31985. const len2 = a.mul( a ).add( b.mul( b ) );
  31986. if ( useAlphaToCoverage ) {
  31987. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  31988. const dlen = property( 'float', 'dlen' );
  31989. dlen.assign( len2.fwidth() );
  31990. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  31991. } else {
  31992. len2.greaterThan( 1.0 ).discard();
  31993. }
  31994. let pointColorNode;
  31995. if ( this.pointColorNode ) {
  31996. pointColorNode = this.pointColorNode;
  31997. } else {
  31998. if ( useColor ) {
  31999. const instanceColor = attribute( 'instanceColor' );
  32000. pointColorNode = instanceColor.mul( materialColor );
  32001. } else {
  32002. pointColorNode = materialColor;
  32003. }
  32004. }
  32005. return vec4( pointColorNode, alpha );
  32006. } )();
  32007. this.needsUpdate = true;
  32008. }
  32009. get alphaToCoverage() {
  32010. return this.useAlphaToCoverage;
  32011. }
  32012. set alphaToCoverage( value ) {
  32013. if ( this.useAlphaToCoverage !== value ) {
  32014. this.useAlphaToCoverage = value;
  32015. this.setupShaders();
  32016. }
  32017. }
  32018. }
  32019. addNodeMaterial( 'InstancedPointsNodeMaterial', InstancedPointsNodeMaterial );
  32020. const defaultValues$d = new LineBasicMaterial();
  32021. class LineBasicNodeMaterial extends NodeMaterial {
  32022. constructor( parameters ) {
  32023. super();
  32024. this.isLineBasicNodeMaterial = true;
  32025. this.lights = false;
  32026. this.normals = false;
  32027. this.setDefaultValues( defaultValues$d );
  32028. this.setValues( parameters );
  32029. }
  32030. }
  32031. addNodeMaterial( 'LineBasicNodeMaterial', LineBasicNodeMaterial );
  32032. const defaultValues$c = new LineDashedMaterial();
  32033. class LineDashedNodeMaterial extends NodeMaterial {
  32034. constructor( parameters ) {
  32035. super();
  32036. this.isLineDashedNodeMaterial = true;
  32037. this.lights = false;
  32038. this.normals = false;
  32039. this.setDefaultValues( defaultValues$c );
  32040. this.offsetNode = null;
  32041. this.dashScaleNode = null;
  32042. this.dashSizeNode = null;
  32043. this.gapSizeNode = null;
  32044. this.setValues( parameters );
  32045. }
  32046. setupVariants() {
  32047. const offsetNode = this.offsetNode;
  32048. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  32049. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  32050. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  32051. dashSize.assign( dashSizeNode );
  32052. gapSize.assign( gapSizeNode );
  32053. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  32054. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  32055. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  32056. }
  32057. }
  32058. addNodeMaterial( 'LineDashedNodeMaterial', LineDashedNodeMaterial );
  32059. const defaultValues$b = new LineDashedMaterial();
  32060. class Line2NodeMaterial extends NodeMaterial {
  32061. constructor( params = {} ) {
  32062. super();
  32063. this.normals = false;
  32064. this.lights = false;
  32065. this.setDefaultValues( defaultValues$b );
  32066. this.useAlphaToCoverage = true;
  32067. this.useColor = params.vertexColors;
  32068. this.useDash = params.dashed;
  32069. this.useWorldUnits = false;
  32070. this.dashOffset = 0;
  32071. this.lineWidth = 1;
  32072. this.lineColorNode = null;
  32073. this.offsetNode = null;
  32074. this.dashScaleNode = null;
  32075. this.dashSizeNode = null;
  32076. this.gapSizeNode = null;
  32077. this.setValues( params );
  32078. }
  32079. setup( builder ) {
  32080. this.setupShaders();
  32081. super.setup( builder );
  32082. }
  32083. setupShaders() {
  32084. const useAlphaToCoverage = this.alphaToCoverage;
  32085. const useColor = this.useColor;
  32086. const useDash = this.dashed;
  32087. const useWorldUnits = this.worldUnits;
  32088. const trimSegment = tslFn( ( { start, end } ) => {
  32089. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  32090. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  32091. const nearEstimate = b.mul( - 0.5 ).div( a );
  32092. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  32093. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  32094. } );
  32095. this.vertexNode = tslFn( () => {
  32096. varyingProperty( 'vec2', 'vUv' ).assign( uv() );
  32097. const instanceStart = attribute( 'instanceStart' );
  32098. const instanceEnd = attribute( 'instanceEnd' );
  32099. // camera space
  32100. const start = property( 'vec4', 'start' );
  32101. const end = property( 'vec4', 'end' );
  32102. start.assign( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ); // force assignment into correct place in flow
  32103. end.assign( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) );
  32104. if ( useWorldUnits ) {
  32105. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  32106. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  32107. }
  32108. const aspect = viewport.z.div( viewport.w );
  32109. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  32110. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  32111. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  32112. // perhaps there is a more elegant solution -- WestLangley
  32113. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  32114. If( perspective, () => {
  32115. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  32116. end.assign( trimSegment( { start: start, end: end } ) );
  32117. } ).elseif( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  32118. start.assign( trimSegment( { start: end, end: start } ) );
  32119. } );
  32120. } );
  32121. // clip space
  32122. const clipStart = cameraProjectionMatrix.mul( start );
  32123. const clipEnd = cameraProjectionMatrix.mul( end );
  32124. // ndc space
  32125. const ndcStart = clipStart.xyz.div( clipStart.w );
  32126. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  32127. // direction
  32128. const dir = ndcEnd.xy.sub( ndcStart.xy ).temp();
  32129. // account for clip-space aspect ratio
  32130. dir.x.assign( dir.x.mul( aspect ) );
  32131. dir.assign( dir.normalize() );
  32132. const clip = temp( vec4() );
  32133. if ( useWorldUnits ) {
  32134. // get the offset direction as perpendicular to the view vector
  32135. const worldDir = end.xyz.sub( start.xyz ).normalize();
  32136. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  32137. const worldUp = worldDir.cross( tmpFwd ).normalize();
  32138. const worldFwd = worldDir.cross( worldUp );
  32139. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  32140. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).cond( start, end ) );
  32141. // height offset
  32142. const hw = materialLineWidth.mul( 0.5 );
  32143. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).cond( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  32144. // don't extend the line if we're rendering dashes because we
  32145. // won't be rendering the endcaps
  32146. if ( ! useDash ) {
  32147. // cap extension
  32148. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).cond( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  32149. // add width to the box
  32150. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  32151. // endcaps
  32152. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  32153. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  32154. } );
  32155. }
  32156. // project the worldpos
  32157. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  32158. // shift the depth of the projected points so the line
  32159. // segments overlap neatly
  32160. const clipPose = temp( vec3() );
  32161. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).cond( ndcStart, ndcEnd ) );
  32162. clip.z.assign( clipPose.z.mul( clip.w ) );
  32163. } else {
  32164. const offset = property( 'vec2', 'offset' );
  32165. offset.assign( vec2( dir.y, dir.x.negate() ) );
  32166. // undo aspect ratio adjustment
  32167. dir.x.assign( dir.x.div( aspect ) );
  32168. offset.x.assign( offset.x.div( aspect ) );
  32169. // sign flip
  32170. offset.assign( positionGeometry.x.lessThan( 0.0 ).cond( offset.negate(), offset ) );
  32171. // endcaps
  32172. If( positionGeometry.y.lessThan( 0.0 ), () => {
  32173. offset.assign( offset.sub( dir ) );
  32174. } ).elseif( positionGeometry.y.greaterThan( 1.0 ), () => {
  32175. offset.assign( offset.add( dir ) );
  32176. } );
  32177. // adjust for linewidth
  32178. offset.assign( offset.mul( materialLineWidth ) );
  32179. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  32180. offset.assign( offset.div( viewport.w ) );
  32181. // select end
  32182. clip.assign( positionGeometry.y.lessThan( 0.5 ).cond( clipStart, clipEnd ) );
  32183. // back to clip space
  32184. offset.assign( offset.mul( clip.w ) );
  32185. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  32186. }
  32187. return clip;
  32188. } )();
  32189. const closestLineToLine = tslFn( ( { p1, p2, p3, p4 } ) => {
  32190. const p13 = p1.sub( p3 );
  32191. const p43 = p4.sub( p3 );
  32192. const p21 = p2.sub( p1 );
  32193. const d1343 = p13.dot( p43 );
  32194. const d4321 = p43.dot( p21 );
  32195. const d1321 = p13.dot( p21 );
  32196. const d4343 = p43.dot( p43 );
  32197. const d2121 = p21.dot( p21 );
  32198. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  32199. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  32200. const mua = numer.div( denom ).clamp();
  32201. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  32202. return vec2( mua, mub );
  32203. } );
  32204. this.fragmentNode = tslFn( () => {
  32205. const vUv = varyingProperty( 'vec2', 'vUv' );
  32206. if ( useDash ) {
  32207. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  32208. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  32209. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  32210. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  32211. dashSize.assign( dashSizeNode );
  32212. gapSize.assign( gapSizeNode );
  32213. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  32214. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  32215. const lineDistance = positionGeometry.y.lessThan( 0.5 ).cond( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  32216. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  32217. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  32218. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  32219. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  32220. }
  32221. // force assignment into correct place in flow
  32222. const alpha = property( 'float', 'alpha' );
  32223. alpha.assign( 1 );
  32224. if ( useWorldUnits ) {
  32225. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  32226. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  32227. // Find the closest points on the view ray and the line segment
  32228. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  32229. const lineDir = worldEnd.sub( worldStart );
  32230. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  32231. const p1 = worldStart.add( lineDir.mul( params.x ) );
  32232. const p2 = rayEnd.mul( params.y );
  32233. const delta = p1.sub( p2 );
  32234. const len = delta.length();
  32235. const norm = len.div( materialLineWidth );
  32236. if ( ! useDash ) {
  32237. if ( useAlphaToCoverage ) {
  32238. const dnorm = norm.fwidth();
  32239. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  32240. } else {
  32241. norm.greaterThan( 0.5 ).discard();
  32242. }
  32243. }
  32244. } else {
  32245. // round endcaps
  32246. if ( useAlphaToCoverage ) {
  32247. const a = vUv.x;
  32248. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32249. const len2 = a.mul( a ).add( b.mul( b ) );
  32250. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  32251. const dlen = property( 'float', 'dlen' );
  32252. dlen.assign( len2.fwidth() );
  32253. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32254. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  32255. } );
  32256. } else {
  32257. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32258. const a = vUv.x;
  32259. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32260. const len2 = a.mul( a ).add( b.mul( b ) );
  32261. len2.greaterThan( 1.0 ).discard();
  32262. } );
  32263. }
  32264. }
  32265. let lineColorNode;
  32266. if ( this.lineColorNode ) {
  32267. lineColorNode = this.lineColorNode;
  32268. } else {
  32269. if ( useColor ) {
  32270. const instanceColorStart = attribute( 'instanceColorStart' );
  32271. const instanceColorEnd = attribute( 'instanceColorEnd' );
  32272. const instanceColor = positionGeometry.y.lessThan( 0.5 ).cond( instanceColorStart, instanceColorEnd );
  32273. lineColorNode = instanceColor.mul( materialColor );
  32274. } else {
  32275. lineColorNode = materialColor;
  32276. }
  32277. }
  32278. return vec4( lineColorNode, alpha );
  32279. } )();
  32280. }
  32281. get worldUnits() {
  32282. return this.useWorldUnits;
  32283. }
  32284. set worldUnits( value ) {
  32285. if ( this.useWorldUnits !== value ) {
  32286. this.useWorldUnits = value;
  32287. this.needsUpdate = true;
  32288. }
  32289. }
  32290. get dashed() {
  32291. return this.useDash;
  32292. }
  32293. set dashed( value ) {
  32294. if ( this.useDash !== value ) {
  32295. this.useDash = value;
  32296. this.needsUpdate = true;
  32297. }
  32298. }
  32299. get alphaToCoverage() {
  32300. return this.useAlphaToCoverage;
  32301. }
  32302. set alphaToCoverage( value ) {
  32303. if ( this.useAlphaToCoverage !== value ) {
  32304. this.useAlphaToCoverage = value;
  32305. this.needsUpdate = true;
  32306. }
  32307. }
  32308. }
  32309. addNodeMaterial( 'Line2NodeMaterial', Line2NodeMaterial );
  32310. const defaultValues$a = new MeshNormalMaterial();
  32311. class MeshNormalNodeMaterial extends NodeMaterial {
  32312. constructor( parameters ) {
  32313. super();
  32314. this.lights = false;
  32315. this.isMeshNormalNodeMaterial = true;
  32316. this.setDefaultValues( defaultValues$a );
  32317. this.setValues( parameters );
  32318. }
  32319. setupDiffuseColor() {
  32320. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  32321. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  32322. }
  32323. }
  32324. addNodeMaterial( 'MeshNormalNodeMaterial', MeshNormalNodeMaterial );
  32325. const defaultValues$9 = new MeshBasicMaterial();
  32326. class MeshBasicNodeMaterial extends NodeMaterial {
  32327. constructor( parameters ) {
  32328. super();
  32329. this.isMeshBasicNodeMaterial = true;
  32330. this.lights = false;
  32331. //this.normals = false; @TODO: normals usage by context
  32332. this.setDefaultValues( defaultValues$9 );
  32333. this.setValues( parameters );
  32334. }
  32335. }
  32336. addNodeMaterial( 'MeshBasicNodeMaterial', MeshBasicNodeMaterial );
  32337. const F_Schlick = tslFn( ( { f0, f90, dotVH } ) => {
  32338. // Original approximation by Christophe Schlick '94
  32339. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  32340. // Optimized variant (presented by Epic at SIGGRAPH '13)
  32341. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  32342. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  32343. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  32344. } ); // validated
  32345. const BRDF_Lambert = tslFn( ( inputs ) => {
  32346. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  32347. } ); // validated
  32348. const G_BlinnPhong_Implicit = () => float( 0.25 );
  32349. const D_BlinnPhong = tslFn( ( { dotNH } ) => {
  32350. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  32351. } );
  32352. const BRDF_BlinnPhong = tslFn( ( { lightDirection } ) => {
  32353. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32354. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32355. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32356. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  32357. const G = G_BlinnPhong_Implicit();
  32358. const D = D_BlinnPhong( { dotNH } );
  32359. return F.mul( G ).mul( D );
  32360. } );
  32361. class PhongLightingModel extends LightingModel {
  32362. constructor( specular = true ) {
  32363. super();
  32364. this.specular = specular;
  32365. }
  32366. direct( { lightDirection, lightColor, reflectedLight } ) {
  32367. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32368. const irradiance = dotNL.mul( lightColor );
  32369. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  32370. if ( this.specular === true ) {
  32371. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  32372. }
  32373. }
  32374. indirectDiffuse( { irradiance, reflectedLight } ) {
  32375. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  32376. }
  32377. }
  32378. const defaultValues$8 = new MeshLambertMaterial();
  32379. class MeshLambertNodeMaterial extends NodeMaterial {
  32380. constructor( parameters ) {
  32381. super();
  32382. this.isMeshLambertNodeMaterial = true;
  32383. this.lights = true;
  32384. this.setDefaultValues( defaultValues$8 );
  32385. this.setValues( parameters );
  32386. }
  32387. setupLightingModel( /*builder*/ ) {
  32388. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  32389. }
  32390. }
  32391. addNodeMaterial( 'MeshLambertNodeMaterial', MeshLambertNodeMaterial );
  32392. const defaultValues$7 = new MeshPhongMaterial();
  32393. class MeshPhongNodeMaterial extends NodeMaterial {
  32394. constructor( parameters ) {
  32395. super();
  32396. this.isMeshPhongNodeMaterial = true;
  32397. this.lights = true;
  32398. this.shininessNode = null;
  32399. this.specularNode = null;
  32400. this.setDefaultValues( defaultValues$7 );
  32401. this.setValues( parameters );
  32402. }
  32403. setupLightingModel( /*builder*/ ) {
  32404. return new PhongLightingModel();
  32405. }
  32406. setupVariants() {
  32407. // SHININESS
  32408. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  32409. shininess.assign( shininessNode );
  32410. // SPECULAR COLOR
  32411. const specularNode = this.specularNode || materialSpecular;
  32412. specularColor.assign( specularNode );
  32413. }
  32414. copy( source ) {
  32415. this.shininessNode = source.shininessNode;
  32416. this.specularNode = source.specularNode;
  32417. return super.copy( source );
  32418. }
  32419. }
  32420. addNodeMaterial( 'MeshPhongNodeMaterial', MeshPhongNodeMaterial );
  32421. const getGeometryRoughness = tslFn( () => {
  32422. const dxy = normalGeometry.dFdx().abs().max( normalGeometry.dFdy().abs() );
  32423. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  32424. return geometryRoughness;
  32425. } );
  32426. const getRoughness = tslFn( ( inputs ) => {
  32427. const { roughness } = inputs;
  32428. const geometryRoughness = getGeometryRoughness();
  32429. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  32430. roughnessFactor = roughnessFactor.add( geometryRoughness );
  32431. roughnessFactor = roughnessFactor.min( 1.0 );
  32432. return roughnessFactor;
  32433. } );
  32434. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  32435. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32436. const V_GGX_SmithCorrelated = tslFn( ( { alpha, dotNL, dotNV } ) => {
  32437. const a2 = alpha.pow2();
  32438. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  32439. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  32440. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  32441. } ).setLayout( {
  32442. name: 'V_GGX_SmithCorrelated',
  32443. type: 'float',
  32444. inputs: [
  32445. { name: 'alpha', type: 'float' },
  32446. { name: 'dotNL', type: 'float' },
  32447. { name: 'dotNV', type: 'float' }
  32448. ]
  32449. } ); // validated
  32450. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32451. const V_GGX_SmithCorrelated_Anisotropic = tslFn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  32452. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  32453. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  32454. const v = div( 0.5, gv.add( gl ) );
  32455. return v.saturate();
  32456. } ).setLayout( {
  32457. name: 'V_GGX_SmithCorrelated_Anisotropic',
  32458. type: 'float',
  32459. inputs: [
  32460. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32461. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32462. { name: 'dotTV', type: 'float', qualifier: 'in' },
  32463. { name: 'dotBV', type: 'float', qualifier: 'in' },
  32464. { name: 'dotTL', type: 'float', qualifier: 'in' },
  32465. { name: 'dotBL', type: 'float', qualifier: 'in' },
  32466. { name: 'dotNV', type: 'float', qualifier: 'in' },
  32467. { name: 'dotNL', type: 'float', qualifier: 'in' }
  32468. ]
  32469. } );
  32470. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  32471. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  32472. // alpha is "roughness squared" in Disney’s reparameterization
  32473. const D_GGX = tslFn( ( { alpha, dotNH } ) => {
  32474. const a2 = alpha.pow2();
  32475. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  32476. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  32477. } ).setLayout( {
  32478. name: 'D_GGX',
  32479. type: 'float',
  32480. inputs: [
  32481. { name: 'alpha', type: 'float' },
  32482. { name: 'dotNH', type: 'float' }
  32483. ]
  32484. } ); // validated
  32485. const RECIPROCAL_PI = float( 1 / Math.PI );
  32486. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32487. const D_GGX_Anisotropic = tslFn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  32488. const a2 = alphaT.mul( alphaB );
  32489. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  32490. const v2 = v.dot( v );
  32491. const w2 = a2.div( v2 );
  32492. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  32493. } ).setLayout( {
  32494. name: 'D_GGX_Anisotropic',
  32495. type: 'float',
  32496. inputs: [
  32497. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32498. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32499. { name: 'dotNH', type: 'float', qualifier: 'in' },
  32500. { name: 'dotTH', type: 'float', qualifier: 'in' },
  32501. { name: 'dotBH', type: 'float', qualifier: 'in' }
  32502. ]
  32503. } );
  32504. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  32505. const BRDF_GGX = tslFn( ( inputs ) => {
  32506. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  32507. const normalView = inputs.normalView || transformedNormalView;
  32508. const alpha = roughness.pow2(); // UE4's roughness
  32509. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32510. const dotNL = normalView.dot( lightDirection ).clamp();
  32511. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  32512. const dotNH = normalView.dot( halfDir ).clamp();
  32513. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32514. let F = F_Schlick( { f0, f90, dotVH } );
  32515. let V, D;
  32516. if ( defined( USE_IRIDESCENCE ) ) {
  32517. F = iridescence.mix( F, f );
  32518. }
  32519. if ( defined( USE_ANISOTROPY ) ) {
  32520. const dotTL = anisotropyT.dot( lightDirection );
  32521. const dotTV = anisotropyT.dot( positionViewDirection );
  32522. const dotTH = anisotropyT.dot( halfDir );
  32523. const dotBL = anisotropyB.dot( lightDirection );
  32524. const dotBV = anisotropyB.dot( positionViewDirection );
  32525. const dotBH = anisotropyB.dot( halfDir );
  32526. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  32527. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  32528. } else {
  32529. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  32530. D = D_GGX( { alpha, dotNH } );
  32531. }
  32532. return F.mul( V ).mul( D );
  32533. } ); // validated
  32534. // Analytical approximation of the DFG LUT, one half of the
  32535. // split-sum approximation used in indirect specular lighting.
  32536. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  32537. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  32538. const DFGApprox = tslFn( ( { roughness, dotNV } ) => {
  32539. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  32540. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  32541. const r = roughness.mul( c0 ).add( c1 );
  32542. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  32543. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  32544. return fab;
  32545. } ).setLayout( {
  32546. name: 'DFGApprox',
  32547. type: 'vec2',
  32548. inputs: [
  32549. { name: 'roughness', type: 'float' },
  32550. { name: 'dotNV', type: 'vec3' }
  32551. ]
  32552. } );
  32553. const EnvironmentBRDF = tslFn( ( inputs ) => {
  32554. const { dotNV, specularColor, specularF90, roughness } = inputs;
  32555. const fab = DFGApprox( { dotNV, roughness } );
  32556. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  32557. } );
  32558. const Schlick_to_F0 = tslFn( ( { f, f90, dotVH } ) => {
  32559. const x = dotVH.oneMinus().saturate();
  32560. const x2 = x.mul( x );
  32561. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  32562. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  32563. } ).setLayout( {
  32564. name: 'Schlick_to_F0',
  32565. type: 'vec3',
  32566. inputs: [
  32567. { name: 'f', type: 'vec3' },
  32568. { name: 'f90', type: 'float' },
  32569. { name: 'dotVH', type: 'float' }
  32570. ]
  32571. } );
  32572. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32573. const D_Charlie = tslFn( ( { roughness, dotNH } ) => {
  32574. const alpha = roughness.pow2();
  32575. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  32576. const invAlpha = float( 1.0 ).div( alpha );
  32577. const cos2h = dotNH.pow2();
  32578. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  32579. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  32580. } ).setLayout( {
  32581. name: 'D_Charlie',
  32582. type: 'float',
  32583. inputs: [
  32584. { name: 'roughness', type: 'float' },
  32585. { name: 'dotNH', type: 'float' }
  32586. ]
  32587. } );
  32588. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32589. const V_Neubelt = tslFn( ( { dotNV, dotNL } ) => {
  32590. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  32591. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  32592. } ).setLayout( {
  32593. name: 'V_Neubelt',
  32594. type: 'float',
  32595. inputs: [
  32596. { name: 'dotNV', type: 'float' },
  32597. { name: 'dotNL', type: 'float' }
  32598. ]
  32599. } );
  32600. const BRDF_Sheen = tslFn( ( { lightDirection } ) => {
  32601. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32602. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32603. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  32604. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32605. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  32606. const V = V_Neubelt( { dotNV, dotNL } );
  32607. return sheen.mul( D ).mul( V );
  32608. } );
  32609. // Rect Area Light
  32610. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  32611. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  32612. // code: https://github.com/selfshadow/ltc_code/
  32613. const LTC_Uv = tslFn( ( { N, V, roughness } ) => {
  32614. const LUT_SIZE = 64.0;
  32615. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  32616. const LUT_BIAS = 0.5 / LUT_SIZE;
  32617. const dotNV = N.dot( V ).saturate();
  32618. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  32619. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  32620. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  32621. return uv;
  32622. } ).setLayout( {
  32623. name: 'LTC_Uv',
  32624. type: 'vec2',
  32625. inputs: [
  32626. { name: 'N', type: 'vec3' },
  32627. { name: 'V', type: 'vec3' },
  32628. { name: 'roughness', type: 'float' }
  32629. ]
  32630. } );
  32631. const LTC_ClippedSphereFormFactor = tslFn( ( { f } ) => {
  32632. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  32633. // An approximation of the form factor of a horizon-clipped rectangle.
  32634. const l = f.length();
  32635. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  32636. } ).setLayout( {
  32637. name: 'LTC_ClippedSphereFormFactor',
  32638. type: 'float',
  32639. inputs: [
  32640. { name: 'f', type: 'vec3' }
  32641. ]
  32642. } );
  32643. const LTC_EdgeVectorFormFactor = tslFn( ( { v1, v2 } ) => {
  32644. const x = v1.dot( v2 );
  32645. const y = x.abs().toVar();
  32646. // rational polynomial approximation to theta / sin( theta ) / 2PI
  32647. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  32648. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  32649. const v = a.div( b );
  32650. const theta_sintheta = x.greaterThan( 0.0 ).cond( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  32651. return v1.cross( v2 ).mul( theta_sintheta );
  32652. } ).setLayout( {
  32653. name: 'LTC_EdgeVectorFormFactor',
  32654. type: 'vec3',
  32655. inputs: [
  32656. { name: 'v1', type: 'vec3' },
  32657. { name: 'v2', type: 'vec3' }
  32658. ]
  32659. } );
  32660. const LTC_Evaluate = tslFn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  32661. // bail if point is on back side of plane of light
  32662. // assumes ccw winding order of light vertices
  32663. const v1 = p1.sub( p0 ).toVar();
  32664. const v2 = p3.sub( p0 ).toVar();
  32665. const lightNormal = v1.cross( v2 );
  32666. const result = vec3().toVar();
  32667. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  32668. // construct orthonormal basis around N
  32669. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  32670. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  32671. // compute transform
  32672. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  32673. // transform rect
  32674. // & project rect onto sphere
  32675. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  32676. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  32677. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  32678. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  32679. // calculate vector form factor
  32680. const vectorFormFactor = vec3( 0 ).toVar();
  32681. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  32682. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  32683. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  32684. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  32685. // adjust for horizon clipping
  32686. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  32687. } );
  32688. return result;
  32689. } ).setLayout( {
  32690. name: 'LTC_Evaluate',
  32691. type: 'vec3',
  32692. inputs: [
  32693. { name: 'N', type: 'vec3' },
  32694. { name: 'V', type: 'vec3' },
  32695. { name: 'P', type: 'vec3' },
  32696. { name: 'mInv', type: 'mat3' },
  32697. { name: 'p0', type: 'vec3' },
  32698. { name: 'p1', type: 'vec3' },
  32699. { name: 'p2', type: 'vec3' },
  32700. { name: 'p3', type: 'vec3' }
  32701. ]
  32702. } );
  32703. //
  32704. // Transmission
  32705. //
  32706. const getVolumeTransmissionRay = tslFn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  32707. // Direction of refracted light.
  32708. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  32709. // Compute rotation-independant scaling of the model matrix.
  32710. const modelScale = vec3(
  32711. length( modelMatrix[ 0 ].xyz ),
  32712. length( modelMatrix[ 1 ].xyz ),
  32713. length( modelMatrix[ 2 ].xyz )
  32714. );
  32715. // The thickness is specified in local space.
  32716. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  32717. } ).setLayout( {
  32718. name: 'getVolumeTransmissionRay',
  32719. type: 'vec3',
  32720. inputs: [
  32721. { name: 'n', type: 'vec3' },
  32722. { name: 'v', type: 'vec3' },
  32723. { name: 'thickness', type: 'float' },
  32724. { name: 'ior', type: 'float' },
  32725. { name: 'modelMatrix', type: 'mat4' }
  32726. ]
  32727. } );
  32728. const applyIorToRoughness = tslFn( ( [ roughness, ior ] ) => {
  32729. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  32730. // an IOR of 1.5 results in the default amount of microfacet refraction.
  32731. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  32732. } ).setLayout( {
  32733. name: 'applyIorToRoughness',
  32734. type: 'float',
  32735. inputs: [
  32736. { name: 'roughness', type: 'float' },
  32737. { name: 'ior', type: 'float' }
  32738. ]
  32739. } );
  32740. const singleViewportMipTexture = viewportMipTexture();
  32741. const getTransmissionSample = tslFn( ( [ fragCoord, roughness, ior ] ) => {
  32742. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  32743. //const transmissionSample = viewportMipTexture( fragCoord );
  32744. const lod = log2( float( viewportResolution.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  32745. return transmissionSample.bicubic( lod );
  32746. } );
  32747. const volumeAttenuation = tslFn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  32748. If( attenuationDistance.notEqual( 0 ), () => {
  32749. // Compute light attenuation using Beer's law.
  32750. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  32751. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  32752. return transmittance;
  32753. } );
  32754. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  32755. return vec3( 1.0 );
  32756. } ).setLayout( {
  32757. name: 'volumeAttenuation',
  32758. type: 'vec3',
  32759. inputs: [
  32760. { name: 'transmissionDistance', type: 'float' },
  32761. { name: 'attenuationColor', type: 'vec3' },
  32762. { name: 'attenuationDistance', type: 'float' }
  32763. ]
  32764. } );
  32765. const getIBLVolumeRefraction = tslFn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  32766. let transmittedLight, transmittance;
  32767. if ( dispersion ) {
  32768. transmittedLight = vec4().toVar();
  32769. transmittance = vec3().toVar();
  32770. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  32771. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  32772. loop( { start: 0, end: 3 }, ( { i } ) => {
  32773. const ior = iors.element( i );
  32774. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  32775. const refractedRayExit = position.add( transmissionRay );
  32776. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  32777. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  32778. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  32779. refractionCoords.addAssign( 1.0 );
  32780. refractionCoords.divAssign( 2.0 );
  32781. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  32782. // Sample framebuffer to get pixel the refracted ray hits.
  32783. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  32784. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  32785. transmittedLight.a.addAssign( transmissionSample.a );
  32786. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  32787. } );
  32788. transmittedLight.a.divAssign( 3.0 );
  32789. } else {
  32790. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  32791. const refractedRayExit = position.add( transmissionRay );
  32792. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  32793. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  32794. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  32795. refractionCoords.addAssign( 1.0 );
  32796. refractionCoords.divAssign( 2.0 );
  32797. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  32798. // Sample framebuffer to get pixel the refracted ray hits.
  32799. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  32800. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  32801. }
  32802. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  32803. const dotNV = n.dot( v ).clamp();
  32804. // Get the specular component.
  32805. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  32806. dotNV,
  32807. specularColor,
  32808. specularF90,
  32809. roughness
  32810. } ) );
  32811. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  32812. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  32813. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  32814. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  32815. } );
  32816. //
  32817. // Iridescence
  32818. //
  32819. // XYZ to linear-sRGB color space
  32820. const XYZ_TO_REC709 = mat3(
  32821. 3.2404542, - 0.9692660, 0.0556434,
  32822. - 1.5371385, 1.8760108, - 0.2040259,
  32823. - 0.4985314, 0.0415560, 1.0572252
  32824. );
  32825. // Assume air interface for top
  32826. // Note: We don't handle the case fresnel0 == 1
  32827. const Fresnel0ToIor = ( fresnel0 ) => {
  32828. const sqrtF0 = fresnel0.sqrt();
  32829. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  32830. };
  32831. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  32832. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  32833. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  32834. };
  32835. // Fresnel equations for dielectric/dielectric interfaces.
  32836. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  32837. // Evaluation XYZ sensitivity curves in Fourier space
  32838. const evalSensitivity = ( OPD, shift ) => {
  32839. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  32840. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  32841. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  32842. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  32843. 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() );
  32844. 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() );
  32845. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  32846. const rgb = XYZ_TO_REC709.mul( xyz );
  32847. return rgb;
  32848. };
  32849. const evalIridescence = tslFn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  32850. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  32851. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  32852. // Evaluate the cosTheta on the base layer (Snell law)
  32853. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  32854. // Handle TIR:
  32855. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  32856. /*if ( cosTheta2Sq < 0.0 ) {
  32857. return vec3( 1.0 );
  32858. }*/
  32859. const cosTheta2 = cosTheta2Sq.sqrt();
  32860. // First interface
  32861. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  32862. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  32863. //const R21 = R12;
  32864. const T121 = R12.oneMinus();
  32865. const phi12 = iridescenceIOR.lessThan( outsideIOR ).cond( Math.PI, 0.0 );
  32866. const phi21 = float( Math.PI ).sub( phi12 );
  32867. // Second interface
  32868. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  32869. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  32870. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  32871. const phi23 = vec3(
  32872. baseIOR.x.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  32873. baseIOR.y.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  32874. baseIOR.z.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 )
  32875. );
  32876. // Phase shift
  32877. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  32878. const phi = vec3( phi21 ).add( phi23 );
  32879. // Compound terms
  32880. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  32881. const r123 = R123.sqrt();
  32882. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  32883. // Reflectance term for m = 0 (DC term amplitude)
  32884. const C0 = R12.add( Rs );
  32885. let I = C0;
  32886. // Reflectance term for m > 0 (pairs of diracs)
  32887. let Cm = Rs.sub( T121 );
  32888. for ( let m = 1; m <= 2; ++ m ) {
  32889. Cm = Cm.mul( r123 );
  32890. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  32891. I = I.add( Cm.mul( Sm ) );
  32892. }
  32893. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  32894. return I.max( vec3( 0.0 ) );
  32895. } ).setLayout( {
  32896. name: 'evalIridescence',
  32897. type: 'vec3',
  32898. inputs: [
  32899. { name: 'outsideIOR', type: 'float' },
  32900. { name: 'eta2', type: 'float' },
  32901. { name: 'cosTheta1', type: 'float' },
  32902. { name: 'thinFilmThickness', type: 'float' },
  32903. { name: 'baseF0', type: 'vec3' }
  32904. ]
  32905. } );
  32906. //
  32907. // Sheen
  32908. //
  32909. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  32910. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  32911. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  32912. const IBLSheenBRDF = tslFn( ( { normal, viewDir, roughness } ) => {
  32913. const dotNV = normal.dot( viewDir ).saturate();
  32914. const r2 = roughness.pow2();
  32915. const a = cond(
  32916. roughness.lessThan( 0.25 ),
  32917. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  32918. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  32919. );
  32920. const b = cond(
  32921. roughness.lessThan( 0.25 ),
  32922. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  32923. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  32924. );
  32925. const DG = cond( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  32926. return DG.mul( 1.0 / Math.PI ).saturate();
  32927. } );
  32928. const clearcoatF0 = vec3( 0.04 );
  32929. const clearcoatF90 = float( 1 );
  32930. //
  32931. class PhysicalLightingModel extends LightingModel {
  32932. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  32933. super();
  32934. this.clearcoat = clearcoat;
  32935. this.sheen = sheen;
  32936. this.iridescence = iridescence;
  32937. this.anisotropy = anisotropy;
  32938. this.transmission = transmission;
  32939. this.dispersion = dispersion;
  32940. this.clearcoatRadiance = null;
  32941. this.clearcoatSpecularDirect = null;
  32942. this.clearcoatSpecularIndirect = null;
  32943. this.sheenSpecularDirect = null;
  32944. this.sheenSpecularIndirect = null;
  32945. this.iridescenceFresnel = null;
  32946. this.iridescenceF0 = null;
  32947. }
  32948. start( context ) {
  32949. if ( this.clearcoat === true ) {
  32950. this.clearcoatRadiance = vec3().temp( 'clearcoatRadiance' );
  32951. this.clearcoatSpecularDirect = vec3().temp( 'clearcoatSpecularDirect' );
  32952. this.clearcoatSpecularIndirect = vec3().temp( 'clearcoatSpecularIndirect' );
  32953. }
  32954. if ( this.sheen === true ) {
  32955. this.sheenSpecularDirect = vec3().temp( 'sheenSpecularDirect' );
  32956. this.sheenSpecularIndirect = vec3().temp( 'sheenSpecularIndirect' );
  32957. }
  32958. if ( this.iridescence === true ) {
  32959. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  32960. this.iridescenceFresnel = evalIridescence( {
  32961. outsideIOR: float( 1.0 ),
  32962. eta2: iridescenceIOR,
  32963. cosTheta1: dotNVi,
  32964. thinFilmThickness: iridescenceThickness,
  32965. baseF0: specularColor
  32966. } );
  32967. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  32968. }
  32969. if ( this.transmission === true ) {
  32970. const position = positionWorld;
  32971. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  32972. const n = transformedNormalWorld;
  32973. context.backdrop = getIBLVolumeRefraction(
  32974. n,
  32975. v,
  32976. roughness,
  32977. diffuseColor,
  32978. specularColor,
  32979. specularF90, // specularF90
  32980. position, // positionWorld
  32981. modelWorldMatrix, // modelMatrix
  32982. cameraViewMatrix, // viewMatrix
  32983. cameraProjectionMatrix, // projMatrix
  32984. ior,
  32985. thickness,
  32986. attenuationColor,
  32987. attenuationDistance,
  32988. this.dispersion ? dispersion : null
  32989. );
  32990. context.backdropAlpha = transmission;
  32991. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  32992. }
  32993. }
  32994. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  32995. // Approximates multiscattering in order to preserve energy.
  32996. // http://www.jcgt.org/published/0008/01/03/
  32997. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  32998. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  32999. const fab = DFGApprox( { roughness, dotNV } );
  33000. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  33001. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  33002. const Ess = fab.x.add( fab.y );
  33003. const Ems = Ess.oneMinus();
  33004. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  33005. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  33006. singleScatter.addAssign( FssEss );
  33007. multiScatter.addAssign( Fms.mul( Ems ) );
  33008. }
  33009. direct( { lightDirection, lightColor, reflectedLight } ) {
  33010. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  33011. const irradiance = dotNL.mul( lightColor );
  33012. if ( this.sheen === true ) {
  33013. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  33014. }
  33015. if ( this.clearcoat === true ) {
  33016. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  33017. const ccIrradiance = dotNLcc.mul( lightColor );
  33018. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  33019. }
  33020. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33021. 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 } ) ) );
  33022. }
  33023. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  33024. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  33025. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  33026. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  33027. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  33028. const N = transformedNormalView;
  33029. const V = positionViewDirection;
  33030. const P = positionView.toVar();
  33031. const uv = LTC_Uv( { N, V, roughness } );
  33032. const t1 = ltc_1.uv( uv ).toVar();
  33033. const t2 = ltc_2.uv( uv ).toVar();
  33034. const mInv = mat3(
  33035. vec3( t1.x, 0, t1.y ),
  33036. vec3( 0, 1, 0 ),
  33037. vec3( t1.z, 0, t1.w )
  33038. ).toVar();
  33039. // LTC Fresnel Approximation by Stephen Hill
  33040. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  33041. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  33042. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  33043. 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 } ) ) );
  33044. }
  33045. indirectDiffuse( { irradiance, reflectedLight } ) {
  33046. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33047. }
  33048. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  33049. if ( this.sheen === true ) {
  33050. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  33051. sheen,
  33052. IBLSheenBRDF( {
  33053. normal: transformedNormalView,
  33054. viewDir: positionViewDirection,
  33055. roughness: sheenRoughness
  33056. } )
  33057. ) );
  33058. }
  33059. if ( this.clearcoat === true ) {
  33060. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  33061. const clearcoatEnv = EnvironmentBRDF( {
  33062. dotNV: dotNVcc,
  33063. specularColor: clearcoatF0,
  33064. specularF90: clearcoatF90,
  33065. roughness: clearcoatRoughness
  33066. } );
  33067. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  33068. }
  33069. // Both indirect specular and indirect diffuse light accumulate here
  33070. const singleScattering = vec3().temp( 'singleScattering' );
  33071. const multiScattering = vec3().temp( 'multiScattering' );
  33072. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  33073. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  33074. const totalScattering = singleScattering.add( multiScattering );
  33075. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  33076. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  33077. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  33078. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  33079. }
  33080. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  33081. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  33082. const aoNV = dotNV.add( ambientOcclusion );
  33083. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  33084. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  33085. if ( this.clearcoat === true ) {
  33086. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  33087. }
  33088. if ( this.sheen === true ) {
  33089. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  33090. }
  33091. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33092. reflectedLight.indirectSpecular.mulAssign( aoNode );
  33093. }
  33094. finish( context ) {
  33095. const { outgoingLight } = context;
  33096. if ( this.clearcoat === true ) {
  33097. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  33098. const Fcc = F_Schlick( {
  33099. dotVH: dotNVcc,
  33100. f0: clearcoatF0,
  33101. f90: clearcoatF90
  33102. } );
  33103. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  33104. outgoingLight.assign( clearcoatLight );
  33105. }
  33106. if ( this.sheen === true ) {
  33107. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  33108. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  33109. outgoingLight.assign( sheenLight );
  33110. }
  33111. }
  33112. }
  33113. const defaultValues$6 = new MeshStandardMaterial();
  33114. class MeshStandardNodeMaterial extends NodeMaterial {
  33115. constructor( parameters ) {
  33116. super();
  33117. this.isMeshStandardNodeMaterial = true;
  33118. this.emissiveNode = null;
  33119. this.metalnessNode = null;
  33120. this.roughnessNode = null;
  33121. this.setDefaultValues( defaultValues$6 );
  33122. this.setValues( parameters );
  33123. }
  33124. setupLightingModel( /*builder*/ ) {
  33125. return new PhysicalLightingModel();
  33126. }
  33127. setupSpecular() {
  33128. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  33129. specularColor.assign( specularColorNode );
  33130. specularF90.assign( 1.0 );
  33131. }
  33132. setupVariants() {
  33133. // METALNESS
  33134. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  33135. metalness.assign( metalnessNode );
  33136. // ROUGHNESS
  33137. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  33138. roughnessNode = getRoughness( { roughness: roughnessNode } );
  33139. roughness.assign( roughnessNode );
  33140. // SPECULAR COLOR
  33141. this.setupSpecular();
  33142. // DIFFUSE COLOR
  33143. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  33144. }
  33145. copy( source ) {
  33146. this.emissiveNode = source.emissiveNode;
  33147. this.metalnessNode = source.metalnessNode;
  33148. this.roughnessNode = source.roughnessNode;
  33149. return super.copy( source );
  33150. }
  33151. }
  33152. addNodeMaterial( 'MeshStandardNodeMaterial', MeshStandardNodeMaterial );
  33153. const defaultValues$5 = new MeshPhysicalMaterial();
  33154. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  33155. constructor( parameters ) {
  33156. super();
  33157. this.isMeshPhysicalNodeMaterial = true;
  33158. this.clearcoatNode = null;
  33159. this.clearcoatRoughnessNode = null;
  33160. this.clearcoatNormalNode = null;
  33161. this.sheenNode = null;
  33162. this.sheenRoughnessNode = null;
  33163. this.iridescenceNode = null;
  33164. this.iridescenceIORNode = null;
  33165. this.iridescenceThicknessNode = null;
  33166. this.specularIntensityNode = null;
  33167. this.specularColorNode = null;
  33168. this.iorNode = null;
  33169. this.transmissionNode = null;
  33170. this.thicknessNode = null;
  33171. this.attenuationDistanceNode = null;
  33172. this.attenuationColorNode = null;
  33173. this.dispersionNode = null;
  33174. this.anisotropyNode = null;
  33175. this.setDefaultValues( defaultValues$5 );
  33176. this.setValues( parameters );
  33177. }
  33178. get useClearcoat() {
  33179. return this.clearcoat > 0 || this.clearcoatNode !== null;
  33180. }
  33181. get useIridescence() {
  33182. return this.iridescence > 0 || this.iridescenceNode !== null;
  33183. }
  33184. get useSheen() {
  33185. return this.sheen > 0 || this.sheenNode !== null;
  33186. }
  33187. get useAnisotropy() {
  33188. return this.anisotropy > 0 || this.anisotropyNode !== null;
  33189. }
  33190. get useTransmission() {
  33191. return this.transmission > 0 || this.transmissionNode !== null;
  33192. }
  33193. get useDispersion() {
  33194. return this.dispersion > 0 || this.dispersionNode !== null;
  33195. }
  33196. setupSpecular() {
  33197. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  33198. ior.assign( iorNode );
  33199. 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 ) );
  33200. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  33201. }
  33202. setupLightingModel( /*builder*/ ) {
  33203. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  33204. }
  33205. setupVariants( builder ) {
  33206. super.setupVariants( builder );
  33207. // CLEARCOAT
  33208. if ( this.useClearcoat ) {
  33209. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  33210. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  33211. clearcoat.assign( clearcoatNode );
  33212. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  33213. }
  33214. // SHEEN
  33215. if ( this.useSheen ) {
  33216. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  33217. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  33218. sheen.assign( sheenNode );
  33219. sheenRoughness.assign( sheenRoughnessNode );
  33220. }
  33221. // IRIDESCENCE
  33222. if ( this.useIridescence ) {
  33223. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  33224. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  33225. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  33226. iridescence.assign( iridescenceNode );
  33227. iridescenceIOR.assign( iridescenceIORNode );
  33228. iridescenceThickness.assign( iridescenceThicknessNode );
  33229. }
  33230. // ANISOTROPY
  33231. if ( this.useAnisotropy ) {
  33232. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  33233. anisotropy.assign( anisotropyV.length() );
  33234. If( anisotropy.equal( 0.0 ), () => {
  33235. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  33236. } ).else( () => {
  33237. anisotropyV.divAssign( vec2( anisotropy ) );
  33238. anisotropy.assign( anisotropy.saturate() );
  33239. } );
  33240. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  33241. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  33242. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  33243. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  33244. }
  33245. // TRANSMISSION
  33246. if ( this.useTransmission ) {
  33247. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  33248. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  33249. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  33250. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  33251. transmission.assign( transmissionNode );
  33252. thickness.assign( thicknessNode );
  33253. attenuationDistance.assign( attenuationDistanceNode );
  33254. attenuationColor.assign( attenuationColorNode );
  33255. if ( this.useDispersion ) {
  33256. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  33257. dispersion.assign( dispersionNode );
  33258. }
  33259. }
  33260. }
  33261. setupNormal( builder ) {
  33262. super.setupNormal( builder );
  33263. // CLEARCOAT NORMAL
  33264. const clearcoatNormalNode = this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  33265. transformedClearcoatNormalView.assign( clearcoatNormalNode );
  33266. }
  33267. copy( source ) {
  33268. this.clearcoatNode = source.clearcoatNode;
  33269. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  33270. this.clearcoatNormalNode = source.clearcoatNormalNode;
  33271. this.sheenNode = source.sheenNode;
  33272. this.sheenRoughnessNode = source.sheenRoughnessNode;
  33273. this.iridescenceNode = source.iridescenceNode;
  33274. this.iridescenceIORNode = source.iridescenceIORNode;
  33275. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  33276. this.specularIntensityNode = source.specularIntensityNode;
  33277. this.specularColorNode = source.specularColorNode;
  33278. this.transmissionNode = source.transmissionNode;
  33279. this.thicknessNode = source.thicknessNode;
  33280. this.attenuationDistanceNode = source.attenuationDistanceNode;
  33281. this.attenuationColorNode = source.attenuationColorNode;
  33282. this.dispersionNode = source.dispersionNode;
  33283. this.anisotropyNode = source.anisotropyNode;
  33284. return super.copy( source );
  33285. }
  33286. }
  33287. addNodeMaterial( 'MeshPhysicalNodeMaterial', MeshPhysicalNodeMaterial );
  33288. class SSSLightingModel extends PhysicalLightingModel {
  33289. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  33290. super( useClearcoat, useSheen, useIridescence );
  33291. this.useSSS = useSSS;
  33292. }
  33293. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33294. if ( this.useSSS === true ) {
  33295. const material = builder.material;
  33296. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  33297. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  33298. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  33299. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  33300. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  33301. }
  33302. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  33303. }
  33304. }
  33305. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  33306. constructor( parameters ) {
  33307. super( parameters );
  33308. this.thicknessColorNode = null;
  33309. this.thicknessDistortionNode = float( 0.1 );
  33310. this.thicknessAmbientNode = float( 0.0 );
  33311. this.thicknessAttenuationNode = float( .1 );
  33312. this.thicknessPowerNode = float( 2.0 );
  33313. this.thicknessScaleNode = float( 10.0 );
  33314. }
  33315. get useSSS() {
  33316. return this.thicknessColorNode !== null;
  33317. }
  33318. setupLightingModel( /*builder*/ ) {
  33319. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  33320. }
  33321. copy( source ) {
  33322. this.thicknessColorNode = source.thicknessColorNode;
  33323. this.thicknessDistortionNode = source.thicknessDistortionNode;
  33324. this.thicknessAmbientNode = source.thicknessAmbientNode;
  33325. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  33326. this.thicknessPowerNode = source.thicknessPowerNode;
  33327. this.thicknessScaleNode = source.thicknessScaleNode;
  33328. return super.copy( source );
  33329. }
  33330. }
  33331. addNodeMaterial( 'MeshSSSNodeMaterial', MeshSSSNodeMaterial );
  33332. const getGradientIrradiance = tslFn( ( { normal, lightDirection, builder } ) => {
  33333. // dotNL will be from -1.0 to 1.0
  33334. const dotNL = normal.dot( lightDirection );
  33335. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  33336. if ( builder.material.gradientMap ) {
  33337. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  33338. return vec3( gradientMap.r );
  33339. } else {
  33340. const fw = coord.fwidth().mul( 0.5 );
  33341. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  33342. }
  33343. } );
  33344. class ToonLightingModel extends LightingModel {
  33345. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33346. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  33347. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33348. }
  33349. indirectDiffuse( { irradiance, reflectedLight } ) {
  33350. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33351. }
  33352. }
  33353. const defaultValues$4 = new MeshToonMaterial();
  33354. class MeshToonNodeMaterial extends NodeMaterial {
  33355. constructor( parameters ) {
  33356. super();
  33357. this.isMeshToonNodeMaterial = true;
  33358. this.lights = true;
  33359. this.setDefaultValues( defaultValues$4 );
  33360. this.setValues( parameters );
  33361. }
  33362. setupLightingModel( /*builder*/ ) {
  33363. return new ToonLightingModel();
  33364. }
  33365. }
  33366. addNodeMaterial( 'MeshToonNodeMaterial', MeshToonNodeMaterial );
  33367. const defaultValues$3 = new MeshMatcapMaterial();
  33368. class MeshMatcapNodeMaterial extends NodeMaterial {
  33369. constructor( parameters ) {
  33370. super();
  33371. this.lights = false;
  33372. this.isMeshMatcapNodeMaterial = true;
  33373. this.setDefaultValues( defaultValues$3 );
  33374. this.setValues( parameters );
  33375. }
  33376. setupVariants( builder ) {
  33377. const uv = matcapUV;
  33378. let matcapColor;
  33379. if ( builder.material.matcap ) {
  33380. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  33381. } else {
  33382. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  33383. }
  33384. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  33385. }
  33386. }
  33387. addNodeMaterial( 'MeshMatcapNodeMaterial', MeshMatcapNodeMaterial );
  33388. const defaultValues$2 = new PointsMaterial();
  33389. class PointsNodeMaterial extends NodeMaterial {
  33390. constructor( parameters ) {
  33391. super();
  33392. this.isPointsNodeMaterial = true;
  33393. this.lights = false;
  33394. this.normals = false;
  33395. this.transparent = true;
  33396. this.sizeNode = null;
  33397. this.setDefaultValues( defaultValues$2 );
  33398. this.setValues( parameters );
  33399. }
  33400. copy( source ) {
  33401. this.sizeNode = source.sizeNode;
  33402. return super.copy( source );
  33403. }
  33404. }
  33405. addNodeMaterial( 'PointsNodeMaterial', PointsNodeMaterial );
  33406. const defaultValues$1 = new SpriteMaterial();
  33407. class SpriteNodeMaterial extends NodeMaterial {
  33408. constructor( parameters ) {
  33409. super();
  33410. this.isSpriteNodeMaterial = true;
  33411. this.lights = false;
  33412. this.normals = false;
  33413. this.positionNode = null;
  33414. this.rotationNode = null;
  33415. this.scaleNode = null;
  33416. this.setDefaultValues( defaultValues$1 );
  33417. this.setValues( parameters );
  33418. }
  33419. setupPosition( { object, context } ) {
  33420. // < VERTEX STAGE >
  33421. const { positionNode, rotationNode, scaleNode } = this;
  33422. const vertex = positionLocal;
  33423. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  33424. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  33425. if ( scaleNode !== null ) {
  33426. scale = scale.mul( scaleNode );
  33427. }
  33428. let alignedPosition = vertex.xy;
  33429. if ( object.center && object.center.isVector2 === true ) {
  33430. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  33431. }
  33432. alignedPosition = alignedPosition.mul( scale );
  33433. const rotation = float( rotationNode || materialRotation );
  33434. const rotatedPosition = alignedPosition.rotate( rotation );
  33435. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  33436. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  33437. context.vertex = vertex;
  33438. return modelViewProjection;
  33439. }
  33440. copy( source ) {
  33441. this.positionNode = source.positionNode;
  33442. this.rotationNode = source.rotationNode;
  33443. this.scaleNode = source.scaleNode;
  33444. return super.copy( source );
  33445. }
  33446. }
  33447. addNodeMaterial( 'SpriteNodeMaterial', SpriteNodeMaterial );
  33448. class ShadowMaskModel extends LightingModel {
  33449. constructor() {
  33450. super();
  33451. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  33452. }
  33453. direct( { shadowMask } ) {
  33454. this.shadowNode.mulAssign( shadowMask );
  33455. }
  33456. finish( context ) {
  33457. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  33458. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  33459. }
  33460. }
  33461. const defaultValues = new ShadowMaterial();
  33462. class ShadowNodeMaterial extends NodeMaterial {
  33463. constructor( parameters ) {
  33464. super();
  33465. this.isShadowNodeMaterial = true;
  33466. this.lights = true;
  33467. this.setDefaultValues( defaultValues );
  33468. this.setValues( parameters );
  33469. }
  33470. setupLightingModel( /*builder*/ ) {
  33471. return new ShadowMaskModel();
  33472. }
  33473. }
  33474. addNodeMaterial( 'ShadowNodeMaterial', ShadowNodeMaterial );
  33475. class VolumeNodeMaterial extends NodeMaterial {
  33476. constructor( params = {} ) {
  33477. super();
  33478. this.normals = false;
  33479. this.lights = false;
  33480. this.isVolumeNodeMaterial = true;
  33481. this.testNode = null;
  33482. this.setValues( params );
  33483. }
  33484. setup( builder ) {
  33485. const map = texture3D( this.map, null, 0 );
  33486. const hitBox = tslFn( ( { orig, dir } ) => {
  33487. const box_min = vec3( - 0.5 );
  33488. const box_max = vec3( 0.5 );
  33489. const inv_dir = dir.reciprocal();
  33490. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  33491. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  33492. const tmin = min$1( tmin_tmp, tmax_tmp );
  33493. const tmax = max$1( tmin_tmp, tmax_tmp );
  33494. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  33495. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  33496. return vec2( t0, t1 );
  33497. } );
  33498. this.fragmentNode = tslFn( () => {
  33499. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  33500. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  33501. const rayDir = vDirection.normalize();
  33502. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  33503. bounds.x.greaterThan( bounds.y ).discard();
  33504. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  33505. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  33506. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  33507. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  33508. delta.divAssign( materialReference( 'steps', 'float' ) );
  33509. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  33510. loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  33511. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  33512. if ( this.testNode !== null ) {
  33513. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  33514. } else {
  33515. // default to show surface of mesh
  33516. ac.a.assign( 1 );
  33517. Break();
  33518. }
  33519. p.addAssign( rayDir.mul( delta ) );
  33520. } );
  33521. ac.a.equal( 0 ).discard();
  33522. return vec4( ac );
  33523. } )();
  33524. super.setup( builder );
  33525. }
  33526. }
  33527. addNodeMaterial( 'VolumeNodeMaterial', VolumeNodeMaterial );
  33528. const superFromTypeFunction = MaterialLoader.createMaterialFromType;
  33529. MaterialLoader.createMaterialFromType = function ( type ) {
  33530. const material = createNodeMaterialFromType( type );
  33531. if ( material !== undefined ) {
  33532. return material;
  33533. }
  33534. return superFromTypeFunction.call( this, type );
  33535. };
  33536. class NodeMaterialLoader extends MaterialLoader {
  33537. constructor( manager ) {
  33538. super( manager );
  33539. this.nodes = {};
  33540. }
  33541. parse( json ) {
  33542. const material = super.parse( json );
  33543. const nodes = this.nodes;
  33544. const inputNodes = json.inputNodes;
  33545. for ( const property in inputNodes ) {
  33546. const uuid = inputNodes[ property ];
  33547. material[ property ] = nodes[ uuid ];
  33548. }
  33549. return material;
  33550. }
  33551. setNodes( value ) {
  33552. this.nodes = value;
  33553. return this;
  33554. }
  33555. }
  33556. class NodeObjectLoader extends ObjectLoader {
  33557. constructor( manager ) {
  33558. super( manager );
  33559. this._nodesJSON = null;
  33560. }
  33561. parse( json, onLoad ) {
  33562. this._nodesJSON = json.nodes;
  33563. const data = super.parse( json, onLoad );
  33564. this._nodesJSON = null; // dispose
  33565. return data;
  33566. }
  33567. parseNodes( json, textures ) {
  33568. if ( json !== undefined ) {
  33569. const loader = new NodeLoader();
  33570. loader.setTextures( textures );
  33571. return loader.parseNodes( json );
  33572. }
  33573. return {};
  33574. }
  33575. parseMaterials( json, textures ) {
  33576. const materials = {};
  33577. if ( json !== undefined ) {
  33578. const nodes = this.parseNodes( this._nodesJSON, textures );
  33579. const loader = new NodeMaterialLoader();
  33580. loader.setTextures( textures );
  33581. loader.setNodes( nodes );
  33582. for ( let i = 0, l = json.length; i < l; i ++ ) {
  33583. const data = json[ i ];
  33584. materials[ data.uuid ] = loader.parse( data );
  33585. }
  33586. }
  33587. return materials;
  33588. }
  33589. }
  33590. class NodeParser {
  33591. parseFunction( /*source*/ ) {
  33592. console.warn( 'Abstract function.' );
  33593. }
  33594. }
  33595. class NodeFunction {
  33596. constructor( type, inputs, name = '', precision = '' ) {
  33597. this.type = type;
  33598. this.inputs = inputs;
  33599. this.name = name;
  33600. this.precision = precision;
  33601. }
  33602. getCode( /*name = this.name*/ ) {
  33603. console.warn( 'Abstract function.' );
  33604. }
  33605. }
  33606. NodeFunction.isNodeFunction = true;
  33607. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  33608. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  33609. const pragmaMain = '#pragma main';
  33610. const parse$1 = ( source ) => {
  33611. source = source.trim();
  33612. const pragmaMainIndex = source.indexOf( pragmaMain );
  33613. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  33614. const declaration = mainCode.match( declarationRegexp$1 );
  33615. if ( declaration !== null && declaration.length === 5 ) {
  33616. // tokenizer
  33617. const inputsCode = declaration[ 4 ];
  33618. const propsMatches = [];
  33619. let nameMatch = null;
  33620. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  33621. propsMatches.push( nameMatch );
  33622. }
  33623. // parser
  33624. const inputs = [];
  33625. let i = 0;
  33626. while ( i < propsMatches.length ) {
  33627. const isConst = propsMatches[ i ][ 0 ] === 'const';
  33628. if ( isConst === true ) {
  33629. i ++;
  33630. }
  33631. let qualifier = propsMatches[ i ][ 0 ];
  33632. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  33633. i ++;
  33634. } else {
  33635. qualifier = '';
  33636. }
  33637. const type = propsMatches[ i ++ ][ 0 ];
  33638. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  33639. if ( Number.isNaN( count ) === false ) i ++;
  33640. else count = null;
  33641. const name = propsMatches[ i ++ ][ 0 ];
  33642. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  33643. }
  33644. //
  33645. const blockCode = mainCode.substring( declaration[ 0 ].length );
  33646. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  33647. const type = declaration[ 2 ];
  33648. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  33649. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  33650. return {
  33651. type,
  33652. inputs,
  33653. name,
  33654. precision,
  33655. inputsCode,
  33656. blockCode,
  33657. headerCode
  33658. };
  33659. } else {
  33660. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  33661. }
  33662. };
  33663. class GLSLNodeFunction extends NodeFunction {
  33664. constructor( source ) {
  33665. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  33666. super( type, inputs, name, precision );
  33667. this.inputsCode = inputsCode;
  33668. this.blockCode = blockCode;
  33669. this.headerCode = headerCode;
  33670. }
  33671. getCode( name = this.name ) {
  33672. let code;
  33673. const blockCode = this.blockCode;
  33674. if ( blockCode !== '' ) {
  33675. const { type, inputsCode, headerCode, precision } = this;
  33676. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  33677. if ( precision !== '' ) {
  33678. declarationCode = `${ precision } ${ declarationCode }`;
  33679. }
  33680. code = headerCode + declarationCode + blockCode;
  33681. } else {
  33682. // interface function
  33683. code = '';
  33684. }
  33685. return code;
  33686. }
  33687. }
  33688. class GLSLNodeParser extends NodeParser {
  33689. parseFunction( source ) {
  33690. return new GLSLNodeFunction( source );
  33691. }
  33692. }
  33693. // Three.js Transpiler
  33694. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33695. const mx_select = /*#__PURE__*/ tslFn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33696. const f = float( f_immutable ).toVar();
  33697. const t = float( t_immutable ).toVar();
  33698. const b = bool( b_immutable ).toVar();
  33699. return cond( b, t, f );
  33700. } ).setLayout( {
  33701. name: 'mx_select',
  33702. type: 'float',
  33703. inputs: [
  33704. { name: 'b', type: 'bool' },
  33705. { name: 't', type: 'float' },
  33706. { name: 'f', type: 'float' }
  33707. ]
  33708. } );
  33709. const mx_negate_if = /*#__PURE__*/ tslFn( ( [ val_immutable, b_immutable ] ) => {
  33710. const b = bool( b_immutable ).toVar();
  33711. const val = float( val_immutable ).toVar();
  33712. return cond( b, val.negate(), val );
  33713. } ).setLayout( {
  33714. name: 'mx_negate_if',
  33715. type: 'float',
  33716. inputs: [
  33717. { name: 'val', type: 'float' },
  33718. { name: 'b', type: 'bool' }
  33719. ]
  33720. } );
  33721. const mx_floor = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  33722. const x = float( x_immutable ).toVar();
  33723. return int( floor( x ) );
  33724. } ).setLayout( {
  33725. name: 'mx_floor',
  33726. type: 'int',
  33727. inputs: [
  33728. { name: 'x', type: 'float' }
  33729. ]
  33730. } );
  33731. const mx_floorfrac = /*#__PURE__*/ tslFn( ( [ x_immutable, i ] ) => {
  33732. const x = float( x_immutable ).toVar();
  33733. i.assign( mx_floor( x ) );
  33734. return x.sub( float( i ) );
  33735. } );
  33736. const mx_bilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33737. const t = float( t_immutable ).toVar();
  33738. const s = float( s_immutable ).toVar();
  33739. const v3 = float( v3_immutable ).toVar();
  33740. const v2 = float( v2_immutable ).toVar();
  33741. const v1 = float( v1_immutable ).toVar();
  33742. const v0 = float( v0_immutable ).toVar();
  33743. const s1 = float( sub( 1.0, s ) ).toVar();
  33744. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33745. } ).setLayout( {
  33746. name: 'mx_bilerp_0',
  33747. type: 'float',
  33748. inputs: [
  33749. { name: 'v0', type: 'float' },
  33750. { name: 'v1', type: 'float' },
  33751. { name: 'v2', type: 'float' },
  33752. { name: 'v3', type: 'float' },
  33753. { name: 's', type: 'float' },
  33754. { name: 't', type: 'float' }
  33755. ]
  33756. } );
  33757. const mx_bilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33758. const t = float( t_immutable ).toVar();
  33759. const s = float( s_immutable ).toVar();
  33760. const v3 = vec3( v3_immutable ).toVar();
  33761. const v2 = vec3( v2_immutable ).toVar();
  33762. const v1 = vec3( v1_immutable ).toVar();
  33763. const v0 = vec3( v0_immutable ).toVar();
  33764. const s1 = float( sub( 1.0, s ) ).toVar();
  33765. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33766. } ).setLayout( {
  33767. name: 'mx_bilerp_1',
  33768. type: 'vec3',
  33769. inputs: [
  33770. { name: 'v0', type: 'vec3' },
  33771. { name: 'v1', type: 'vec3' },
  33772. { name: 'v2', type: 'vec3' },
  33773. { name: 'v3', type: 'vec3' },
  33774. { name: 's', type: 'float' },
  33775. { name: 't', type: 'float' }
  33776. ]
  33777. } );
  33778. const mx_bilerp = /*#__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  33779. const mx_trilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  33780. const r = float( r_immutable ).toVar();
  33781. const t = float( t_immutable ).toVar();
  33782. const s = float( s_immutable ).toVar();
  33783. const v7 = float( v7_immutable ).toVar();
  33784. const v6 = float( v6_immutable ).toVar();
  33785. const v5 = float( v5_immutable ).toVar();
  33786. const v4 = float( v4_immutable ).toVar();
  33787. const v3 = float( v3_immutable ).toVar();
  33788. const v2 = float( v2_immutable ).toVar();
  33789. const v1 = float( v1_immutable ).toVar();
  33790. const v0 = float( v0_immutable ).toVar();
  33791. const s1 = float( sub( 1.0, s ) ).toVar();
  33792. const t1 = float( sub( 1.0, t ) ).toVar();
  33793. const r1 = float( sub( 1.0, r ) ).toVar();
  33794. 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 ) ) ) ) ) );
  33795. } ).setLayout( {
  33796. name: 'mx_trilerp_0',
  33797. type: 'float',
  33798. inputs: [
  33799. { name: 'v0', type: 'float' },
  33800. { name: 'v1', type: 'float' },
  33801. { name: 'v2', type: 'float' },
  33802. { name: 'v3', type: 'float' },
  33803. { name: 'v4', type: 'float' },
  33804. { name: 'v5', type: 'float' },
  33805. { name: 'v6', type: 'float' },
  33806. { name: 'v7', type: 'float' },
  33807. { name: 's', type: 'float' },
  33808. { name: 't', type: 'float' },
  33809. { name: 'r', type: 'float' }
  33810. ]
  33811. } );
  33812. const mx_trilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  33813. const r = float( r_immutable ).toVar();
  33814. const t = float( t_immutable ).toVar();
  33815. const s = float( s_immutable ).toVar();
  33816. const v7 = vec3( v7_immutable ).toVar();
  33817. const v6 = vec3( v6_immutable ).toVar();
  33818. const v5 = vec3( v5_immutable ).toVar();
  33819. const v4 = vec3( v4_immutable ).toVar();
  33820. const v3 = vec3( v3_immutable ).toVar();
  33821. const v2 = vec3( v2_immutable ).toVar();
  33822. const v1 = vec3( v1_immutable ).toVar();
  33823. const v0 = vec3( v0_immutable ).toVar();
  33824. const s1 = float( sub( 1.0, s ) ).toVar();
  33825. const t1 = float( sub( 1.0, t ) ).toVar();
  33826. const r1 = float( sub( 1.0, r ) ).toVar();
  33827. 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 ) ) ) ) ) );
  33828. } ).setLayout( {
  33829. name: 'mx_trilerp_1',
  33830. type: 'vec3',
  33831. inputs: [
  33832. { name: 'v0', type: 'vec3' },
  33833. { name: 'v1', type: 'vec3' },
  33834. { name: 'v2', type: 'vec3' },
  33835. { name: 'v3', type: 'vec3' },
  33836. { name: 'v4', type: 'vec3' },
  33837. { name: 'v5', type: 'vec3' },
  33838. { name: 'v6', type: 'vec3' },
  33839. { name: 'v7', type: 'vec3' },
  33840. { name: 's', type: 'float' },
  33841. { name: 't', type: 'float' },
  33842. { name: 'r', type: 'float' }
  33843. ]
  33844. } );
  33845. const mx_trilerp = /*#__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  33846. const mx_gradient_float_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33847. const y = float( y_immutable ).toVar();
  33848. const x = float( x_immutable ).toVar();
  33849. const hash = uint( hash_immutable ).toVar();
  33850. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  33851. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  33852. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  33853. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33854. } ).setLayout( {
  33855. name: 'mx_gradient_float_0',
  33856. type: 'float',
  33857. inputs: [
  33858. { name: 'hash', type: 'uint' },
  33859. { name: 'x', type: 'float' },
  33860. { name: 'y', type: 'float' }
  33861. ]
  33862. } );
  33863. const mx_gradient_float_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33864. const z = float( z_immutable ).toVar();
  33865. const y = float( y_immutable ).toVar();
  33866. const x = float( x_immutable ).toVar();
  33867. const hash = uint( hash_immutable ).toVar();
  33868. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  33869. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  33870. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  33871. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33872. } ).setLayout( {
  33873. name: 'mx_gradient_float_1',
  33874. type: 'float',
  33875. inputs: [
  33876. { name: 'hash', type: 'uint' },
  33877. { name: 'x', type: 'float' },
  33878. { name: 'y', type: 'float' },
  33879. { name: 'z', type: 'float' }
  33880. ]
  33881. } );
  33882. const mx_gradient_float = /*#__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  33883. const mx_gradient_vec3_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33884. const y = float( y_immutable ).toVar();
  33885. const x = float( x_immutable ).toVar();
  33886. const hash = uvec3( hash_immutable ).toVar();
  33887. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  33888. } ).setLayout( {
  33889. name: 'mx_gradient_vec3_0',
  33890. type: 'vec3',
  33891. inputs: [
  33892. { name: 'hash', type: 'uvec3' },
  33893. { name: 'x', type: 'float' },
  33894. { name: 'y', type: 'float' }
  33895. ]
  33896. } );
  33897. const mx_gradient_vec3_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33898. const z = float( z_immutable ).toVar();
  33899. const y = float( y_immutable ).toVar();
  33900. const x = float( x_immutable ).toVar();
  33901. const hash = uvec3( hash_immutable ).toVar();
  33902. 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 ) );
  33903. } ).setLayout( {
  33904. name: 'mx_gradient_vec3_1',
  33905. type: 'vec3',
  33906. inputs: [
  33907. { name: 'hash', type: 'uvec3' },
  33908. { name: 'x', type: 'float' },
  33909. { name: 'y', type: 'float' },
  33910. { name: 'z', type: 'float' }
  33911. ]
  33912. } );
  33913. const mx_gradient_vec3 = /*#__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  33914. const mx_gradient_scale2d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33915. const v = float( v_immutable ).toVar();
  33916. return mul( 0.6616, v );
  33917. } ).setLayout( {
  33918. name: 'mx_gradient_scale2d_0',
  33919. type: 'float',
  33920. inputs: [
  33921. { name: 'v', type: 'float' }
  33922. ]
  33923. } );
  33924. const mx_gradient_scale3d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33925. const v = float( v_immutable ).toVar();
  33926. return mul( 0.9820, v );
  33927. } ).setLayout( {
  33928. name: 'mx_gradient_scale3d_0',
  33929. type: 'float',
  33930. inputs: [
  33931. { name: 'v', type: 'float' }
  33932. ]
  33933. } );
  33934. const mx_gradient_scale2d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33935. const v = vec3( v_immutable ).toVar();
  33936. return mul( 0.6616, v );
  33937. } ).setLayout( {
  33938. name: 'mx_gradient_scale2d_1',
  33939. type: 'vec3',
  33940. inputs: [
  33941. { name: 'v', type: 'vec3' }
  33942. ]
  33943. } );
  33944. const mx_gradient_scale2d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  33945. const mx_gradient_scale3d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33946. const v = vec3( v_immutable ).toVar();
  33947. return mul( 0.9820, v );
  33948. } ).setLayout( {
  33949. name: 'mx_gradient_scale3d_1',
  33950. type: 'vec3',
  33951. inputs: [
  33952. { name: 'v', type: 'vec3' }
  33953. ]
  33954. } );
  33955. const mx_gradient_scale3d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  33956. const mx_rotl32 = /*#__PURE__*/ tslFn( ( [ x_immutable, k_immutable ] ) => {
  33957. const k = int( k_immutable ).toVar();
  33958. const x = uint( x_immutable ).toVar();
  33959. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  33960. } ).setLayout( {
  33961. name: 'mx_rotl32',
  33962. type: 'uint',
  33963. inputs: [
  33964. { name: 'x', type: 'uint' },
  33965. { name: 'k', type: 'int' }
  33966. ]
  33967. } );
  33968. const mx_bjmix = /*#__PURE__*/ tslFn( ( [ a, b, c ] ) => {
  33969. a.subAssign( c );
  33970. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  33971. c.addAssign( b );
  33972. b.subAssign( a );
  33973. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  33974. a.addAssign( c );
  33975. c.subAssign( b );
  33976. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  33977. b.addAssign( a );
  33978. a.subAssign( c );
  33979. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  33980. c.addAssign( b );
  33981. b.subAssign( a );
  33982. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  33983. a.addAssign( c );
  33984. c.subAssign( b );
  33985. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  33986. b.addAssign( a );
  33987. } );
  33988. const mx_bjfinal = /*#__PURE__*/ tslFn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  33989. const c = uint( c_immutable ).toVar();
  33990. const b = uint( b_immutable ).toVar();
  33991. const a = uint( a_immutable ).toVar();
  33992. c.bitXorAssign( b );
  33993. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  33994. a.bitXorAssign( c );
  33995. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  33996. b.bitXorAssign( a );
  33997. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  33998. c.bitXorAssign( b );
  33999. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  34000. a.bitXorAssign( c );
  34001. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  34002. b.bitXorAssign( a );
  34003. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  34004. c.bitXorAssign( b );
  34005. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  34006. return c;
  34007. } ).setLayout( {
  34008. name: 'mx_bjfinal',
  34009. type: 'uint',
  34010. inputs: [
  34011. { name: 'a', type: 'uint' },
  34012. { name: 'b', type: 'uint' },
  34013. { name: 'c', type: 'uint' }
  34014. ]
  34015. } );
  34016. const mx_bits_to_01 = /*#__PURE__*/ tslFn( ( [ bits_immutable ] ) => {
  34017. const bits = uint( bits_immutable ).toVar();
  34018. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  34019. } ).setLayout( {
  34020. name: 'mx_bits_to_01',
  34021. type: 'float',
  34022. inputs: [
  34023. { name: 'bits', type: 'uint' }
  34024. ]
  34025. } );
  34026. const mx_fade = /*#__PURE__*/ tslFn( ( [ t_immutable ] ) => {
  34027. const t = float( t_immutable ).toVar();
  34028. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  34029. } ).setLayout( {
  34030. name: 'mx_fade',
  34031. type: 'float',
  34032. inputs: [
  34033. { name: 't', type: 'float' }
  34034. ]
  34035. } );
  34036. const mx_hash_int_0 = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  34037. const x = int( x_immutable ).toVar();
  34038. const len = uint( uint( 1 ) ).toVar();
  34039. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  34040. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  34041. } ).setLayout( {
  34042. name: 'mx_hash_int_0',
  34043. type: 'uint',
  34044. inputs: [
  34045. { name: 'x', type: 'int' }
  34046. ]
  34047. } );
  34048. const mx_hash_int_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  34049. const y = int( y_immutable ).toVar();
  34050. const x = int( x_immutable ).toVar();
  34051. const len = uint( uint( 2 ) ).toVar();
  34052. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34053. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34054. a.addAssign( uint( x ) );
  34055. b.addAssign( uint( y ) );
  34056. return mx_bjfinal( a, b, c );
  34057. } ).setLayout( {
  34058. name: 'mx_hash_int_1',
  34059. type: 'uint',
  34060. inputs: [
  34061. { name: 'x', type: 'int' },
  34062. { name: 'y', type: 'int' }
  34063. ]
  34064. } );
  34065. const mx_hash_int_2 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34066. const z = int( z_immutable ).toVar();
  34067. const y = int( y_immutable ).toVar();
  34068. const x = int( x_immutable ).toVar();
  34069. const len = uint( uint( 3 ) ).toVar();
  34070. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34071. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34072. a.addAssign( uint( x ) );
  34073. b.addAssign( uint( y ) );
  34074. c.addAssign( uint( z ) );
  34075. return mx_bjfinal( a, b, c );
  34076. } ).setLayout( {
  34077. name: 'mx_hash_int_2',
  34078. type: 'uint',
  34079. inputs: [
  34080. { name: 'x', type: 'int' },
  34081. { name: 'y', type: 'int' },
  34082. { name: 'z', type: 'int' }
  34083. ]
  34084. } );
  34085. const mx_hash_int_3 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  34086. const xx = int( xx_immutable ).toVar();
  34087. const z = int( z_immutable ).toVar();
  34088. const y = int( y_immutable ).toVar();
  34089. const x = int( x_immutable ).toVar();
  34090. const len = uint( uint( 4 ) ).toVar();
  34091. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34092. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34093. a.addAssign( uint( x ) );
  34094. b.addAssign( uint( y ) );
  34095. c.addAssign( uint( z ) );
  34096. mx_bjmix( a, b, c );
  34097. a.addAssign( uint( xx ) );
  34098. return mx_bjfinal( a, b, c );
  34099. } ).setLayout( {
  34100. name: 'mx_hash_int_3',
  34101. type: 'uint',
  34102. inputs: [
  34103. { name: 'x', type: 'int' },
  34104. { name: 'y', type: 'int' },
  34105. { name: 'z', type: 'int' },
  34106. { name: 'xx', type: 'int' }
  34107. ]
  34108. } );
  34109. const mx_hash_int_4 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  34110. const yy = int( yy_immutable ).toVar();
  34111. const xx = int( xx_immutable ).toVar();
  34112. const z = int( z_immutable ).toVar();
  34113. const y = int( y_immutable ).toVar();
  34114. const x = int( x_immutable ).toVar();
  34115. const len = uint( uint( 5 ) ).toVar();
  34116. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34117. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34118. a.addAssign( uint( x ) );
  34119. b.addAssign( uint( y ) );
  34120. c.addAssign( uint( z ) );
  34121. mx_bjmix( a, b, c );
  34122. a.addAssign( uint( xx ) );
  34123. b.addAssign( uint( yy ) );
  34124. return mx_bjfinal( a, b, c );
  34125. } ).setLayout( {
  34126. name: 'mx_hash_int_4',
  34127. type: 'uint',
  34128. inputs: [
  34129. { name: 'x', type: 'int' },
  34130. { name: 'y', type: 'int' },
  34131. { name: 'z', type: 'int' },
  34132. { name: 'xx', type: 'int' },
  34133. { name: 'yy', type: 'int' }
  34134. ]
  34135. } );
  34136. 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 ] );
  34137. const mx_hash_vec3_0 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  34138. const y = int( y_immutable ).toVar();
  34139. const x = int( x_immutable ).toVar();
  34140. const h = uint( mx_hash_int( x, y ) ).toVar();
  34141. const result = uvec3().toVar();
  34142. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34143. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34144. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34145. return result;
  34146. } ).setLayout( {
  34147. name: 'mx_hash_vec3_0',
  34148. type: 'uvec3',
  34149. inputs: [
  34150. { name: 'x', type: 'int' },
  34151. { name: 'y', type: 'int' }
  34152. ]
  34153. } );
  34154. const mx_hash_vec3_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34155. const z = int( z_immutable ).toVar();
  34156. const y = int( y_immutable ).toVar();
  34157. const x = int( x_immutable ).toVar();
  34158. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  34159. const result = uvec3().toVar();
  34160. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34161. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34162. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34163. return result;
  34164. } ).setLayout( {
  34165. name: 'mx_hash_vec3_1',
  34166. type: 'uvec3',
  34167. inputs: [
  34168. { name: 'x', type: 'int' },
  34169. { name: 'y', type: 'int' },
  34170. { name: 'z', type: 'int' }
  34171. ]
  34172. } );
  34173. const mx_hash_vec3 = /*#__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  34174. const mx_perlin_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34175. const p = vec2( p_immutable ).toVar();
  34176. const X = int().toVar(), Y = int().toVar();
  34177. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34178. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34179. const u = float( mx_fade( fx ) ).toVar();
  34180. const v = float( mx_fade( fy ) ).toVar();
  34181. 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();
  34182. return mx_gradient_scale2d( result );
  34183. } ).setLayout( {
  34184. name: 'mx_perlin_noise_float_0',
  34185. type: 'float',
  34186. inputs: [
  34187. { name: 'p', type: 'vec2' }
  34188. ]
  34189. } );
  34190. const mx_perlin_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34191. const p = vec3( p_immutable ).toVar();
  34192. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34193. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34194. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34195. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34196. const u = float( mx_fade( fx ) ).toVar();
  34197. const v = float( mx_fade( fy ) ).toVar();
  34198. const w = float( mx_fade( fz ) ).toVar();
  34199. 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();
  34200. return mx_gradient_scale3d( result );
  34201. } ).setLayout( {
  34202. name: 'mx_perlin_noise_float_1',
  34203. type: 'float',
  34204. inputs: [
  34205. { name: 'p', type: 'vec3' }
  34206. ]
  34207. } );
  34208. const mx_perlin_noise_float = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  34209. const mx_perlin_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34210. const p = vec2( p_immutable ).toVar();
  34211. const X = int().toVar(), Y = int().toVar();
  34212. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34213. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34214. const u = float( mx_fade( fx ) ).toVar();
  34215. const v = float( mx_fade( fy ) ).toVar();
  34216. 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();
  34217. return mx_gradient_scale2d( result );
  34218. } ).setLayout( {
  34219. name: 'mx_perlin_noise_vec3_0',
  34220. type: 'vec3',
  34221. inputs: [
  34222. { name: 'p', type: 'vec2' }
  34223. ]
  34224. } );
  34225. const mx_perlin_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34226. const p = vec3( p_immutable ).toVar();
  34227. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34228. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34229. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34230. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34231. const u = float( mx_fade( fx ) ).toVar();
  34232. const v = float( mx_fade( fy ) ).toVar();
  34233. const w = float( mx_fade( fz ) ).toVar();
  34234. 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();
  34235. return mx_gradient_scale3d( result );
  34236. } ).setLayout( {
  34237. name: 'mx_perlin_noise_vec3_1',
  34238. type: 'vec3',
  34239. inputs: [
  34240. { name: 'p', type: 'vec3' }
  34241. ]
  34242. } );
  34243. const mx_perlin_noise_vec3 = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  34244. const mx_cell_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34245. const p = float( p_immutable ).toVar();
  34246. const ix = int( mx_floor( p ) ).toVar();
  34247. return mx_bits_to_01( mx_hash_int( ix ) );
  34248. } ).setLayout( {
  34249. name: 'mx_cell_noise_float_0',
  34250. type: 'float',
  34251. inputs: [
  34252. { name: 'p', type: 'float' }
  34253. ]
  34254. } );
  34255. const mx_cell_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34256. const p = vec2( p_immutable ).toVar();
  34257. const ix = int( mx_floor( p.x ) ).toVar();
  34258. const iy = int( mx_floor( p.y ) ).toVar();
  34259. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  34260. } ).setLayout( {
  34261. name: 'mx_cell_noise_float_1',
  34262. type: 'float',
  34263. inputs: [
  34264. { name: 'p', type: 'vec2' }
  34265. ]
  34266. } );
  34267. const mx_cell_noise_float_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34268. const p = vec3( p_immutable ).toVar();
  34269. const ix = int( mx_floor( p.x ) ).toVar();
  34270. const iy = int( mx_floor( p.y ) ).toVar();
  34271. const iz = int( mx_floor( p.z ) ).toVar();
  34272. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  34273. } ).setLayout( {
  34274. name: 'mx_cell_noise_float_2',
  34275. type: 'float',
  34276. inputs: [
  34277. { name: 'p', type: 'vec3' }
  34278. ]
  34279. } );
  34280. const mx_cell_noise_float_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34281. const p = vec4( p_immutable ).toVar();
  34282. const ix = int( mx_floor( p.x ) ).toVar();
  34283. const iy = int( mx_floor( p.y ) ).toVar();
  34284. const iz = int( mx_floor( p.z ) ).toVar();
  34285. const iw = int( mx_floor( p.w ) ).toVar();
  34286. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  34287. } ).setLayout( {
  34288. name: 'mx_cell_noise_float_3',
  34289. type: 'float',
  34290. inputs: [
  34291. { name: 'p', type: 'vec4' }
  34292. ]
  34293. } );
  34294. 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 ] );
  34295. const mx_cell_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34296. const p = float( p_immutable ).toVar();
  34297. const ix = int( mx_floor( p ) ).toVar();
  34298. 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 ) ) ) );
  34299. } ).setLayout( {
  34300. name: 'mx_cell_noise_vec3_0',
  34301. type: 'vec3',
  34302. inputs: [
  34303. { name: 'p', type: 'float' }
  34304. ]
  34305. } );
  34306. const mx_cell_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34307. const p = vec2( p_immutable ).toVar();
  34308. const ix = int( mx_floor( p.x ) ).toVar();
  34309. const iy = int( mx_floor( p.y ) ).toVar();
  34310. 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 ) ) ) );
  34311. } ).setLayout( {
  34312. name: 'mx_cell_noise_vec3_1',
  34313. type: 'vec3',
  34314. inputs: [
  34315. { name: 'p', type: 'vec2' }
  34316. ]
  34317. } );
  34318. const mx_cell_noise_vec3_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34319. const p = vec3( p_immutable ).toVar();
  34320. const ix = int( mx_floor( p.x ) ).toVar();
  34321. const iy = int( mx_floor( p.y ) ).toVar();
  34322. const iz = int( mx_floor( p.z ) ).toVar();
  34323. 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 ) ) ) );
  34324. } ).setLayout( {
  34325. name: 'mx_cell_noise_vec3_2',
  34326. type: 'vec3',
  34327. inputs: [
  34328. { name: 'p', type: 'vec3' }
  34329. ]
  34330. } );
  34331. const mx_cell_noise_vec3_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34332. const p = vec4( p_immutable ).toVar();
  34333. const ix = int( mx_floor( p.x ) ).toVar();
  34334. const iy = int( mx_floor( p.y ) ).toVar();
  34335. const iz = int( mx_floor( p.z ) ).toVar();
  34336. const iw = int( mx_floor( p.w ) ).toVar();
  34337. 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 ) ) ) );
  34338. } ).setLayout( {
  34339. name: 'mx_cell_noise_vec3_3',
  34340. type: 'vec3',
  34341. inputs: [
  34342. { name: 'p', type: 'vec4' }
  34343. ]
  34344. } );
  34345. 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 ] );
  34346. const mx_fractal_noise_float$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34347. const diminish = float( diminish_immutable ).toVar();
  34348. const lacunarity = float( lacunarity_immutable ).toVar();
  34349. const octaves = int( octaves_immutable ).toVar();
  34350. const p = vec3( p_immutable ).toVar();
  34351. const result = float( 0.0 ).toVar();
  34352. const amplitude = float( 1.0 ).toVar();
  34353. loop( octaves, () => {
  34354. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  34355. amplitude.mulAssign( diminish );
  34356. p.mulAssign( lacunarity );
  34357. } );
  34358. return result;
  34359. } ).setLayout( {
  34360. name: 'mx_fractal_noise_float',
  34361. type: 'float',
  34362. inputs: [
  34363. { name: 'p', type: 'vec3' },
  34364. { name: 'octaves', type: 'int' },
  34365. { name: 'lacunarity', type: 'float' },
  34366. { name: 'diminish', type: 'float' }
  34367. ]
  34368. } );
  34369. const mx_fractal_noise_vec3$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34370. const diminish = float( diminish_immutable ).toVar();
  34371. const lacunarity = float( lacunarity_immutable ).toVar();
  34372. const octaves = int( octaves_immutable ).toVar();
  34373. const p = vec3( p_immutable ).toVar();
  34374. const result = vec3( 0.0 ).toVar();
  34375. const amplitude = float( 1.0 ).toVar();
  34376. loop( octaves, () => {
  34377. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  34378. amplitude.mulAssign( diminish );
  34379. p.mulAssign( lacunarity );
  34380. } );
  34381. return result;
  34382. } ).setLayout( {
  34383. name: 'mx_fractal_noise_vec3',
  34384. type: 'vec3',
  34385. inputs: [
  34386. { name: 'p', type: 'vec3' },
  34387. { name: 'octaves', type: 'int' },
  34388. { name: 'lacunarity', type: 'float' },
  34389. { name: 'diminish', type: 'float' }
  34390. ]
  34391. } );
  34392. const mx_fractal_noise_vec2$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34393. const diminish = float( diminish_immutable ).toVar();
  34394. const lacunarity = float( lacunarity_immutable ).toVar();
  34395. const octaves = int( octaves_immutable ).toVar();
  34396. const p = vec3( p_immutable ).toVar();
  34397. 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 ) );
  34398. } ).setLayout( {
  34399. name: 'mx_fractal_noise_vec2',
  34400. type: 'vec2',
  34401. inputs: [
  34402. { name: 'p', type: 'vec3' },
  34403. { name: 'octaves', type: 'int' },
  34404. { name: 'lacunarity', type: 'float' },
  34405. { name: 'diminish', type: 'float' }
  34406. ]
  34407. } );
  34408. const mx_fractal_noise_vec4$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34409. const diminish = float( diminish_immutable ).toVar();
  34410. const lacunarity = float( lacunarity_immutable ).toVar();
  34411. const octaves = int( octaves_immutable ).toVar();
  34412. const p = vec3( p_immutable ).toVar();
  34413. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  34414. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  34415. return vec4( c, f );
  34416. } ).setLayout( {
  34417. name: 'mx_fractal_noise_vec4',
  34418. type: 'vec4',
  34419. inputs: [
  34420. { name: 'p', type: 'vec3' },
  34421. { name: 'octaves', type: 'int' },
  34422. { name: 'lacunarity', type: 'float' },
  34423. { name: 'diminish', type: 'float' }
  34424. ]
  34425. } );
  34426. const mx_worley_distance_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34427. const metric = int( metric_immutable ).toVar();
  34428. const jitter = float( jitter_immutable ).toVar();
  34429. const yoff = int( yoff_immutable ).toVar();
  34430. const xoff = int( xoff_immutable ).toVar();
  34431. const y = int( y_immutable ).toVar();
  34432. const x = int( x_immutable ).toVar();
  34433. const p = vec2( p_immutable ).toVar();
  34434. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  34435. const off = vec2( tmp.x, tmp.y ).toVar();
  34436. off.subAssign( 0.5 );
  34437. off.mulAssign( jitter );
  34438. off.addAssign( 0.5 );
  34439. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  34440. const diff = vec2( cellpos.sub( p ) ).toVar();
  34441. If( metric.equal( int( 2 ) ), () => {
  34442. return abs( diff.x ).add( abs( diff.y ) );
  34443. } );
  34444. If( metric.equal( int( 3 ) ), () => {
  34445. return max$1( abs( diff.x ), abs( diff.y ) );
  34446. } );
  34447. return dot( diff, diff );
  34448. } ).setLayout( {
  34449. name: 'mx_worley_distance_0',
  34450. type: 'float',
  34451. inputs: [
  34452. { name: 'p', type: 'vec2' },
  34453. { name: 'x', type: 'int' },
  34454. { name: 'y', type: 'int' },
  34455. { name: 'xoff', type: 'int' },
  34456. { name: 'yoff', type: 'int' },
  34457. { name: 'jitter', type: 'float' },
  34458. { name: 'metric', type: 'int' }
  34459. ]
  34460. } );
  34461. const mx_worley_distance_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34462. const metric = int( metric_immutable ).toVar();
  34463. const jitter = float( jitter_immutable ).toVar();
  34464. const zoff = int( zoff_immutable ).toVar();
  34465. const yoff = int( yoff_immutable ).toVar();
  34466. const xoff = int( xoff_immutable ).toVar();
  34467. const z = int( z_immutable ).toVar();
  34468. const y = int( y_immutable ).toVar();
  34469. const x = int( x_immutable ).toVar();
  34470. const p = vec3( p_immutable ).toVar();
  34471. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  34472. off.subAssign( 0.5 );
  34473. off.mulAssign( jitter );
  34474. off.addAssign( 0.5 );
  34475. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  34476. const diff = vec3( cellpos.sub( p ) ).toVar();
  34477. If( metric.equal( int( 2 ) ), () => {
  34478. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  34479. } );
  34480. If( metric.equal( int( 3 ) ), () => {
  34481. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  34482. } );
  34483. return dot( diff, diff );
  34484. } ).setLayout( {
  34485. name: 'mx_worley_distance_1',
  34486. type: 'float',
  34487. inputs: [
  34488. { name: 'p', type: 'vec3' },
  34489. { name: 'x', type: 'int' },
  34490. { name: 'y', type: 'int' },
  34491. { name: 'z', type: 'int' },
  34492. { name: 'xoff', type: 'int' },
  34493. { name: 'yoff', type: 'int' },
  34494. { name: 'zoff', type: 'int' },
  34495. { name: 'jitter', type: 'float' },
  34496. { name: 'metric', type: 'int' }
  34497. ]
  34498. } );
  34499. const mx_worley_distance = /*#__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  34500. const mx_worley_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34501. const metric = int( metric_immutable ).toVar();
  34502. const jitter = float( jitter_immutable ).toVar();
  34503. const p = vec2( p_immutable ).toVar();
  34504. const X = int().toVar(), Y = int().toVar();
  34505. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34506. const sqdist = float( 1e6 ).toVar();
  34507. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34508. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34509. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34510. sqdist.assign( min$1( sqdist, dist ) );
  34511. } );
  34512. } );
  34513. If( metric.equal( int( 0 ) ), () => {
  34514. sqdist.assign( sqrt( sqdist ) );
  34515. } );
  34516. return sqdist;
  34517. } ).setLayout( {
  34518. name: 'mx_worley_noise_float_0',
  34519. type: 'float',
  34520. inputs: [
  34521. { name: 'p', type: 'vec2' },
  34522. { name: 'jitter', type: 'float' },
  34523. { name: 'metric', type: 'int' }
  34524. ]
  34525. } );
  34526. const mx_worley_noise_vec2_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34527. const metric = int( metric_immutable ).toVar();
  34528. const jitter = float( jitter_immutable ).toVar();
  34529. const p = vec2( p_immutable ).toVar();
  34530. const X = int().toVar(), Y = int().toVar();
  34531. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34532. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34533. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34534. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34535. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34536. If( dist.lessThan( sqdist.x ), () => {
  34537. sqdist.y.assign( sqdist.x );
  34538. sqdist.x.assign( dist );
  34539. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34540. sqdist.y.assign( dist );
  34541. } );
  34542. } );
  34543. } );
  34544. If( metric.equal( int( 0 ) ), () => {
  34545. sqdist.assign( sqrt( sqdist ) );
  34546. } );
  34547. return sqdist;
  34548. } ).setLayout( {
  34549. name: 'mx_worley_noise_vec2_0',
  34550. type: 'vec2',
  34551. inputs: [
  34552. { name: 'p', type: 'vec2' },
  34553. { name: 'jitter', type: 'float' },
  34554. { name: 'metric', type: 'int' }
  34555. ]
  34556. } );
  34557. const mx_worley_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34558. const metric = int( metric_immutable ).toVar();
  34559. const jitter = float( jitter_immutable ).toVar();
  34560. const p = vec2( p_immutable ).toVar();
  34561. const X = int().toVar(), Y = int().toVar();
  34562. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34563. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34564. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34565. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34566. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34567. If( dist.lessThan( sqdist.x ), () => {
  34568. sqdist.z.assign( sqdist.y );
  34569. sqdist.y.assign( sqdist.x );
  34570. sqdist.x.assign( dist );
  34571. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34572. sqdist.z.assign( sqdist.y );
  34573. sqdist.y.assign( dist );
  34574. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34575. sqdist.z.assign( dist );
  34576. } );
  34577. } );
  34578. } );
  34579. If( metric.equal( int( 0 ) ), () => {
  34580. sqdist.assign( sqrt( sqdist ) );
  34581. } );
  34582. return sqdist;
  34583. } ).setLayout( {
  34584. name: 'mx_worley_noise_vec3_0',
  34585. type: 'vec3',
  34586. inputs: [
  34587. { name: 'p', type: 'vec2' },
  34588. { name: 'jitter', type: 'float' },
  34589. { name: 'metric', type: 'int' }
  34590. ]
  34591. } );
  34592. const mx_worley_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34593. const metric = int( metric_immutable ).toVar();
  34594. const jitter = float( jitter_immutable ).toVar();
  34595. const p = vec3( p_immutable ).toVar();
  34596. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34597. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34598. const sqdist = float( 1e6 ).toVar();
  34599. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34600. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34601. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34602. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34603. sqdist.assign( min$1( sqdist, dist ) );
  34604. } );
  34605. } );
  34606. } );
  34607. If( metric.equal( int( 0 ) ), () => {
  34608. sqdist.assign( sqrt( sqdist ) );
  34609. } );
  34610. return sqdist;
  34611. } ).setLayout( {
  34612. name: 'mx_worley_noise_float_1',
  34613. type: 'float',
  34614. inputs: [
  34615. { name: 'p', type: 'vec3' },
  34616. { name: 'jitter', type: 'float' },
  34617. { name: 'metric', type: 'int' }
  34618. ]
  34619. } );
  34620. const mx_worley_noise_float$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  34621. const mx_worley_noise_vec2_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34622. const metric = int( metric_immutable ).toVar();
  34623. const jitter = float( jitter_immutable ).toVar();
  34624. const p = vec3( p_immutable ).toVar();
  34625. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34626. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34627. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34628. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34629. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34630. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34631. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34632. If( dist.lessThan( sqdist.x ), () => {
  34633. sqdist.y.assign( sqdist.x );
  34634. sqdist.x.assign( dist );
  34635. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34636. sqdist.y.assign( dist );
  34637. } );
  34638. } );
  34639. } );
  34640. } );
  34641. If( metric.equal( int( 0 ) ), () => {
  34642. sqdist.assign( sqrt( sqdist ) );
  34643. } );
  34644. return sqdist;
  34645. } ).setLayout( {
  34646. name: 'mx_worley_noise_vec2_1',
  34647. type: 'vec2',
  34648. inputs: [
  34649. { name: 'p', type: 'vec3' },
  34650. { name: 'jitter', type: 'float' },
  34651. { name: 'metric', type: 'int' }
  34652. ]
  34653. } );
  34654. const mx_worley_noise_vec2$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  34655. const mx_worley_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34656. const metric = int( metric_immutable ).toVar();
  34657. const jitter = float( jitter_immutable ).toVar();
  34658. const p = vec3( p_immutable ).toVar();
  34659. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34660. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34661. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34662. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34663. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34664. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34665. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34666. If( dist.lessThan( sqdist.x ), () => {
  34667. sqdist.z.assign( sqdist.y );
  34668. sqdist.y.assign( sqdist.x );
  34669. sqdist.x.assign( dist );
  34670. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34671. sqdist.z.assign( sqdist.y );
  34672. sqdist.y.assign( dist );
  34673. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34674. sqdist.z.assign( dist );
  34675. } );
  34676. } );
  34677. } );
  34678. } );
  34679. If( metric.equal( int( 0 ) ), () => {
  34680. sqdist.assign( sqrt( sqdist ) );
  34681. } );
  34682. return sqdist;
  34683. } ).setLayout( {
  34684. name: 'mx_worley_noise_vec3_1',
  34685. type: 'vec3',
  34686. inputs: [
  34687. { name: 'p', type: 'vec3' },
  34688. { name: 'jitter', type: 'float' },
  34689. { name: 'metric', type: 'int' }
  34690. ]
  34691. } );
  34692. const mx_worley_noise_vec3$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34693. // Three.js Transpiler
  34694. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34695. const mx_hsvtorgb = /*#__PURE__*/ tslFn( ( [ hsv_immutable ] ) => {
  34696. const hsv = vec3( hsv_immutable ).toVar();
  34697. const h = float( hsv.x ).toVar();
  34698. const s = float( hsv.y ).toVar();
  34699. const v = float( hsv.z ).toVar();
  34700. If( s.lessThan( 0.0001 ), () => {
  34701. return vec3( v, v, v );
  34702. } ).else( () => {
  34703. h.assign( mul( 6.0, h.sub( floor( h ) ) ) );
  34704. const hi = int( trunc( h ) ).toVar();
  34705. const f = float( h.sub( float( hi ) ) ).toVar();
  34706. const p = float( v.mul( sub( 1.0, s ) ) ).toVar();
  34707. const q = float( v.mul( sub( 1.0, s.mul( f ) ) ) ).toVar();
  34708. const t = float( v.mul( sub( 1.0, s.mul( sub( 1.0, f ) ) ) ) ).toVar();
  34709. If( hi.equal( int( 0 ) ), () => {
  34710. return vec3( v, t, p );
  34711. } ).elseif( hi.equal( int( 1 ) ), () => {
  34712. return vec3( q, v, p );
  34713. } ).elseif( hi.equal( int( 2 ) ), () => {
  34714. return vec3( p, v, t );
  34715. } ).elseif( hi.equal( int( 3 ) ), () => {
  34716. return vec3( p, q, v );
  34717. } ).elseif( hi.equal( int( 4 ) ), () => {
  34718. return vec3( t, p, v );
  34719. } );
  34720. return vec3( v, p, q );
  34721. } );
  34722. } ).setLayout( {
  34723. name: 'mx_hsvtorgb',
  34724. type: 'vec3',
  34725. inputs: [
  34726. { name: 'hsv', type: 'vec3' }
  34727. ]
  34728. } );
  34729. const mx_rgbtohsv = /*#__PURE__*/ tslFn( ( [ c_immutable ] ) => {
  34730. const c = vec3( c_immutable ).toVar();
  34731. const r = float( c.x ).toVar();
  34732. const g = float( c.y ).toVar();
  34733. const b = float( c.z ).toVar();
  34734. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34735. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34736. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34737. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34738. v.assign( maxcomp );
  34739. If( maxcomp.greaterThan( 0.0 ), () => {
  34740. s.assign( delta.div( maxcomp ) );
  34741. } ).else( () => {
  34742. s.assign( 0.0 );
  34743. } );
  34744. If( s.lessThanEqual( 0.0 ), () => {
  34745. h.assign( 0.0 );
  34746. } ).else( () => {
  34747. If( r.greaterThanEqual( maxcomp ), () => {
  34748. h.assign( g.sub( b ).div( delta ) );
  34749. } ).elseif( g.greaterThanEqual( maxcomp ), () => {
  34750. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34751. } ).else( () => {
  34752. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34753. } );
  34754. h.mulAssign( 1.0 / 6.0 );
  34755. If( h.lessThan( 0.0 ), () => {
  34756. h.addAssign( 1.0 );
  34757. } );
  34758. } );
  34759. return vec3( h, s, v );
  34760. } ).setLayout( {
  34761. name: 'mx_rgbtohsv',
  34762. type: 'vec3',
  34763. inputs: [
  34764. { name: 'c', type: 'vec3' }
  34765. ]
  34766. } );
  34767. // Three.js Transpiler
  34768. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  34769. const mx_srgb_texture_to_lin_rec709 = /*#__PURE__*/ tslFn( ( [ color_immutable ] ) => {
  34770. const color = vec3( color_immutable ).toVar();
  34771. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  34772. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  34773. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  34774. return mix( linSeg, powSeg, isAbove );
  34775. } ).setLayout( {
  34776. name: 'mx_srgb_texture_to_lin_rec709',
  34777. type: 'vec3',
  34778. inputs: [
  34779. { name: 'color', type: 'vec3' }
  34780. ]
  34781. } );
  34782. const mx_aastep = ( threshold, value ) => {
  34783. threshold = float( threshold );
  34784. value = float( value );
  34785. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  34786. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  34787. };
  34788. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  34789. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  34790. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  34791. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  34792. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  34793. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  34794. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  34795. const mx_safepower = ( in1, in2 = 1 ) => {
  34796. in1 = float( in1 );
  34797. return in1.abs().pow( in2 ).mul( in1.sign() );
  34798. };
  34799. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  34800. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34801. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34802. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34803. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  34804. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  34805. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  34806. return noise_vec4.mul( amplitude ).add( pivot );
  34807. };
  34808. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34809. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34810. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34811. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  34812. 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 );
  34813. 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 );
  34814. 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 );
  34815. 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 );
  34816. function painterSortStable( a, b ) {
  34817. if ( a.groupOrder !== b.groupOrder ) {
  34818. return a.groupOrder - b.groupOrder;
  34819. } else if ( a.renderOrder !== b.renderOrder ) {
  34820. return a.renderOrder - b.renderOrder;
  34821. } else if ( a.material.id !== b.material.id ) {
  34822. return a.material.id - b.material.id;
  34823. } else if ( a.z !== b.z ) {
  34824. return a.z - b.z;
  34825. } else {
  34826. return a.id - b.id;
  34827. }
  34828. }
  34829. function reversePainterSortStable( a, b ) {
  34830. if ( a.groupOrder !== b.groupOrder ) {
  34831. return a.groupOrder - b.groupOrder;
  34832. } else if ( a.renderOrder !== b.renderOrder ) {
  34833. return a.renderOrder - b.renderOrder;
  34834. } else if ( a.z !== b.z ) {
  34835. return b.z - a.z;
  34836. } else {
  34837. return a.id - b.id;
  34838. }
  34839. }
  34840. class RenderList {
  34841. constructor() {
  34842. this.renderItems = [];
  34843. this.renderItemsIndex = 0;
  34844. this.opaque = [];
  34845. this.transparent = [];
  34846. this.bundles = [];
  34847. this.lightsNode = new LightsNode( [] );
  34848. this.lightsArray = [];
  34849. this.occlusionQueryCount = 0;
  34850. }
  34851. begin() {
  34852. this.renderItemsIndex = 0;
  34853. this.opaque.length = 0;
  34854. this.transparent.length = 0;
  34855. this.bundles.length = 0;
  34856. this.lightsArray.length = 0;
  34857. this.occlusionQueryCount = 0;
  34858. return this;
  34859. }
  34860. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  34861. let renderItem = this.renderItems[ this.renderItemsIndex ];
  34862. if ( renderItem === undefined ) {
  34863. renderItem = {
  34864. id: object.id,
  34865. object: object,
  34866. geometry: geometry,
  34867. material: material,
  34868. groupOrder: groupOrder,
  34869. renderOrder: object.renderOrder,
  34870. z: z,
  34871. group: group
  34872. };
  34873. this.renderItems[ this.renderItemsIndex ] = renderItem;
  34874. } else {
  34875. renderItem.id = object.id;
  34876. renderItem.object = object;
  34877. renderItem.geometry = geometry;
  34878. renderItem.material = material;
  34879. renderItem.groupOrder = groupOrder;
  34880. renderItem.renderOrder = object.renderOrder;
  34881. renderItem.z = z;
  34882. renderItem.group = group;
  34883. }
  34884. this.renderItemsIndex ++;
  34885. return renderItem;
  34886. }
  34887. push( object, geometry, material, groupOrder, z, group ) {
  34888. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  34889. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  34890. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  34891. }
  34892. unshift( object, geometry, material, groupOrder, z, group ) {
  34893. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  34894. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  34895. }
  34896. pushBundle( group ) {
  34897. this.bundles.push( group );
  34898. }
  34899. pushLight( light ) {
  34900. this.lightsArray.push( light );
  34901. }
  34902. getLightsNode() {
  34903. return this.lightsNode.fromLights( this.lightsArray );
  34904. }
  34905. sort( customOpaqueSort, customTransparentSort ) {
  34906. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  34907. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  34908. }
  34909. finish() {
  34910. // update lights
  34911. this.lightsNode.fromLights( this.lightsArray );
  34912. // Clear references from inactive renderItems in the list
  34913. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  34914. const renderItem = this.renderItems[ i ];
  34915. if ( renderItem.id === null ) break;
  34916. renderItem.id = null;
  34917. renderItem.object = null;
  34918. renderItem.geometry = null;
  34919. renderItem.material = null;
  34920. renderItem.groupOrder = null;
  34921. renderItem.renderOrder = null;
  34922. renderItem.z = null;
  34923. renderItem.group = null;
  34924. }
  34925. }
  34926. }
  34927. class RenderLists {
  34928. constructor() {
  34929. this.lists = new ChainMap();
  34930. }
  34931. get( scene, camera ) {
  34932. const lists = this.lists;
  34933. const keys = [ scene, camera ];
  34934. let list = lists.get( keys );
  34935. if ( list === undefined ) {
  34936. list = new RenderList();
  34937. lists.set( keys, list );
  34938. }
  34939. return list;
  34940. }
  34941. dispose() {
  34942. this.lists = new ChainMap();
  34943. }
  34944. }
  34945. let id$2 = 0;
  34946. class RenderContext {
  34947. constructor() {
  34948. this.id = id$2 ++;
  34949. this.color = true;
  34950. this.clearColor = true;
  34951. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  34952. this.depth = true;
  34953. this.clearDepth = true;
  34954. this.clearDepthValue = 1;
  34955. this.stencil = false;
  34956. this.clearStencil = true;
  34957. this.clearStencilValue = 1;
  34958. this.viewport = false;
  34959. this.viewportValue = new Vector4();
  34960. this.scissor = false;
  34961. this.scissorValue = new Vector4();
  34962. this.textures = null;
  34963. this.depthTexture = null;
  34964. this.activeCubeFace = 0;
  34965. this.sampleCount = 1;
  34966. this.width = 0;
  34967. this.height = 0;
  34968. this.isRenderContext = true;
  34969. }
  34970. }
  34971. class RenderContexts {
  34972. constructor() {
  34973. this.chainMaps = {};
  34974. }
  34975. get( scene, camera, renderTarget = null ) {
  34976. const chainKey = [ scene, camera ];
  34977. let attachmentState;
  34978. if ( renderTarget === null ) {
  34979. attachmentState = 'default';
  34980. } else {
  34981. const format = renderTarget.texture.format;
  34982. const count = renderTarget.count;
  34983. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  34984. }
  34985. const chainMap = this.getChainMap( attachmentState );
  34986. let renderState = chainMap.get( chainKey );
  34987. if ( renderState === undefined ) {
  34988. renderState = new RenderContext();
  34989. chainMap.set( chainKey, renderState );
  34990. }
  34991. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  34992. return renderState;
  34993. }
  34994. getChainMap( attachmentState ) {
  34995. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  34996. }
  34997. dispose() {
  34998. this.chainMaps = {};
  34999. }
  35000. }
  35001. const _size = new Vector3();
  35002. class Textures extends DataMap {
  35003. constructor( renderer, backend, info ) {
  35004. super();
  35005. this.renderer = renderer;
  35006. this.backend = backend;
  35007. this.info = info;
  35008. }
  35009. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  35010. const renderTargetData = this.get( renderTarget );
  35011. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  35012. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  35013. const texture = renderTarget.texture;
  35014. const textures = renderTarget.textures;
  35015. const size = this.getSize( texture );
  35016. const mipWidth = size.width >> activeMipmapLevel;
  35017. const mipHeight = size.height >> activeMipmapLevel;
  35018. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  35019. let textureNeedsUpdate = false;
  35020. if ( depthTexture === undefined ) {
  35021. depthTexture = new DepthTexture();
  35022. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  35023. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  35024. depthTexture.image.width = mipWidth;
  35025. depthTexture.image.height = mipHeight;
  35026. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  35027. }
  35028. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  35029. textureNeedsUpdate = true;
  35030. depthTexture.needsUpdate = true;
  35031. depthTexture.image.width = mipWidth;
  35032. depthTexture.image.height = mipHeight;
  35033. }
  35034. renderTargetData.width = size.width;
  35035. renderTargetData.height = size.height;
  35036. renderTargetData.textures = textures;
  35037. renderTargetData.depthTexture = depthTexture;
  35038. renderTargetData.depth = renderTarget.depthBuffer;
  35039. renderTargetData.stencil = renderTarget.stencilBuffer;
  35040. renderTargetData.renderTarget = renderTarget;
  35041. if ( renderTargetData.sampleCount !== sampleCount ) {
  35042. textureNeedsUpdate = true;
  35043. depthTexture.needsUpdate = true;
  35044. renderTargetData.sampleCount = sampleCount;
  35045. }
  35046. //
  35047. const options = { sampleCount };
  35048. for ( let i = 0; i < textures.length; i ++ ) {
  35049. const texture = textures[ i ];
  35050. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  35051. this.updateTexture( texture, options );
  35052. }
  35053. this.updateTexture( depthTexture, options );
  35054. // dispose handler
  35055. if ( renderTargetData.initialized !== true ) {
  35056. renderTargetData.initialized = true;
  35057. // dispose
  35058. const onDispose = () => {
  35059. renderTarget.removeEventListener( 'dispose', onDispose );
  35060. if ( textures !== undefined ) {
  35061. for ( let i = 0; i < textures.length; i ++ ) {
  35062. this._destroyTexture( textures[ i ] );
  35063. }
  35064. } else {
  35065. this._destroyTexture( texture );
  35066. }
  35067. this._destroyTexture( depthTexture );
  35068. };
  35069. renderTarget.addEventListener( 'dispose', onDispose );
  35070. }
  35071. }
  35072. updateTexture( texture, options = {} ) {
  35073. const textureData = this.get( texture );
  35074. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  35075. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  35076. const backend = this.backend;
  35077. if ( isRenderTarget && textureData.initialized === true ) {
  35078. // it's an update
  35079. backend.destroySampler( texture );
  35080. backend.destroyTexture( texture );
  35081. }
  35082. //
  35083. if ( texture.isFramebufferTexture ) {
  35084. const renderer = this.renderer;
  35085. const renderTarget = renderer.getRenderTarget();
  35086. if ( renderTarget ) {
  35087. texture.type = renderTarget.texture.type;
  35088. } else {
  35089. texture.type = UnsignedByteType;
  35090. }
  35091. }
  35092. //
  35093. const { width, height, depth } = this.getSize( texture );
  35094. options.width = width;
  35095. options.height = height;
  35096. options.depth = depth;
  35097. options.needsMipmaps = this.needsMipmaps( texture );
  35098. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  35099. //
  35100. if ( isRenderTarget || texture.isStorageTexture === true ) {
  35101. backend.createSampler( texture );
  35102. backend.createTexture( texture, options );
  35103. } else {
  35104. const needsCreate = textureData.initialized !== true;
  35105. if ( needsCreate ) backend.createSampler( texture );
  35106. if ( texture.version > 0 ) {
  35107. const image = texture.image;
  35108. if ( image === undefined ) {
  35109. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  35110. } else if ( image.complete === false ) {
  35111. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  35112. } else {
  35113. if ( texture.images ) {
  35114. const images = [];
  35115. for ( const image of texture.images ) {
  35116. images.push( image );
  35117. }
  35118. options.images = images;
  35119. } else {
  35120. options.image = image;
  35121. }
  35122. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  35123. backend.createTexture( texture, options );
  35124. textureData.isDefaultTexture = false;
  35125. }
  35126. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  35127. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  35128. }
  35129. } else {
  35130. // async update
  35131. backend.createDefaultTexture( texture );
  35132. textureData.isDefaultTexture = true;
  35133. }
  35134. }
  35135. // dispose handler
  35136. if ( textureData.initialized !== true ) {
  35137. textureData.initialized = true;
  35138. //
  35139. this.info.memory.textures ++;
  35140. // dispose
  35141. const onDispose = () => {
  35142. texture.removeEventListener( 'dispose', onDispose );
  35143. this._destroyTexture( texture );
  35144. this.info.memory.textures --;
  35145. };
  35146. texture.addEventListener( 'dispose', onDispose );
  35147. }
  35148. //
  35149. textureData.version = texture.version;
  35150. }
  35151. getSize( texture, target = _size ) {
  35152. let image = texture.images ? texture.images[ 0 ] : texture.image;
  35153. if ( image ) {
  35154. if ( image.image !== undefined ) image = image.image;
  35155. target.width = image.width;
  35156. target.height = image.height;
  35157. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  35158. } else {
  35159. target.width = target.height = target.depth = 1;
  35160. }
  35161. return target;
  35162. }
  35163. getMipLevels( texture, width, height ) {
  35164. let mipLevelCount;
  35165. if ( texture.isCompressedTexture ) {
  35166. mipLevelCount = texture.mipmaps.length;
  35167. } else {
  35168. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  35169. }
  35170. return mipLevelCount;
  35171. }
  35172. needsMipmaps( texture ) {
  35173. if ( this.isEnvironmentTexture( texture ) ) return true;
  35174. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  35175. }
  35176. isEnvironmentTexture( texture ) {
  35177. const mapping = texture.mapping;
  35178. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  35179. }
  35180. _destroyTexture( texture ) {
  35181. this.backend.destroySampler( texture );
  35182. this.backend.destroyTexture( texture );
  35183. this.delete( texture );
  35184. }
  35185. }
  35186. class Color4 extends Color {
  35187. constructor( r, g, b, a = 1 ) {
  35188. super( r, g, b );
  35189. this.a = a;
  35190. }
  35191. set( r, g, b, a = 1 ) {
  35192. this.a = a;
  35193. return super.set( r, g, b );
  35194. }
  35195. copy( color ) {
  35196. if ( color.a !== undefined ) this.a = color.a;
  35197. return super.copy( color );
  35198. }
  35199. clone() {
  35200. return new this.constructor( this.r, this.g, this.b, this.a );
  35201. }
  35202. }
  35203. const _clearColor = new Color4();
  35204. class Background extends DataMap {
  35205. constructor( renderer, nodes ) {
  35206. super();
  35207. this.renderer = renderer;
  35208. this.nodes = nodes;
  35209. }
  35210. update( scene, renderList, renderContext ) {
  35211. const renderer = this.renderer;
  35212. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  35213. let forceClear = false;
  35214. if ( background === null ) {
  35215. // no background settings, use clear color configuration from the renderer
  35216. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  35217. _clearColor.a = renderer._clearColor.a;
  35218. } else if ( background.isColor === true ) {
  35219. // background is an opaque color
  35220. background.getRGB( _clearColor, LinearSRGBColorSpace );
  35221. _clearColor.a = 1;
  35222. forceClear = true;
  35223. } else if ( background.isNode === true ) {
  35224. const sceneData = this.get( scene );
  35225. const backgroundNode = background;
  35226. _clearColor.copy( renderer._clearColor );
  35227. let backgroundMesh = sceneData.backgroundMesh;
  35228. if ( backgroundMesh === undefined ) {
  35229. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  35230. // @TODO: Add Texture2D support using node context
  35231. getUV: () => normalWorld,
  35232. getTextureLevel: () => backgroundBlurriness
  35233. } );
  35234. let viewProj = modelViewProjection();
  35235. viewProj = viewProj.setZ( viewProj.w );
  35236. const nodeMaterial = new NodeMaterial();
  35237. nodeMaterial.side = BackSide;
  35238. nodeMaterial.depthTest = false;
  35239. nodeMaterial.depthWrite = false;
  35240. nodeMaterial.fog = false;
  35241. nodeMaterial.vertexNode = viewProj;
  35242. nodeMaterial.fragmentNode = backgroundMeshNode;
  35243. sceneData.backgroundMeshNode = backgroundMeshNode;
  35244. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  35245. backgroundMesh.frustumCulled = false;
  35246. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  35247. this.matrixWorld.copyPosition( camera.matrixWorld );
  35248. };
  35249. }
  35250. const backgroundCacheKey = backgroundNode.getCacheKey();
  35251. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  35252. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  35253. backgroundMesh.material.needsUpdate = true;
  35254. sceneData.backgroundCacheKey = backgroundCacheKey;
  35255. }
  35256. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  35257. } else {
  35258. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  35259. }
  35260. //
  35261. if ( renderer.autoClear === true || forceClear === true ) {
  35262. _clearColor.multiplyScalar( _clearColor.a );
  35263. const clearColorValue = renderContext.clearColorValue;
  35264. clearColorValue.r = _clearColor.r;
  35265. clearColorValue.g = _clearColor.g;
  35266. clearColorValue.b = _clearColor.b;
  35267. clearColorValue.a = _clearColor.a;
  35268. renderContext.depthClearValue = renderer._clearDepth;
  35269. renderContext.stencilClearValue = renderer._clearStencil;
  35270. renderContext.clearColor = renderer.autoClearColor === true;
  35271. renderContext.clearDepth = renderer.autoClearDepth === true;
  35272. renderContext.clearStencil = renderer.autoClearStencil === true;
  35273. } else {
  35274. renderContext.clearColor = false;
  35275. renderContext.clearDepth = false;
  35276. renderContext.clearStencil = false;
  35277. }
  35278. }
  35279. }
  35280. class NodeBuilderState {
  35281. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, instanceBindGroups = true, transforms = [] ) {
  35282. this.vertexShader = vertexShader;
  35283. this.fragmentShader = fragmentShader;
  35284. this.computeShader = computeShader;
  35285. this.transforms = transforms;
  35286. this.nodeAttributes = nodeAttributes;
  35287. this.bindings = bindings;
  35288. this.updateNodes = updateNodes;
  35289. this.updateBeforeNodes = updateBeforeNodes;
  35290. this.updateAfterNodes = updateAfterNodes;
  35291. this.instanceBindGroups = instanceBindGroups;
  35292. this.usedTimes = 0;
  35293. }
  35294. createBindings() {
  35295. const bindings = [];
  35296. for ( const instanceGroup of this.bindings ) {
  35297. const shared = this.instanceBindGroups && instanceGroup.bindings[ 0 ].groupNode.shared;
  35298. if ( shared !== true ) {
  35299. const bindingsGroup = new BindGroup( instanceGroup.name );
  35300. bindings.push( bindingsGroup );
  35301. for ( const instanceBinding of instanceGroup.bindings ) {
  35302. bindingsGroup.bindings.push( instanceBinding.clone() );
  35303. }
  35304. } else {
  35305. bindings.push( instanceGroup );
  35306. }
  35307. }
  35308. return bindings;
  35309. }
  35310. }
  35311. const outputNodeMap = new WeakMap();
  35312. class Nodes extends DataMap {
  35313. constructor( renderer, backend ) {
  35314. super();
  35315. this.renderer = renderer;
  35316. this.backend = backend;
  35317. this.nodeFrame = new NodeFrame();
  35318. this.nodeBuilderCache = new Map();
  35319. this.callHashCache = new ChainMap();
  35320. this.groupsData = new ChainMap();
  35321. }
  35322. updateGroup( nodeUniformsGroup ) {
  35323. const groupNode = nodeUniformsGroup.groupNode;
  35324. const name = groupNode.name;
  35325. // objectGroup is every updated
  35326. if ( name === objectGroup.name ) return true;
  35327. // renderGroup is updated once per render/compute call
  35328. if ( name === renderGroup.name ) {
  35329. const uniformsGroupData = this.get( nodeUniformsGroup );
  35330. const renderId = this.nodeFrame.renderId;
  35331. if ( uniformsGroupData.renderId !== renderId ) {
  35332. uniformsGroupData.renderId = renderId;
  35333. return true;
  35334. }
  35335. return false;
  35336. }
  35337. // frameGroup is updated once per frame
  35338. if ( name === frameGroup.name ) {
  35339. const uniformsGroupData = this.get( nodeUniformsGroup );
  35340. const frameId = this.nodeFrame.frameId;
  35341. if ( uniformsGroupData.frameId !== frameId ) {
  35342. uniformsGroupData.frameId = frameId;
  35343. return true;
  35344. }
  35345. return false;
  35346. }
  35347. // other groups are updated just when groupNode.needsUpdate is true
  35348. const groupChain = [ groupNode, nodeUniformsGroup ];
  35349. let groupData = this.groupsData.get( groupChain );
  35350. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  35351. if ( groupData.version !== groupNode.version ) {
  35352. groupData.version = groupNode.version;
  35353. return true;
  35354. }
  35355. return false;
  35356. }
  35357. getForRenderCacheKey( renderObject ) {
  35358. return renderObject.initialCacheKey;
  35359. }
  35360. getForRender( renderObject ) {
  35361. const renderObjectData = this.get( renderObject );
  35362. let nodeBuilderState = renderObjectData.nodeBuilderState;
  35363. if ( nodeBuilderState === undefined ) {
  35364. const { nodeBuilderCache } = this;
  35365. const cacheKey = this.getForRenderCacheKey( renderObject );
  35366. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  35367. if ( nodeBuilderState === undefined ) {
  35368. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  35369. nodeBuilder.scene = renderObject.scene;
  35370. nodeBuilder.material = renderObject.material;
  35371. nodeBuilder.camera = renderObject.camera;
  35372. nodeBuilder.context.material = renderObject.material;
  35373. nodeBuilder.lightsNode = renderObject.lightsNode;
  35374. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  35375. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  35376. nodeBuilder.clippingContext = renderObject.clippingContext;
  35377. nodeBuilder.build();
  35378. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35379. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  35380. }
  35381. nodeBuilderState.usedTimes ++;
  35382. renderObjectData.nodeBuilderState = nodeBuilderState;
  35383. }
  35384. return nodeBuilderState;
  35385. }
  35386. delete( object ) {
  35387. if ( object.isRenderObject ) {
  35388. const nodeBuilderState = this.get( object ).nodeBuilderState;
  35389. nodeBuilderState.usedTimes --;
  35390. if ( nodeBuilderState.usedTimes === 0 ) {
  35391. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  35392. }
  35393. }
  35394. return super.delete( object );
  35395. }
  35396. getForCompute( computeNode ) {
  35397. const computeData = this.get( computeNode );
  35398. let nodeBuilderState = computeData.nodeBuilderState;
  35399. if ( nodeBuilderState === undefined ) {
  35400. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  35401. nodeBuilder.build();
  35402. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35403. computeData.nodeBuilderState = nodeBuilderState;
  35404. }
  35405. return nodeBuilderState;
  35406. }
  35407. _createNodeBuilderState( nodeBuilder ) {
  35408. return new NodeBuilderState(
  35409. nodeBuilder.vertexShader,
  35410. nodeBuilder.fragmentShader,
  35411. nodeBuilder.computeShader,
  35412. nodeBuilder.getAttributesArray(),
  35413. nodeBuilder.getBindings(),
  35414. nodeBuilder.updateNodes,
  35415. nodeBuilder.updateBeforeNodes,
  35416. nodeBuilder.updateAfterNodes,
  35417. nodeBuilder.instanceBindGroups,
  35418. nodeBuilder.transforms
  35419. );
  35420. }
  35421. getEnvironmentNode( scene ) {
  35422. return scene.environmentNode || this.get( scene ).environmentNode || null;
  35423. }
  35424. getBackgroundNode( scene ) {
  35425. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  35426. }
  35427. getFogNode( scene ) {
  35428. return scene.fogNode || this.get( scene ).fogNode || null;
  35429. }
  35430. getCacheKey( scene, lightsNode ) {
  35431. const chain = [ scene, lightsNode ];
  35432. const callId = this.renderer.info.calls;
  35433. let cacheKeyData = this.callHashCache.get( chain );
  35434. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  35435. const environmentNode = this.getEnvironmentNode( scene );
  35436. const fogNode = this.getFogNode( scene );
  35437. const cacheKey = [];
  35438. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey() );
  35439. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  35440. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  35441. cacheKeyData = {
  35442. callId,
  35443. cacheKey: cacheKey.join( ',' )
  35444. };
  35445. this.callHashCache.set( chain, cacheKeyData );
  35446. }
  35447. return cacheKeyData.cacheKey;
  35448. }
  35449. updateScene( scene ) {
  35450. this.updateEnvironment( scene );
  35451. this.updateFog( scene );
  35452. this.updateBackground( scene );
  35453. }
  35454. get isToneMappingState() {
  35455. return this.renderer.getRenderTarget() ? false : true;
  35456. }
  35457. updateBackground( scene ) {
  35458. const sceneData = this.get( scene );
  35459. const background = scene.background;
  35460. if ( background ) {
  35461. if ( sceneData.background !== background ) {
  35462. let backgroundNode = null;
  35463. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping ) ) {
  35464. backgroundNode = pmremTexture( background, normalWorld );
  35465. } else if ( background.isTexture === true ) {
  35466. backgroundNode = texture( background, viewportBottomLeft ).setUpdateMatrix( true );
  35467. } else if ( background.isColor !== true ) {
  35468. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  35469. }
  35470. sceneData.backgroundNode = backgroundNode;
  35471. sceneData.background = background;
  35472. }
  35473. } else if ( sceneData.backgroundNode ) {
  35474. delete sceneData.backgroundNode;
  35475. delete sceneData.background;
  35476. }
  35477. }
  35478. updateFog( scene ) {
  35479. const sceneData = this.get( scene );
  35480. const fog = scene.fog;
  35481. if ( fog ) {
  35482. if ( sceneData.fog !== fog ) {
  35483. let fogNode = null;
  35484. if ( fog.isFogExp2 ) {
  35485. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  35486. } else if ( fog.isFog ) {
  35487. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  35488. } else {
  35489. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  35490. }
  35491. sceneData.fogNode = fogNode;
  35492. sceneData.fog = fog;
  35493. }
  35494. } else {
  35495. delete sceneData.fogNode;
  35496. delete sceneData.fog;
  35497. }
  35498. }
  35499. updateEnvironment( scene ) {
  35500. const sceneData = this.get( scene );
  35501. const environment = scene.environment;
  35502. if ( environment ) {
  35503. if ( sceneData.environment !== environment ) {
  35504. let environmentNode = null;
  35505. if ( environment.isCubeTexture === true ) {
  35506. environmentNode = cubeTexture( environment );
  35507. } else if ( environment.isTexture === true ) {
  35508. environmentNode = texture( environment );
  35509. } else {
  35510. console.error( 'Nodes: Unsupported environment configuration.', environment );
  35511. }
  35512. sceneData.environmentNode = environmentNode;
  35513. sceneData.environment = environment;
  35514. }
  35515. } else if ( sceneData.environmentNode ) {
  35516. delete sceneData.environmentNode;
  35517. delete sceneData.environment;
  35518. }
  35519. }
  35520. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  35521. const nodeFrame = this.nodeFrame;
  35522. nodeFrame.renderer = renderer;
  35523. nodeFrame.scene = scene;
  35524. nodeFrame.object = object;
  35525. nodeFrame.camera = camera;
  35526. nodeFrame.material = material;
  35527. return nodeFrame;
  35528. }
  35529. getNodeFrameForRender( renderObject ) {
  35530. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  35531. }
  35532. getOutputCacheKey() {
  35533. const renderer = this.renderer;
  35534. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  35535. }
  35536. hasOutputChange( outputTarget ) {
  35537. const cacheKey = outputNodeMap.get( outputTarget );
  35538. return cacheKey !== this.getOutputCacheKey();
  35539. }
  35540. getOutputNode( outputTexture ) {
  35541. const renderer = this.renderer;
  35542. const cacheKey = this.getOutputCacheKey();
  35543. const output = texture( outputTexture, viewportTopLeft ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  35544. outputNodeMap.set( outputTexture, cacheKey );
  35545. return output;
  35546. }
  35547. updateBefore( renderObject ) {
  35548. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35549. const nodeBuilder = renderObject.getNodeBuilderState();
  35550. for ( const node of nodeBuilder.updateBeforeNodes ) {
  35551. nodeFrame.updateBeforeNode( node );
  35552. }
  35553. }
  35554. updateAfter( renderObject ) {
  35555. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35556. const nodeBuilder = renderObject.getNodeBuilderState();
  35557. for ( const node of nodeBuilder.updateAfterNodes ) {
  35558. nodeFrame.updateAfterNode( node );
  35559. }
  35560. }
  35561. updateForCompute( computeNode ) {
  35562. const nodeFrame = this.getNodeFrame();
  35563. const nodeBuilder = this.getForCompute( computeNode );
  35564. for ( const node of nodeBuilder.updateNodes ) {
  35565. nodeFrame.updateNode( node );
  35566. }
  35567. }
  35568. updateForRender( renderObject ) {
  35569. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35570. const nodeBuilder = renderObject.getNodeBuilderState();
  35571. for ( const node of nodeBuilder.updateNodes ) {
  35572. nodeFrame.updateNode( node );
  35573. }
  35574. }
  35575. dispose() {
  35576. super.dispose();
  35577. this.nodeFrame = new NodeFrame();
  35578. this.nodeBuilderCache = new Map();
  35579. }
  35580. }
  35581. class RenderBundle {
  35582. constructor( scene, camera ) {
  35583. this.scene = scene;
  35584. this.camera = camera;
  35585. }
  35586. clone() {
  35587. return Object.assign( new this.constructor(), this );
  35588. }
  35589. }
  35590. class RenderBundles {
  35591. constructor() {
  35592. this.lists = new ChainMap();
  35593. }
  35594. get( scene, camera ) {
  35595. const lists = this.lists;
  35596. const keys = [ scene, camera ];
  35597. let list = lists.get( keys );
  35598. if ( list === undefined ) {
  35599. list = new RenderBundle( scene, camera );
  35600. lists.set( keys, list );
  35601. }
  35602. return list;
  35603. }
  35604. dispose() {
  35605. this.lists = new ChainMap();
  35606. }
  35607. }
  35608. const _scene = new Scene();
  35609. const _drawingBufferSize = new Vector2();
  35610. const _screen = new Vector4();
  35611. const _frustum = new Frustum();
  35612. const _projScreenMatrix = new Matrix4();
  35613. const _vector3 = new Vector3();
  35614. const _quad = new QuadMesh( new NodeMaterial() );
  35615. class Renderer {
  35616. constructor( backend, parameters = {} ) {
  35617. this.isRenderer = true;
  35618. //
  35619. const {
  35620. logarithmicDepthBuffer = false,
  35621. alpha = true
  35622. } = parameters;
  35623. // public
  35624. this.domElement = backend.getDomElement();
  35625. this.backend = backend;
  35626. this.autoClear = true;
  35627. this.autoClearColor = true;
  35628. this.autoClearDepth = true;
  35629. this.autoClearStencil = true;
  35630. this.alpha = alpha;
  35631. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  35632. this.outputColorSpace = SRGBColorSpace;
  35633. this.toneMapping = NoToneMapping;
  35634. this.toneMappingExposure = 1.0;
  35635. this.sortObjects = true;
  35636. this.depth = true;
  35637. this.stencil = false;
  35638. this.clippingPlanes = [];
  35639. this.info = new Info();
  35640. // internals
  35641. this._pixelRatio = 1;
  35642. this._width = this.domElement.width;
  35643. this._height = this.domElement.height;
  35644. this._viewport = new Vector4( 0, 0, this._width, this._height );
  35645. this._scissor = new Vector4( 0, 0, this._width, this._height );
  35646. this._scissorTest = false;
  35647. this._attributes = null;
  35648. this._geometries = null;
  35649. this._nodes = null;
  35650. this._animation = null;
  35651. this._bindings = null;
  35652. this._objects = null;
  35653. this._pipelines = null;
  35654. this._bundles = null;
  35655. this._renderLists = null;
  35656. this._renderContexts = null;
  35657. this._textures = null;
  35658. this._background = null;
  35659. this._currentRenderContext = null;
  35660. this._opaqueSort = null;
  35661. this._transparentSort = null;
  35662. this._frameBufferTarget = null;
  35663. const alphaClear = this.alpha === true ? 0 : 1;
  35664. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  35665. this._clearDepth = 1;
  35666. this._clearStencil = 0;
  35667. this._renderTarget = null;
  35668. this._activeCubeFace = 0;
  35669. this._activeMipmapLevel = 0;
  35670. this._renderObjectFunction = null;
  35671. this._currentRenderObjectFunction = null;
  35672. this._currentRenderBundle = null;
  35673. this._handleObjectFunction = this._renderObjectDirect;
  35674. this._initialized = false;
  35675. this._initPromise = null;
  35676. this._compilationPromises = null;
  35677. // backwards compatibility
  35678. this.shadowMap = {
  35679. enabled: false,
  35680. type: null
  35681. };
  35682. this.xr = {
  35683. enabled: false
  35684. };
  35685. this.debug = {
  35686. checkShaderErrors: true,
  35687. onShaderError: null
  35688. };
  35689. }
  35690. async init() {
  35691. if ( this._initialized ) {
  35692. throw new Error( 'Renderer: Backend has already been initialized.' );
  35693. }
  35694. if ( this._initPromise !== null ) {
  35695. return this._initPromise;
  35696. }
  35697. this._initPromise = new Promise( async ( resolve, reject ) => {
  35698. const backend = this.backend;
  35699. try {
  35700. await backend.init( this );
  35701. } catch ( error ) {
  35702. reject( error );
  35703. return;
  35704. }
  35705. this._nodes = new Nodes( this, backend );
  35706. this._animation = new Animation( this._nodes, this.info );
  35707. this._attributes = new Attributes( backend );
  35708. this._background = new Background( this, this._nodes );
  35709. this._geometries = new Geometries( this._attributes, this.info );
  35710. this._textures = new Textures( this, backend, this.info );
  35711. this._pipelines = new Pipelines( backend, this._nodes );
  35712. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35713. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35714. this._renderLists = new RenderLists();
  35715. this._bundles = new RenderBundles();
  35716. this._renderContexts = new RenderContexts();
  35717. //
  35718. this._initialized = true;
  35719. resolve();
  35720. } );
  35721. return this._initPromise;
  35722. }
  35723. get coordinateSystem() {
  35724. return this.backend.coordinateSystem;
  35725. }
  35726. async compileAsync( scene, camera, targetScene = null ) {
  35727. if ( this._initialized === false ) await this.init();
  35728. // preserve render tree
  35729. const nodeFrame = this._nodes.nodeFrame;
  35730. const previousRenderId = nodeFrame.renderId;
  35731. const previousRenderContext = this._currentRenderContext;
  35732. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35733. const previousCompilationPromises = this._compilationPromises;
  35734. //
  35735. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35736. if ( targetScene === null ) targetScene = scene;
  35737. const renderTarget = this._renderTarget;
  35738. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  35739. const activeMipmapLevel = this._activeMipmapLevel;
  35740. const compilationPromises = [];
  35741. this._currentRenderContext = renderContext;
  35742. this._currentRenderObjectFunction = this.renderObject;
  35743. this._handleObjectFunction = this._createObjectPipeline;
  35744. this._compilationPromises = compilationPromises;
  35745. nodeFrame.renderId ++;
  35746. //
  35747. nodeFrame.update();
  35748. //
  35749. renderContext.depth = this.depth;
  35750. renderContext.stencil = this.stencil;
  35751. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35752. renderContext.clippingContext.updateGlobal( this, camera );
  35753. //
  35754. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35755. //
  35756. const renderList = this._renderLists.get( scene, camera );
  35757. renderList.begin();
  35758. this._projectObject( scene, camera, 0, renderList );
  35759. // include lights from target scene
  35760. if ( targetScene !== scene ) {
  35761. targetScene.traverseVisible( function ( object ) {
  35762. if ( object.isLight && object.layers.test( camera.layers ) ) {
  35763. renderList.pushLight( object );
  35764. }
  35765. } );
  35766. }
  35767. renderList.finish();
  35768. //
  35769. if ( renderTarget !== null ) {
  35770. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35771. const renderTargetData = this._textures.get( renderTarget );
  35772. renderContext.textures = renderTargetData.textures;
  35773. renderContext.depthTexture = renderTargetData.depthTexture;
  35774. } else {
  35775. renderContext.textures = null;
  35776. renderContext.depthTexture = null;
  35777. }
  35778. //
  35779. this._nodes.updateScene( sceneRef );
  35780. //
  35781. this._background.update( sceneRef, renderList, renderContext );
  35782. // process render lists
  35783. const opaqueObjects = renderList.opaque;
  35784. const transparentObjects = renderList.transparent;
  35785. const lightsNode = renderList.lightsNode;
  35786. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35787. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  35788. // restore render tree
  35789. nodeFrame.renderId = previousRenderId;
  35790. this._currentRenderContext = previousRenderContext;
  35791. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35792. this._compilationPromises = previousCompilationPromises;
  35793. this._handleObjectFunction = this._renderObjectDirect;
  35794. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  35795. await Promise.all( compilationPromises );
  35796. }
  35797. async renderAsync( scene, camera ) {
  35798. if ( this._initialized === false ) await this.init();
  35799. const renderContext = this._renderScene( scene, camera );
  35800. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  35801. }
  35802. _renderBundle( bundle, sceneRef, lightsNode ) {
  35803. const { object, camera, renderList } = bundle;
  35804. const renderContext = this._currentRenderContext;
  35805. const renderContextData = this.backend.get( renderContext );
  35806. //
  35807. const renderBundle = this._bundles.get( object, camera );
  35808. const renderBundleData = this.backend.get( renderBundle );
  35809. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  35810. //
  35811. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || object.needsUpdate === true;
  35812. renderBundleData.renderContexts.add( renderContext );
  35813. if ( renderBundleNeedsUpdate ) {
  35814. if ( renderContextData.renderObjects === undefined || object.needsUpdate === true ) {
  35815. const nodeFrame = this._nodes.nodeFrame;
  35816. renderContextData.renderObjects = [];
  35817. renderContextData.renderBundles = [];
  35818. renderContextData.scene = sceneRef;
  35819. renderContextData.camera = camera;
  35820. renderContextData.renderId = nodeFrame.renderId;
  35821. renderContextData.registerBundlesPhase = true;
  35822. }
  35823. this._currentRenderBundle = renderBundle;
  35824. const opaqueObjects = renderList.opaque;
  35825. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35826. this._currentRenderBundle = null;
  35827. //
  35828. object.needsUpdate = false;
  35829. } else {
  35830. const renderContext = this._currentRenderContext;
  35831. const renderContextData = this.backend.get( renderContext );
  35832. for ( let i = 0, l = renderContextData.renderObjects.length; i < l; i ++ ) {
  35833. const renderObject = renderContextData.renderObjects[ i ];
  35834. this._nodes.updateBefore( renderObject );
  35835. //
  35836. renderObject.object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, renderObject.object.matrixWorld );
  35837. renderObject.object.normalMatrix.getNormalMatrix( renderObject.object.modelViewMatrix );
  35838. this._nodes.updateForRender( renderObject );
  35839. this._bindings.updateForRender( renderObject );
  35840. this.backend.draw( renderObject, this.info );
  35841. this._nodes.updateAfter( renderObject );
  35842. }
  35843. }
  35844. }
  35845. render( scene, camera ) {
  35846. if ( this._initialized === false ) {
  35847. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  35848. return this.renderAsync( scene, camera );
  35849. }
  35850. this._renderScene( scene, camera );
  35851. }
  35852. _getFrameBufferTarget() {
  35853. const { currentColorSpace } = this;
  35854. const useToneMapping = this._renderTarget === null && ( this.toneMapping !== NoToneMapping );
  35855. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace && currentColorSpace !== NoColorSpace;
  35856. if ( useToneMapping === false && useColorSpace === false ) return null;
  35857. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  35858. const { depth, stencil } = this;
  35859. let frameBufferTarget = this._frameBufferTarget;
  35860. if ( frameBufferTarget === null ) {
  35861. frameBufferTarget = new RenderTarget( width, height, {
  35862. depthBuffer: depth,
  35863. stencilBuffer: stencil,
  35864. type: HalfFloatType, // FloatType
  35865. format: RGBAFormat,
  35866. colorSpace: LinearSRGBColorSpace,
  35867. generateMipmaps: false,
  35868. minFilter: LinearFilter,
  35869. magFilter: LinearFilter,
  35870. samples: this.backend.parameters.antialias ? 4 : 0
  35871. } );
  35872. frameBufferTarget.isPostProcessingRenderTarget = true;
  35873. this._frameBufferTarget = frameBufferTarget;
  35874. }
  35875. frameBufferTarget.depthBuffer = depth;
  35876. frameBufferTarget.stencilBuffer = stencil;
  35877. frameBufferTarget.setSize( width, height );
  35878. frameBufferTarget.viewport.copy( this._viewport );
  35879. frameBufferTarget.scissor.copy( this._scissor );
  35880. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  35881. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  35882. frameBufferTarget.scissorTest = this._scissorTest;
  35883. return frameBufferTarget;
  35884. }
  35885. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  35886. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  35887. // preserve render tree
  35888. const nodeFrame = this._nodes.nodeFrame;
  35889. const previousRenderId = nodeFrame.renderId;
  35890. const previousRenderContext = this._currentRenderContext;
  35891. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35892. //
  35893. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35894. const outputRenderTarget = this._renderTarget;
  35895. const activeCubeFace = this._activeCubeFace;
  35896. const activeMipmapLevel = this._activeMipmapLevel;
  35897. //
  35898. let renderTarget;
  35899. if ( frameBufferTarget !== null ) {
  35900. renderTarget = frameBufferTarget;
  35901. this.setRenderTarget( renderTarget );
  35902. } else {
  35903. renderTarget = outputRenderTarget;
  35904. }
  35905. //
  35906. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  35907. this._currentRenderContext = renderContext;
  35908. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  35909. //
  35910. this.info.calls ++;
  35911. this.info.render.calls ++;
  35912. this.info.render.frameCalls ++;
  35913. nodeFrame.renderId = this.info.calls;
  35914. //
  35915. const coordinateSystem = this.coordinateSystem;
  35916. if ( camera.coordinateSystem !== coordinateSystem ) {
  35917. camera.coordinateSystem = coordinateSystem;
  35918. camera.updateProjectionMatrix();
  35919. }
  35920. //
  35921. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  35922. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  35923. //
  35924. let viewport = this._viewport;
  35925. let scissor = this._scissor;
  35926. let pixelRatio = this._pixelRatio;
  35927. if ( renderTarget !== null ) {
  35928. viewport = renderTarget.viewport;
  35929. scissor = renderTarget.scissor;
  35930. pixelRatio = 1;
  35931. }
  35932. this.getDrawingBufferSize( _drawingBufferSize );
  35933. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  35934. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  35935. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  35936. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  35937. renderContext.viewportValue.width >>= activeMipmapLevel;
  35938. renderContext.viewportValue.height >>= activeMipmapLevel;
  35939. renderContext.viewportValue.minDepth = minDepth;
  35940. renderContext.viewportValue.maxDepth = maxDepth;
  35941. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  35942. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  35943. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  35944. renderContext.scissorValue.width >>= activeMipmapLevel;
  35945. renderContext.scissorValue.height >>= activeMipmapLevel;
  35946. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35947. renderContext.clippingContext.updateGlobal( this, camera );
  35948. //
  35949. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35950. //
  35951. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  35952. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  35953. const renderList = this._renderLists.get( scene, camera );
  35954. renderList.begin();
  35955. this._projectObject( scene, camera, 0, renderList );
  35956. renderList.finish();
  35957. if ( this.sortObjects === true ) {
  35958. renderList.sort( this._opaqueSort, this._transparentSort );
  35959. }
  35960. //
  35961. if ( renderTarget !== null ) {
  35962. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35963. const renderTargetData = this._textures.get( renderTarget );
  35964. renderContext.textures = renderTargetData.textures;
  35965. renderContext.depthTexture = renderTargetData.depthTexture;
  35966. renderContext.width = renderTargetData.width;
  35967. renderContext.height = renderTargetData.height;
  35968. renderContext.renderTarget = renderTarget;
  35969. renderContext.depth = renderTarget.depthBuffer;
  35970. renderContext.stencil = renderTarget.stencilBuffer;
  35971. } else {
  35972. renderContext.textures = null;
  35973. renderContext.depthTexture = null;
  35974. renderContext.width = this.domElement.width;
  35975. renderContext.height = this.domElement.height;
  35976. renderContext.depth = this.depth;
  35977. renderContext.stencil = this.stencil;
  35978. }
  35979. renderContext.width >>= activeMipmapLevel;
  35980. renderContext.height >>= activeMipmapLevel;
  35981. renderContext.activeCubeFace = activeCubeFace;
  35982. renderContext.activeMipmapLevel = activeMipmapLevel;
  35983. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  35984. //
  35985. this._nodes.updateScene( sceneRef );
  35986. //
  35987. this._background.update( sceneRef, renderList, renderContext );
  35988. //
  35989. this.backend.beginRender( renderContext );
  35990. // process render lists
  35991. const opaqueObjects = renderList.opaque;
  35992. const transparentObjects = renderList.transparent;
  35993. const bundles = renderList.bundles;
  35994. const lightsNode = renderList.lightsNode;
  35995. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  35996. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35997. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  35998. // finish render pass
  35999. this.backend.finishRender( renderContext );
  36000. // restore render tree
  36001. nodeFrame.renderId = previousRenderId;
  36002. this._currentRenderContext = previousRenderContext;
  36003. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36004. //
  36005. if ( frameBufferTarget !== null ) {
  36006. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  36007. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  36008. _quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36009. _quad.material.needsUpdate = true;
  36010. }
  36011. this._renderScene( _quad, _quad.camera, false );
  36012. }
  36013. //
  36014. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  36015. //
  36016. return renderContext;
  36017. }
  36018. getMaxAnisotropy() {
  36019. return this.backend.getMaxAnisotropy();
  36020. }
  36021. getActiveCubeFace() {
  36022. return this._activeCubeFace;
  36023. }
  36024. getActiveMipmapLevel() {
  36025. return this._activeMipmapLevel;
  36026. }
  36027. async setAnimationLoop( callback ) {
  36028. if ( this._initialized === false ) await this.init();
  36029. this._animation.setAnimationLoop( callback );
  36030. }
  36031. async getArrayBufferAsync( attribute ) {
  36032. return await this.backend.getArrayBufferAsync( attribute );
  36033. }
  36034. getContext() {
  36035. return this.backend.getContext();
  36036. }
  36037. getPixelRatio() {
  36038. return this._pixelRatio;
  36039. }
  36040. getDrawingBufferSize( target ) {
  36041. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  36042. }
  36043. getSize( target ) {
  36044. return target.set( this._width, this._height );
  36045. }
  36046. setPixelRatio( value = 1 ) {
  36047. this._pixelRatio = value;
  36048. this.setSize( this._width, this._height, false );
  36049. }
  36050. setDrawingBufferSize( width, height, pixelRatio ) {
  36051. this._width = width;
  36052. this._height = height;
  36053. this._pixelRatio = pixelRatio;
  36054. this.domElement.width = Math.floor( width * pixelRatio );
  36055. this.domElement.height = Math.floor( height * pixelRatio );
  36056. this.setViewport( 0, 0, width, height );
  36057. if ( this._initialized ) this.backend.updateSize();
  36058. }
  36059. setSize( width, height, updateStyle = true ) {
  36060. this._width = width;
  36061. this._height = height;
  36062. this.domElement.width = Math.floor( width * this._pixelRatio );
  36063. this.domElement.height = Math.floor( height * this._pixelRatio );
  36064. if ( updateStyle === true ) {
  36065. this.domElement.style.width = width + 'px';
  36066. this.domElement.style.height = height + 'px';
  36067. }
  36068. this.setViewport( 0, 0, width, height );
  36069. if ( this._initialized ) this.backend.updateSize();
  36070. }
  36071. setOpaqueSort( method ) {
  36072. this._opaqueSort = method;
  36073. }
  36074. setTransparentSort( method ) {
  36075. this._transparentSort = method;
  36076. }
  36077. getScissor( target ) {
  36078. const scissor = this._scissor;
  36079. target.x = scissor.x;
  36080. target.y = scissor.y;
  36081. target.width = scissor.width;
  36082. target.height = scissor.height;
  36083. return target;
  36084. }
  36085. setScissor( x, y, width, height ) {
  36086. const scissor = this._scissor;
  36087. if ( x.isVector4 ) {
  36088. scissor.copy( x );
  36089. } else {
  36090. scissor.set( x, y, width, height );
  36091. }
  36092. }
  36093. getScissorTest() {
  36094. return this._scissorTest;
  36095. }
  36096. setScissorTest( boolean ) {
  36097. this._scissorTest = boolean;
  36098. this.backend.setScissorTest( boolean );
  36099. }
  36100. getViewport( target ) {
  36101. return target.copy( this._viewport );
  36102. }
  36103. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  36104. const viewport = this._viewport;
  36105. if ( x.isVector4 ) {
  36106. viewport.copy( x );
  36107. } else {
  36108. viewport.set( x, y, width, height );
  36109. }
  36110. viewport.minDepth = minDepth;
  36111. viewport.maxDepth = maxDepth;
  36112. }
  36113. getClearColor( target ) {
  36114. return target.copy( this._clearColor );
  36115. }
  36116. setClearColor( color, alpha = 1 ) {
  36117. this._clearColor.set( color );
  36118. this._clearColor.a = alpha;
  36119. }
  36120. getClearAlpha() {
  36121. return this._clearColor.a;
  36122. }
  36123. setClearAlpha( alpha ) {
  36124. this._clearColor.a = alpha;
  36125. }
  36126. getClearDepth() {
  36127. return this._clearDepth;
  36128. }
  36129. setClearDepth( depth ) {
  36130. this._clearDepth = depth;
  36131. }
  36132. getClearStencil() {
  36133. return this._clearStencil;
  36134. }
  36135. setClearStencil( stencil ) {
  36136. this._clearStencil = stencil;
  36137. }
  36138. isOccluded( object ) {
  36139. const renderContext = this._currentRenderContext;
  36140. return renderContext && this.backend.isOccluded( renderContext, object );
  36141. }
  36142. clear( color = true, depth = true, stencil = true ) {
  36143. if ( this._initialized === false ) {
  36144. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  36145. return this.clearAsync( color, depth, stencil );
  36146. }
  36147. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36148. let renderTargetData = null;
  36149. if ( renderTarget !== null ) {
  36150. this._textures.updateRenderTarget( renderTarget );
  36151. renderTargetData = this._textures.get( renderTarget );
  36152. }
  36153. this.backend.clear( color, depth, stencil, renderTargetData );
  36154. if ( renderTarget !== null && this._renderTarget === null ) {
  36155. // If a color space transform or tone mapping is required,
  36156. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  36157. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  36158. _quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36159. _quad.material.needsUpdate = true;
  36160. }
  36161. this._renderScene( _quad, _quad.camera, false );
  36162. }
  36163. }
  36164. clearColor() {
  36165. return this.clear( true, false, false );
  36166. }
  36167. clearDepth() {
  36168. return this.clear( false, true, false );
  36169. }
  36170. clearStencil() {
  36171. return this.clear( false, false, true );
  36172. }
  36173. async clearAsync( color = true, depth = true, stencil = true ) {
  36174. if ( this._initialized === false ) await this.init();
  36175. this.clear( color, depth, stencil );
  36176. }
  36177. clearColorAsync() {
  36178. return this.clearAsync( true, false, false );
  36179. }
  36180. clearDepthAsync() {
  36181. return this.clearAsync( false, true, false );
  36182. }
  36183. clearStencilAsync() {
  36184. return this.clearAsync( false, false, true );
  36185. }
  36186. get currentColorSpace() {
  36187. const renderTarget = this._renderTarget;
  36188. if ( renderTarget !== null ) {
  36189. const texture = renderTarget.texture;
  36190. return ( Array.isArray( texture ) ? texture[ 0 ] : texture ).colorSpace;
  36191. }
  36192. return this.outputColorSpace;
  36193. }
  36194. dispose() {
  36195. this.info.dispose();
  36196. this._animation.dispose();
  36197. this._objects.dispose();
  36198. this._pipelines.dispose();
  36199. this._nodes.dispose();
  36200. this._bindings.dispose();
  36201. this._renderLists.dispose();
  36202. this._renderContexts.dispose();
  36203. this._textures.dispose();
  36204. this.setRenderTarget( null );
  36205. this.setAnimationLoop( null );
  36206. }
  36207. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  36208. this._renderTarget = renderTarget;
  36209. this._activeCubeFace = activeCubeFace;
  36210. this._activeMipmapLevel = activeMipmapLevel;
  36211. }
  36212. getRenderTarget() {
  36213. return this._renderTarget;
  36214. }
  36215. setRenderObjectFunction( renderObjectFunction ) {
  36216. this._renderObjectFunction = renderObjectFunction;
  36217. }
  36218. getRenderObjectFunction() {
  36219. return this._renderObjectFunction;
  36220. }
  36221. async computeAsync( computeNodes ) {
  36222. if ( this._initialized === false ) await this.init();
  36223. const nodeFrame = this._nodes.nodeFrame;
  36224. const previousRenderId = nodeFrame.renderId;
  36225. //
  36226. this.info.calls ++;
  36227. this.info.compute.calls ++;
  36228. this.info.compute.frameCalls ++;
  36229. nodeFrame.renderId = this.info.calls;
  36230. //
  36231. const backend = this.backend;
  36232. const pipelines = this._pipelines;
  36233. const bindings = this._bindings;
  36234. const nodes = this._nodes;
  36235. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36236. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36237. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36238. }
  36239. backend.beginCompute( computeNodes );
  36240. for ( const computeNode of computeList ) {
  36241. // onInit
  36242. if ( pipelines.has( computeNode ) === false ) {
  36243. const dispose = () => {
  36244. computeNode.removeEventListener( 'dispose', dispose );
  36245. pipelines.delete( computeNode );
  36246. bindings.delete( computeNode );
  36247. nodes.delete( computeNode );
  36248. };
  36249. computeNode.addEventListener( 'dispose', dispose );
  36250. //
  36251. computeNode.onInit( { renderer: this } );
  36252. }
  36253. nodes.updateForCompute( computeNode );
  36254. bindings.updateForCompute( computeNode );
  36255. const computeBindings = bindings.getForCompute( computeNode );
  36256. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  36257. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  36258. }
  36259. backend.finishCompute( computeNodes );
  36260. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  36261. //
  36262. nodeFrame.renderId = previousRenderId;
  36263. }
  36264. async hasFeatureAsync( name ) {
  36265. if ( this._initialized === false ) await this.init();
  36266. return this.backend.hasFeature( name );
  36267. }
  36268. hasFeature( name ) {
  36269. if ( this._initialized === false ) {
  36270. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  36271. return false;
  36272. }
  36273. return this.backend.hasFeature( name );
  36274. }
  36275. copyFramebufferToTexture( framebufferTexture ) {
  36276. const renderContext = this._currentRenderContext;
  36277. this._textures.updateTexture( framebufferTexture );
  36278. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  36279. }
  36280. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  36281. this._textures.updateTexture( srcTexture );
  36282. this._textures.updateTexture( dstTexture );
  36283. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  36284. }
  36285. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0 ) {
  36286. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height );
  36287. }
  36288. _projectObject( object, camera, groupOrder, renderList ) {
  36289. if ( object.visible === false ) return;
  36290. const visible = object.layers.test( camera.layers );
  36291. if ( visible ) {
  36292. if ( object.isGroup ) {
  36293. groupOrder = object.renderOrder;
  36294. } else if ( object.isLOD ) {
  36295. if ( object.autoUpdate === true ) object.update( camera );
  36296. } else if ( object.isLight ) {
  36297. renderList.pushLight( object );
  36298. } else if ( object.isSprite ) {
  36299. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  36300. if ( this.sortObjects === true ) {
  36301. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  36302. }
  36303. const geometry = object.geometry;
  36304. const material = object.material;
  36305. if ( material.visible ) {
  36306. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36307. }
  36308. }
  36309. } else if ( object.isLineLoop ) {
  36310. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  36311. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  36312. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  36313. const geometry = object.geometry;
  36314. const material = object.material;
  36315. if ( this.sortObjects === true ) {
  36316. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  36317. _vector3
  36318. .copy( geometry.boundingSphere.center )
  36319. .applyMatrix4( object.matrixWorld )
  36320. .applyMatrix4( _projScreenMatrix );
  36321. }
  36322. if ( Array.isArray( material ) ) {
  36323. const groups = geometry.groups;
  36324. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  36325. const group = groups[ i ];
  36326. const groupMaterial = material[ group.materialIndex ];
  36327. if ( groupMaterial && groupMaterial.visible ) {
  36328. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  36329. }
  36330. }
  36331. } else if ( material.visible ) {
  36332. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36333. }
  36334. }
  36335. }
  36336. }
  36337. if ( object.static === true ) {
  36338. const baseRenderList = renderList;
  36339. // replace render list
  36340. renderList = this._renderLists.get( object, camera );
  36341. renderList.begin();
  36342. baseRenderList.pushBundle( {
  36343. object,
  36344. camera,
  36345. renderList,
  36346. } );
  36347. renderList.finish();
  36348. }
  36349. const children = object.children;
  36350. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36351. this._projectObject( children[ i ], camera, groupOrder, renderList );
  36352. }
  36353. }
  36354. _renderBundles( bundles, sceneRef, lightsNode ) {
  36355. for ( const bundle of bundles ) {
  36356. this._renderBundle( bundle, sceneRef, lightsNode );
  36357. }
  36358. }
  36359. _renderObjects( renderList, camera, scene, lightsNode ) {
  36360. // process renderable objects
  36361. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36362. const renderItem = renderList[ i ];
  36363. // @TODO: Add support for multiple materials per object. This will require to extract
  36364. // the material from the renderItem object and pass it with its group data to renderObject().
  36365. const { object, geometry, material, group } = renderItem;
  36366. if ( camera.isArrayCamera ) {
  36367. const cameras = camera.cameras;
  36368. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  36369. const camera2 = cameras[ j ];
  36370. if ( object.layers.test( camera2.layers ) ) {
  36371. const vp = camera2.viewport;
  36372. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  36373. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  36374. const viewportValue = this._currentRenderContext.viewportValue;
  36375. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  36376. viewportValue.minDepth = minDepth;
  36377. viewportValue.maxDepth = maxDepth;
  36378. this.backend.updateViewport( this._currentRenderContext );
  36379. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  36380. }
  36381. }
  36382. } else {
  36383. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  36384. }
  36385. }
  36386. }
  36387. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  36388. let overridePositionNode;
  36389. let overrideFragmentNode;
  36390. let overrideDepthNode;
  36391. //
  36392. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36393. //
  36394. if ( scene.overrideMaterial !== null ) {
  36395. const overrideMaterial = scene.overrideMaterial;
  36396. if ( material.positionNode && material.positionNode.isNode ) {
  36397. overridePositionNode = overrideMaterial.positionNode;
  36398. overrideMaterial.positionNode = material.positionNode;
  36399. }
  36400. if ( overrideMaterial.isShadowNodeMaterial ) {
  36401. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36402. if ( material.depthNode && material.depthNode.isNode ) {
  36403. overrideDepthNode = overrideMaterial.depthNode;
  36404. overrideMaterial.depthNode = material.depthNode;
  36405. }
  36406. if ( material.shadowNode && material.shadowNode.isNode ) {
  36407. overrideFragmentNode = overrideMaterial.fragmentNode;
  36408. overrideMaterial.fragmentNode = material.shadowNode;
  36409. }
  36410. if ( this.localClippingEnabled ) {
  36411. if ( material.clipShadows ) {
  36412. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  36413. overrideMaterial.clippingPlanes = material.clippingPlanes;
  36414. overrideMaterial.needsUpdate = true;
  36415. }
  36416. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  36417. overrideMaterial.clipIntersection = material.clipIntersection;
  36418. }
  36419. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  36420. overrideMaterial.clippingPlanes = null;
  36421. overrideMaterial.needsUpdate = true;
  36422. }
  36423. }
  36424. }
  36425. material = overrideMaterial;
  36426. }
  36427. //
  36428. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36429. material.side = BackSide;
  36430. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  36431. material.side = FrontSide;
  36432. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  36433. material.side = DoubleSide;
  36434. } else {
  36435. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  36436. }
  36437. //
  36438. if ( overridePositionNode !== undefined ) {
  36439. scene.overrideMaterial.positionNode = overridePositionNode;
  36440. }
  36441. if ( overrideDepthNode !== undefined ) {
  36442. scene.overrideMaterial.depthNode = overrideDepthNode;
  36443. }
  36444. if ( overrideFragmentNode !== undefined ) {
  36445. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  36446. }
  36447. //
  36448. object.onAfterRender( this, scene, camera, geometry, material, group );
  36449. }
  36450. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  36451. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36452. renderObject.drawRange = group || object.geometry.drawRange;
  36453. //
  36454. this._nodes.updateBefore( renderObject );
  36455. //
  36456. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  36457. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  36458. //
  36459. this._nodes.updateForRender( renderObject );
  36460. this._geometries.updateForRender( renderObject );
  36461. this._bindings.updateForRender( renderObject );
  36462. this._pipelines.updateForRender( renderObject );
  36463. //
  36464. if ( this._currentRenderBundle !== null && this._currentRenderBundle.needsUpdate === true ) {
  36465. const renderObjectData = this.backend.get( renderObject );
  36466. renderObjectData.bundleEncoder = undefined;
  36467. renderObjectData.lastPipelineGPU = undefined;
  36468. }
  36469. this.backend.draw( renderObject, this.info );
  36470. if ( this._currentRenderBundle !== null ) {
  36471. const renderContextData = this.backend.get( this._currentRenderContext );
  36472. renderContextData.renderObjects.push( renderObject );
  36473. }
  36474. this._nodes.updateAfter( renderObject );
  36475. }
  36476. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  36477. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36478. //
  36479. this._nodes.updateBefore( renderObject );
  36480. //
  36481. this._nodes.updateForRender( renderObject );
  36482. this._geometries.updateForRender( renderObject );
  36483. this._bindings.updateForRender( renderObject );
  36484. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36485. this._nodes.updateAfter( renderObject );
  36486. }
  36487. get compute() {
  36488. return this.computeAsync;
  36489. }
  36490. get compile() {
  36491. return this.compileAsync;
  36492. }
  36493. }
  36494. class Binding {
  36495. constructor( name = '' ) {
  36496. this.name = name;
  36497. this.visibility = 0;
  36498. }
  36499. setVisibility( visibility ) {
  36500. this.visibility |= visibility;
  36501. }
  36502. clone() {
  36503. return Object.assign( new this.constructor(), this );
  36504. }
  36505. }
  36506. function getFloatLength( floatLength ) {
  36507. // ensure chunk size alignment (STD140 layout)
  36508. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36509. }
  36510. class Buffer extends Binding {
  36511. constructor( name, buffer = null ) {
  36512. super( name );
  36513. this.isBuffer = true;
  36514. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36515. this._buffer = buffer;
  36516. }
  36517. get byteLength() {
  36518. return getFloatLength( this._buffer.byteLength );
  36519. }
  36520. get buffer() {
  36521. return this._buffer;
  36522. }
  36523. update() {
  36524. return true;
  36525. }
  36526. }
  36527. class UniformBuffer extends Buffer {
  36528. constructor( name, buffer = null ) {
  36529. super( name, buffer );
  36530. this.isUniformBuffer = true;
  36531. }
  36532. }
  36533. let _id$2 = 0;
  36534. class NodeUniformBuffer extends UniformBuffer {
  36535. constructor( nodeUniform, groupNode ) {
  36536. super( 'UniformBuffer_' + _id$2 ++, nodeUniform ? nodeUniform.value : null );
  36537. this.nodeUniform = nodeUniform;
  36538. this.groupNode = groupNode;
  36539. }
  36540. get buffer() {
  36541. return this.nodeUniform.value;
  36542. }
  36543. }
  36544. class UniformsGroup extends UniformBuffer {
  36545. constructor( name ) {
  36546. super( name );
  36547. this.isUniformsGroup = true;
  36548. this._values = null;
  36549. // the order of uniforms in this array must match the order of uniforms in the shader
  36550. this.uniforms = [];
  36551. }
  36552. addUniform( uniform ) {
  36553. this.uniforms.push( uniform );
  36554. return this;
  36555. }
  36556. removeUniform( uniform ) {
  36557. const index = this.uniforms.indexOf( uniform );
  36558. if ( index !== - 1 ) {
  36559. this.uniforms.splice( index, 1 );
  36560. }
  36561. return this;
  36562. }
  36563. get values() {
  36564. if ( this._values === null ) {
  36565. this._values = Array.from( this.buffer );
  36566. }
  36567. return this._values;
  36568. }
  36569. get buffer() {
  36570. let buffer = this._buffer;
  36571. if ( buffer === null ) {
  36572. const byteLength = this.byteLength;
  36573. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36574. this._buffer = buffer;
  36575. }
  36576. return buffer;
  36577. }
  36578. get byteLength() {
  36579. let offset = 0; // global buffer offset in bytes
  36580. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36581. const uniform = this.uniforms[ i ];
  36582. const { boundary, itemSize } = uniform;
  36583. // offset within a single chunk in bytes
  36584. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36585. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36586. // conformance tests
  36587. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36588. // check for chunk overflow
  36589. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36590. } else if ( chunkOffset % boundary !== 0 ) {
  36591. // check for correct alignment
  36592. offset += ( chunkOffset % boundary );
  36593. }
  36594. uniform.offset = ( offset / this.bytesPerElement );
  36595. offset += ( itemSize * this.bytesPerElement );
  36596. }
  36597. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36598. }
  36599. update() {
  36600. let updated = false;
  36601. for ( const uniform of this.uniforms ) {
  36602. if ( this.updateByType( uniform ) === true ) {
  36603. updated = true;
  36604. }
  36605. }
  36606. return updated;
  36607. }
  36608. updateByType( uniform ) {
  36609. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36610. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36611. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36612. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36613. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36614. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36615. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36616. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36617. }
  36618. updateNumber( uniform ) {
  36619. let updated = false;
  36620. const a = this.values;
  36621. const v = uniform.getValue();
  36622. const offset = uniform.offset;
  36623. if ( a[ offset ] !== v ) {
  36624. const b = this.buffer;
  36625. b[ offset ] = a[ offset ] = v;
  36626. updated = true;
  36627. }
  36628. return updated;
  36629. }
  36630. updateVector2( uniform ) {
  36631. let updated = false;
  36632. const a = this.values;
  36633. const v = uniform.getValue();
  36634. const offset = uniform.offset;
  36635. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36636. const b = this.buffer;
  36637. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36638. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36639. updated = true;
  36640. }
  36641. return updated;
  36642. }
  36643. updateVector3( uniform ) {
  36644. let updated = false;
  36645. const a = this.values;
  36646. const v = uniform.getValue();
  36647. const offset = uniform.offset;
  36648. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36649. const b = this.buffer;
  36650. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36651. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36652. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36653. updated = true;
  36654. }
  36655. return updated;
  36656. }
  36657. updateVector4( uniform ) {
  36658. let updated = false;
  36659. const a = this.values;
  36660. const v = uniform.getValue();
  36661. const offset = uniform.offset;
  36662. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36663. const b = this.buffer;
  36664. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36665. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36666. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36667. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36668. updated = true;
  36669. }
  36670. return updated;
  36671. }
  36672. updateColor( uniform ) {
  36673. let updated = false;
  36674. const a = this.values;
  36675. const c = uniform.getValue();
  36676. const offset = uniform.offset;
  36677. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36678. const b = this.buffer;
  36679. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36680. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36681. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36682. updated = true;
  36683. }
  36684. return updated;
  36685. }
  36686. updateMatrix3( uniform ) {
  36687. let updated = false;
  36688. const a = this.values;
  36689. const e = uniform.getValue().elements;
  36690. const offset = uniform.offset;
  36691. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36692. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36693. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36694. const b = this.buffer;
  36695. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36696. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36697. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36698. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36699. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36700. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36701. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36702. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36703. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36704. updated = true;
  36705. }
  36706. return updated;
  36707. }
  36708. updateMatrix4( uniform ) {
  36709. let updated = false;
  36710. const a = this.values;
  36711. const e = uniform.getValue().elements;
  36712. const offset = uniform.offset;
  36713. if ( arraysEqual( a, e, offset ) === false ) {
  36714. const b = this.buffer;
  36715. b.set( e, offset );
  36716. setArray( a, e, offset );
  36717. updated = true;
  36718. }
  36719. return updated;
  36720. }
  36721. }
  36722. function setArray( a, b, offset ) {
  36723. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36724. a[ offset + i ] = b[ i ];
  36725. }
  36726. }
  36727. function arraysEqual( a, b, offset ) {
  36728. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36729. if ( a[ offset + i ] !== b[ i ] ) return false;
  36730. }
  36731. return true;
  36732. }
  36733. let id$1 = 0;
  36734. class NodeUniformsGroup extends UniformsGroup {
  36735. constructor( name, groupNode ) {
  36736. super( name );
  36737. this.id = id$1 ++;
  36738. this.groupNode = groupNode;
  36739. this.isNodeUniformsGroup = true;
  36740. }
  36741. getNodes() {
  36742. const nodes = [];
  36743. for ( const uniform of this.uniforms ) {
  36744. const node = uniform.nodeUniform.node;
  36745. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  36746. nodes.push( node );
  36747. }
  36748. return nodes;
  36749. }
  36750. }
  36751. let id = 0;
  36752. class SampledTexture extends Binding {
  36753. constructor( name, texture ) {
  36754. super( name );
  36755. this.id = id ++;
  36756. this.texture = texture;
  36757. this.version = texture ? texture.version : 0;
  36758. this.store = false;
  36759. this.isSampledTexture = true;
  36760. }
  36761. get needsBindingsUpdate() {
  36762. const { texture, version } = this;
  36763. return texture.isVideoTexture ? true : version !== texture.version; // @TODO: version === 0 && texture.version > 0 ( add it just to External Textures like PNG,JPG )
  36764. }
  36765. update() {
  36766. const { texture, version } = this;
  36767. if ( version !== texture.version ) {
  36768. this.version = texture.version;
  36769. return true;
  36770. }
  36771. return false;
  36772. }
  36773. }
  36774. class NodeSampledTexture extends SampledTexture {
  36775. constructor( name, textureNode, groupNode, access = null ) {
  36776. super( name, textureNode ? textureNode.value : null );
  36777. this.textureNode = textureNode;
  36778. this.groupNode = groupNode;
  36779. this.access = access;
  36780. }
  36781. get needsBindingsUpdate() {
  36782. return this.textureNode.value !== this.texture || super.needsBindingsUpdate;
  36783. }
  36784. update() {
  36785. const { textureNode } = this;
  36786. if ( this.texture !== textureNode.value ) {
  36787. this.texture = textureNode.value;
  36788. return true;
  36789. }
  36790. return super.update();
  36791. }
  36792. }
  36793. class NodeSampledCubeTexture extends NodeSampledTexture {
  36794. constructor( name, textureNode, groupNode, access ) {
  36795. super( name, textureNode, groupNode, access );
  36796. this.isSampledCubeTexture = true;
  36797. }
  36798. }
  36799. class NodeSampledTexture3D extends NodeSampledTexture {
  36800. constructor( name, textureNode, groupNode, access ) {
  36801. super( name, textureNode, groupNode, access );
  36802. this.isSampledTexture3D = true;
  36803. }
  36804. }
  36805. const glslMethods = {
  36806. [ MathNode.ATAN2 ]: 'atan',
  36807. textureDimensions: 'textureSize',
  36808. equals: 'equal'
  36809. };
  36810. const precisionLib = {
  36811. low: 'lowp',
  36812. medium: 'mediump',
  36813. high: 'highp'
  36814. };
  36815. const supports$1 = {
  36816. swizzleAssign: true,
  36817. storageBuffer: false
  36818. };
  36819. const defaultPrecisions = `
  36820. precision highp float;
  36821. precision highp int;
  36822. precision highp sampler2D;
  36823. precision highp sampler3D;
  36824. precision highp samplerCube;
  36825. precision highp sampler2DArray;
  36826. precision highp usampler2D;
  36827. precision highp usampler3D;
  36828. precision highp usamplerCube;
  36829. precision highp usampler2DArray;
  36830. precision highp isampler2D;
  36831. precision highp isampler3D;
  36832. precision highp isamplerCube;
  36833. precision highp isampler2DArray;
  36834. precision lowp sampler2DShadow;
  36835. `;
  36836. class GLSLNodeBuilder extends NodeBuilder {
  36837. constructor( object, renderer ) {
  36838. super( object, renderer, new GLSLNodeParser() );
  36839. this.uniformGroups = {};
  36840. this.transforms = [];
  36841. this.instanceBindGroups = false;
  36842. }
  36843. getMethod( method ) {
  36844. return glslMethods[ method ] || method;
  36845. }
  36846. getOutputStructName() {
  36847. return '';
  36848. }
  36849. buildFunctionCode( shaderNode ) {
  36850. const layout = shaderNode.layout;
  36851. const flowData = this.flowShaderNode( shaderNode );
  36852. const parameters = [];
  36853. for ( const input of layout.inputs ) {
  36854. parameters.push( this.getType( input.type ) + ' ' + input.name );
  36855. }
  36856. //
  36857. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  36858. ${ flowData.vars }
  36859. ${ flowData.code }
  36860. return ${ flowData.result };
  36861. }`;
  36862. //
  36863. return code;
  36864. }
  36865. setupPBO( storageBufferNode ) {
  36866. const attribute = storageBufferNode.value;
  36867. if ( attribute.pbo === undefined ) {
  36868. const originalArray = attribute.array;
  36869. const numElements = attribute.count * attribute.itemSize;
  36870. const { itemSize } = attribute;
  36871. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  36872. let format = isInteger ? RedIntegerFormat : RedFormat;
  36873. if ( itemSize === 2 ) {
  36874. format = isInteger ? RGIntegerFormat : RGFormat;
  36875. } else if ( itemSize === 3 ) {
  36876. format = isInteger ? RGBIntegerFormat : RGBFormat;
  36877. } else if ( itemSize === 4 ) {
  36878. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  36879. }
  36880. const typeMap = {
  36881. Float32Array: FloatType,
  36882. Uint8Array: UnsignedByteType,
  36883. Uint16Array: UnsignedShortType,
  36884. Uint32Array: UnsignedIntType,
  36885. Int8Array: ByteType,
  36886. Int16Array: ShortType,
  36887. Int32Array: IntType,
  36888. Uint8ClampedArray: UnsignedByteType,
  36889. };
  36890. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  36891. let height = Math.ceil( ( numElements / itemSize ) / width );
  36892. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  36893. const newSize = width * height * itemSize;
  36894. const newArray = new originalArray.constructor( newSize );
  36895. newArray.set( originalArray, 0 );
  36896. attribute.array = newArray;
  36897. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  36898. pboTexture.needsUpdate = true;
  36899. pboTexture.isPBOTexture = true;
  36900. const pbo = new TextureNode( pboTexture, null, null );
  36901. pbo.setPrecision( 'high' );
  36902. attribute.pboNode = pbo;
  36903. attribute.pbo = pbo.value;
  36904. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36905. }
  36906. }
  36907. getPropertyName( node, shaderStage = this.shaderStage ) {
  36908. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  36909. return shaderStage.charAt( 0 ) + '_' + node.name;
  36910. }
  36911. return super.getPropertyName( node, shaderStage );
  36912. }
  36913. generatePBO( storageArrayElementNode ) {
  36914. const { node, indexNode } = storageArrayElementNode;
  36915. const attribute = node.value;
  36916. if ( this.renderer.backend.has( attribute ) ) {
  36917. const attributeData = this.renderer.backend.get( attribute );
  36918. attributeData.pbo = attribute.pbo;
  36919. }
  36920. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36921. const textureName = this.getPropertyName( nodeUniform );
  36922. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  36923. const indexSnippet = indexNode.build( this, 'uint' );
  36924. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  36925. let propertyName = elementNodeData.propertyName;
  36926. if ( propertyName === undefined ) {
  36927. // property element
  36928. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  36929. propertyName = this.getPropertyName( nodeVar );
  36930. // property size
  36931. const bufferNodeData = this.getDataFromNode( node );
  36932. let propertySizeName = bufferNodeData.propertySizeName;
  36933. if ( propertySizeName === undefined ) {
  36934. propertySizeName = propertyName + 'Size';
  36935. this.getVarFromNode( node, propertySizeName, 'uint' );
  36936. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  36937. bufferNodeData.propertySizeName = propertySizeName;
  36938. }
  36939. //
  36940. const { itemSize } = attribute;
  36941. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  36942. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  36943. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  36944. //
  36945. let prefix = 'vec4';
  36946. if ( attribute.pbo.type === UnsignedIntType ) {
  36947. prefix = 'uvec4';
  36948. } else if ( attribute.pbo.type === IntType ) {
  36949. prefix = 'ivec4';
  36950. }
  36951. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  36952. elementNodeData.propertyName = propertyName;
  36953. }
  36954. return propertyName;
  36955. }
  36956. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  36957. if ( depthSnippet ) {
  36958. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  36959. } else {
  36960. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  36961. }
  36962. }
  36963. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  36964. if ( texture.isDepthTexture ) {
  36965. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  36966. } else {
  36967. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  36968. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  36969. }
  36970. }
  36971. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  36972. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  36973. }
  36974. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  36975. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  36976. }
  36977. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  36978. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  36979. }
  36980. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  36981. if ( shaderStage === 'fragment' ) {
  36982. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  36983. } else {
  36984. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  36985. }
  36986. }
  36987. getVars( shaderStage ) {
  36988. const snippets = [];
  36989. const vars = this.vars[ shaderStage ];
  36990. if ( vars !== undefined ) {
  36991. for ( const variable of vars ) {
  36992. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  36993. }
  36994. }
  36995. return snippets.join( '\n\t' );
  36996. }
  36997. getUniforms( shaderStage ) {
  36998. const uniforms = this.uniforms[ shaderStage ];
  36999. const bindingSnippets = [];
  37000. const uniformGroups = {};
  37001. for ( const uniform of uniforms ) {
  37002. let snippet = null;
  37003. let group = false;
  37004. if ( uniform.type === 'texture' ) {
  37005. const texture = uniform.node.value;
  37006. let typePrefix = '';
  37007. if ( texture.isDataTexture === true ) {
  37008. if ( texture.type === UnsignedIntType ) {
  37009. typePrefix = 'u';
  37010. } else if ( texture.type === IntType ) {
  37011. typePrefix = 'i';
  37012. }
  37013. }
  37014. if ( texture.compareFunction ) {
  37015. snippet = `sampler2DShadow ${ uniform.name };`;
  37016. } else if ( texture.isDataArrayTexture === true ) {
  37017. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  37018. } else {
  37019. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  37020. }
  37021. } else if ( uniform.type === 'cubeTexture' ) {
  37022. snippet = `samplerCube ${ uniform.name };`;
  37023. } else if ( uniform.type === 'texture3D' ) {
  37024. snippet = `sampler3D ${ uniform.name };`;
  37025. } else if ( uniform.type === 'buffer' ) {
  37026. const bufferNode = uniform.node;
  37027. const bufferType = this.getType( bufferNode.bufferType );
  37028. const bufferCount = bufferNode.bufferCount;
  37029. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  37030. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  37031. } else {
  37032. const vectorType = this.getVectorType( uniform.type );
  37033. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  37034. group = true;
  37035. }
  37036. const precision = uniform.node.precision;
  37037. if ( precision !== null ) {
  37038. snippet = precisionLib[ precision ] + ' ' + snippet;
  37039. }
  37040. if ( group ) {
  37041. snippet = '\t' + snippet;
  37042. const groupName = uniform.groupNode.name;
  37043. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  37044. groupSnippets.push( snippet );
  37045. } else {
  37046. snippet = 'uniform ' + snippet;
  37047. bindingSnippets.push( snippet );
  37048. }
  37049. }
  37050. let output = '';
  37051. for ( const name in uniformGroups ) {
  37052. const groupSnippets = uniformGroups[ name ];
  37053. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37054. }
  37055. output += bindingSnippets.join( '\n' );
  37056. return output;
  37057. }
  37058. getTypeFromAttribute( attribute ) {
  37059. let nodeType = super.getTypeFromAttribute( attribute );
  37060. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37061. let dataAttribute = attribute;
  37062. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37063. const array = dataAttribute.array;
  37064. if ( ( array instanceof Uint32Array || array instanceof Int32Array || array instanceof Uint16Array || array instanceof Int16Array ) === false ) {
  37065. nodeType = nodeType.slice( 1 );
  37066. }
  37067. }
  37068. return nodeType;
  37069. }
  37070. getAttributes( shaderStage ) {
  37071. let snippet = '';
  37072. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37073. const attributes = this.getAttributesArray();
  37074. let location = 0;
  37075. for ( const attribute of attributes ) {
  37076. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37077. }
  37078. }
  37079. return snippet;
  37080. }
  37081. getStructMembers( struct ) {
  37082. const snippets = [];
  37083. const members = struct.getMemberTypes();
  37084. for ( let i = 0; i < members.length; i ++ ) {
  37085. const member = members[ i ];
  37086. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  37087. }
  37088. return snippets.join( '\n' );
  37089. }
  37090. getStructs( shaderStage ) {
  37091. const snippets = [];
  37092. const structs = this.structs[ shaderStage ];
  37093. if ( structs.length === 0 ) {
  37094. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37095. }
  37096. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37097. const struct = structs[ index ];
  37098. let snippet = '\n';
  37099. snippet += this.getStructMembers( struct );
  37100. snippet += '\n';
  37101. snippets.push( snippet );
  37102. }
  37103. return snippets.join( '\n\n' );
  37104. }
  37105. getVaryings( shaderStage ) {
  37106. let snippet = '';
  37107. const varyings = this.varyings;
  37108. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37109. for ( const varying of varyings ) {
  37110. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37111. const type = varying.type;
  37112. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37113. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37114. }
  37115. } else if ( shaderStage === 'fragment' ) {
  37116. for ( const varying of varyings ) {
  37117. if ( varying.needsInterpolation ) {
  37118. const type = varying.type;
  37119. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37120. snippet += `${flat}in ${type} ${varying.name};\n`;
  37121. }
  37122. }
  37123. }
  37124. return snippet;
  37125. }
  37126. getVertexIndex() {
  37127. return 'uint( gl_VertexID )';
  37128. }
  37129. getInstanceIndex() {
  37130. return 'uint( gl_InstanceID )';
  37131. }
  37132. getDrawIndex() {
  37133. const extensions = this.renderer.backend.extensions;
  37134. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37135. return 'uint( gl_DrawID )';
  37136. }
  37137. return null;
  37138. }
  37139. getFrontFacing() {
  37140. return 'gl_FrontFacing';
  37141. }
  37142. getFragCoord() {
  37143. return 'gl_FragCoord';
  37144. }
  37145. getFragDepth() {
  37146. return 'gl_FragDepth';
  37147. }
  37148. getExtensions( shaderStage ) {
  37149. let extensions = '';
  37150. if ( shaderStage === 'vertex' ) {
  37151. const ext = this.renderer.backend.extensions;
  37152. const isBatchedMesh = this.object.isBatchedMesh;
  37153. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37154. extensions += '#extension GL_ANGLE_multi_draw : require\n';
  37155. }
  37156. }
  37157. return extensions;
  37158. }
  37159. isAvailable( name ) {
  37160. let result = supports$1[ name ];
  37161. if ( result === undefined ) {
  37162. if ( name === 'float32Filterable' ) {
  37163. const extensions = this.renderer.backend.extensions;
  37164. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  37165. extensions.get( 'OES_texture_float_linear' );
  37166. result = true;
  37167. } else {
  37168. result = false;
  37169. }
  37170. }
  37171. supports$1[ name ] = result;
  37172. }
  37173. return result;
  37174. }
  37175. isFlipY() {
  37176. return true;
  37177. }
  37178. registerTransform( varyingName, attributeNode ) {
  37179. this.transforms.push( { varyingName, attributeNode } );
  37180. }
  37181. getTransforms( /* shaderStage */ ) {
  37182. const transforms = this.transforms;
  37183. let snippet = '';
  37184. for ( let i = 0; i < transforms.length; i ++ ) {
  37185. const transform = transforms[ i ];
  37186. const attributeName = this.getPropertyName( transform.attributeNode );
  37187. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37188. }
  37189. return snippet;
  37190. }
  37191. _getGLSLUniformStruct( name, vars ) {
  37192. return `
  37193. layout( std140 ) uniform ${name} {
  37194. ${vars}
  37195. };`;
  37196. }
  37197. _getGLSLVertexCode( shaderData ) {
  37198. return `#version 300 es
  37199. // extensions
  37200. ${shaderData.extensions}
  37201. // precision
  37202. ${ defaultPrecisions }
  37203. // uniforms
  37204. ${shaderData.uniforms}
  37205. // varyings
  37206. ${shaderData.varyings}
  37207. // attributes
  37208. ${shaderData.attributes}
  37209. // codes
  37210. ${shaderData.codes}
  37211. void main() {
  37212. // vars
  37213. ${shaderData.vars}
  37214. // transforms
  37215. ${shaderData.transforms}
  37216. // flow
  37217. ${shaderData.flow}
  37218. gl_PointSize = 1.0;
  37219. }
  37220. `;
  37221. }
  37222. _getGLSLFragmentCode( shaderData ) {
  37223. return `#version 300 es
  37224. ${ this.getSignature() }
  37225. // precision
  37226. ${ defaultPrecisions }
  37227. // uniforms
  37228. ${shaderData.uniforms}
  37229. // varyings
  37230. ${shaderData.varyings}
  37231. // codes
  37232. ${shaderData.codes}
  37233. ${shaderData.structs}
  37234. void main() {
  37235. // vars
  37236. ${shaderData.vars}
  37237. // flow
  37238. ${shaderData.flow}
  37239. }
  37240. `;
  37241. }
  37242. buildCode() {
  37243. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37244. for ( const shaderStage in shadersData ) {
  37245. let flow = '// code\n\n';
  37246. flow += this.flowCode[ shaderStage ];
  37247. const flowNodes = this.flowNodes[ shaderStage ];
  37248. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37249. for ( const node of flowNodes ) {
  37250. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37251. const slotName = node.name;
  37252. if ( slotName ) {
  37253. if ( flow.length > 0 ) flow += '\n';
  37254. flow += `\t// flow -> ${ slotName }\n\t`;
  37255. }
  37256. flow += `${ flowSlotData.code }\n\t`;
  37257. if ( node === mainNode && shaderStage !== 'compute' ) {
  37258. flow += '// result\n\t';
  37259. if ( shaderStage === 'vertex' ) {
  37260. flow += 'gl_Position = ';
  37261. flow += `${ flowSlotData.result };`;
  37262. } else if ( shaderStage === 'fragment' ) {
  37263. if ( ! node.outputNode.isOutputStructNode ) {
  37264. flow += 'fragColor = ';
  37265. flow += `${ flowSlotData.result };`;
  37266. }
  37267. }
  37268. }
  37269. }
  37270. const stageData = shadersData[ shaderStage ];
  37271. stageData.extensions = this.getExtensions( shaderStage );
  37272. stageData.uniforms = this.getUniforms( shaderStage );
  37273. stageData.attributes = this.getAttributes( shaderStage );
  37274. stageData.varyings = this.getVaryings( shaderStage );
  37275. stageData.vars = this.getVars( shaderStage );
  37276. stageData.structs = this.getStructs( shaderStage );
  37277. stageData.codes = this.getCodes( shaderStage );
  37278. stageData.transforms = this.getTransforms( shaderStage );
  37279. stageData.flow = flow;
  37280. }
  37281. if ( this.material !== null ) {
  37282. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37283. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37284. } else {
  37285. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37286. }
  37287. }
  37288. getUniformFromNode( node, type, shaderStage, name = null ) {
  37289. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37290. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37291. let uniformGPU = nodeData.uniformGPU;
  37292. if ( uniformGPU === undefined ) {
  37293. const group = node.groupNode;
  37294. const groupName = group.name;
  37295. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37296. if ( type === 'texture' ) {
  37297. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37298. bindings.push( uniformGPU );
  37299. } else if ( type === 'cubeTexture' ) {
  37300. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37301. bindings.push( uniformGPU );
  37302. } else if ( type === 'texture3D' ) {
  37303. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37304. bindings.push( uniformGPU );
  37305. } else if ( type === 'buffer' ) {
  37306. node.name = `NodeBuffer_${ node.id }`;
  37307. uniformNode.name = `buffer${ node.id }`;
  37308. const buffer = new NodeUniformBuffer( node, group );
  37309. buffer.name = node.name;
  37310. bindings.push( buffer );
  37311. uniformGPU = buffer;
  37312. } else {
  37313. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37314. let uniformsGroup = uniformsStage[ groupName ];
  37315. if ( uniformsGroup === undefined ) {
  37316. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37317. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37318. uniformsStage[ groupName ] = uniformsGroup;
  37319. bindings.push( uniformsGroup );
  37320. }
  37321. uniformGPU = this.getNodeUniform( uniformNode, type );
  37322. uniformsGroup.addUniform( uniformGPU );
  37323. }
  37324. nodeData.uniformGPU = uniformGPU;
  37325. }
  37326. return uniformNode;
  37327. }
  37328. }
  37329. let vector2 = null;
  37330. let vector4 = null;
  37331. let color4 = null;
  37332. class Backend {
  37333. constructor( parameters = {} ) {
  37334. this.parameters = Object.assign( {}, parameters );
  37335. this.data = new WeakMap();
  37336. this.renderer = null;
  37337. this.domElement = null;
  37338. }
  37339. async init( renderer ) {
  37340. this.renderer = renderer;
  37341. }
  37342. // render context
  37343. begin( /*renderContext*/ ) { }
  37344. finish( /*renderContext*/ ) { }
  37345. // render object
  37346. draw( /*renderObject, info*/ ) { }
  37347. // program
  37348. createProgram( /*program*/ ) { }
  37349. destroyProgram( /*program*/ ) { }
  37350. // bindings
  37351. createBindings( /*renderObject*/ ) { }
  37352. updateBindings( /*renderObject*/ ) { }
  37353. // pipeline
  37354. createRenderPipeline( /*renderObject*/ ) { }
  37355. createComputePipeline( /*computeNode, pipeline*/ ) { }
  37356. destroyPipeline( /*pipeline*/ ) { }
  37357. // cache key
  37358. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  37359. getRenderCacheKey( /*renderObject*/ ) { } // return String
  37360. // node builder
  37361. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  37362. // textures
  37363. createSampler( /*texture*/ ) { }
  37364. createDefaultTexture( /*texture*/ ) { }
  37365. createTexture( /*texture*/ ) { }
  37366. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  37367. // attributes
  37368. createAttribute( /*attribute*/ ) { }
  37369. createIndexAttribute( /*attribute*/ ) { }
  37370. updateAttribute( /*attribute*/ ) { }
  37371. destroyAttribute( /*attribute*/ ) { }
  37372. // canvas
  37373. getContext() { }
  37374. updateSize() { }
  37375. // utils
  37376. resolveTimestampAsync( /*renderContext, type*/ ) { }
  37377. hasFeatureAsync( /*name*/ ) { } // return Boolean
  37378. hasFeature( /*name*/ ) { } // return Boolean
  37379. getInstanceCount( renderObject ) {
  37380. const { object, geometry } = renderObject;
  37381. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  37382. }
  37383. getDrawingBufferSize() {
  37384. vector2 = vector2 || new Vector2();
  37385. return this.renderer.getDrawingBufferSize( vector2 );
  37386. }
  37387. getScissor() {
  37388. vector4 = vector4 || new Vector4();
  37389. return this.renderer.getScissor( vector4 );
  37390. }
  37391. setScissorTest( /*boolean*/ ) { }
  37392. getClearColor() {
  37393. const renderer = this.renderer;
  37394. color4 = color4 || new Color4();
  37395. renderer.getClearColor( color4 );
  37396. color4.getRGB( color4, this.renderer.currentColorSpace );
  37397. return color4;
  37398. }
  37399. getDomElement() {
  37400. let domElement = this.domElement;
  37401. if ( domElement === null ) {
  37402. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  37403. // OffscreenCanvas does not have setAttribute, see #22811
  37404. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  37405. this.domElement = domElement;
  37406. }
  37407. return domElement;
  37408. }
  37409. // resource properties
  37410. set( object, value ) {
  37411. this.data.set( object, value );
  37412. }
  37413. get( object ) {
  37414. let map = this.data.get( object );
  37415. if ( map === undefined ) {
  37416. map = {};
  37417. this.data.set( object, map );
  37418. }
  37419. return map;
  37420. }
  37421. has( object ) {
  37422. return this.data.has( object );
  37423. }
  37424. delete( object ) {
  37425. this.data.delete( object );
  37426. }
  37427. }
  37428. let _id$1 = 0;
  37429. class DualAttributeData {
  37430. constructor( attributeData, dualBuffer ) {
  37431. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  37432. this.type = attributeData.type;
  37433. this.bufferType = attributeData.bufferType;
  37434. this.pbo = attributeData.pbo;
  37435. this.byteLength = attributeData.byteLength;
  37436. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  37437. this.version = attributeData.version;
  37438. this.isInteger = attributeData.isInteger;
  37439. this.activeBufferIndex = 0;
  37440. this.baseId = attributeData.id;
  37441. }
  37442. get id() {
  37443. return `${ this.baseId }|${ this.activeBufferIndex }`;
  37444. }
  37445. get bufferGPU() {
  37446. return this.buffers[ this.activeBufferIndex ];
  37447. }
  37448. get transformBuffer() {
  37449. return this.buffers[ this.activeBufferIndex ^ 1 ];
  37450. }
  37451. switchBuffers() {
  37452. this.activeBufferIndex ^= 1;
  37453. }
  37454. }
  37455. class WebGLAttributeUtils {
  37456. constructor( backend ) {
  37457. this.backend = backend;
  37458. }
  37459. createAttribute( attribute, bufferType ) {
  37460. const backend = this.backend;
  37461. const { gl } = backend;
  37462. const array = attribute.array;
  37463. const usage = attribute.usage || gl.STATIC_DRAW;
  37464. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37465. const bufferData = backend.get( bufferAttribute );
  37466. let bufferGPU = bufferData.bufferGPU;
  37467. if ( bufferGPU === undefined ) {
  37468. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  37469. bufferData.bufferGPU = bufferGPU;
  37470. bufferData.bufferType = bufferType;
  37471. bufferData.version = bufferAttribute.version;
  37472. }
  37473. //attribute.onUploadCallback();
  37474. let type;
  37475. if ( array instanceof Float32Array ) {
  37476. type = gl.FLOAT;
  37477. } else if ( array instanceof Uint16Array ) {
  37478. if ( attribute.isFloat16BufferAttribute ) {
  37479. type = gl.HALF_FLOAT;
  37480. } else {
  37481. type = gl.UNSIGNED_SHORT;
  37482. }
  37483. } else if ( array instanceof Int16Array ) {
  37484. type = gl.SHORT;
  37485. } else if ( array instanceof Uint32Array ) {
  37486. type = gl.UNSIGNED_INT;
  37487. } else if ( array instanceof Int32Array ) {
  37488. type = gl.INT;
  37489. } else if ( array instanceof Int8Array ) {
  37490. type = gl.BYTE;
  37491. } else if ( array instanceof Uint8Array ) {
  37492. type = gl.UNSIGNED_BYTE;
  37493. } else if ( array instanceof Uint8ClampedArray ) {
  37494. type = gl.UNSIGNED_BYTE;
  37495. } else {
  37496. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  37497. }
  37498. let attributeData = {
  37499. bufferGPU,
  37500. bufferType,
  37501. type,
  37502. byteLength: array.byteLength,
  37503. bytesPerElement: array.BYTES_PER_ELEMENT,
  37504. version: attribute.version,
  37505. pbo: attribute.pbo,
  37506. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || type === gl.UNSIGNED_SHORT || attribute.gpuType === IntType,
  37507. id: _id$1 ++
  37508. };
  37509. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  37510. // create buffer for tranform feedback use
  37511. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  37512. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  37513. }
  37514. backend.set( attribute, attributeData );
  37515. }
  37516. updateAttribute( attribute ) {
  37517. const backend = this.backend;
  37518. const { gl } = backend;
  37519. const array = attribute.array;
  37520. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37521. const bufferData = backend.get( bufferAttribute );
  37522. const bufferType = bufferData.bufferType;
  37523. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  37524. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  37525. if ( updateRanges.length === 0 ) {
  37526. // Not using update ranges
  37527. gl.bufferSubData( bufferType, 0, array );
  37528. } else {
  37529. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  37530. const range = updateRanges[ i ];
  37531. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  37532. array, range.start, range.count );
  37533. }
  37534. bufferAttribute.clearUpdateRanges();
  37535. }
  37536. gl.bindBuffer( bufferType, null );
  37537. bufferData.version = bufferAttribute.version;
  37538. }
  37539. destroyAttribute( attribute ) {
  37540. const backend = this.backend;
  37541. const { gl } = backend;
  37542. if ( attribute.isInterleavedBufferAttribute ) {
  37543. backend.delete( attribute.data );
  37544. }
  37545. const attributeData = backend.get( attribute );
  37546. gl.deleteBuffer( attributeData.bufferGPU );
  37547. backend.delete( attribute );
  37548. }
  37549. async getArrayBufferAsync( attribute ) {
  37550. const backend = this.backend;
  37551. const { gl } = backend;
  37552. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37553. const { bufferGPU } = backend.get( bufferAttribute );
  37554. const array = attribute.array;
  37555. const byteLength = array.byteLength;
  37556. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  37557. const writeBuffer = gl.createBuffer();
  37558. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  37559. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  37560. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  37561. await backend.utils._clientWaitAsync();
  37562. const dstBuffer = new attribute.array.constructor( array.length );
  37563. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  37564. gl.deleteBuffer( writeBuffer );
  37565. return dstBuffer.buffer;
  37566. }
  37567. _createBuffer( gl, bufferType, array, usage ) {
  37568. const bufferGPU = gl.createBuffer();
  37569. gl.bindBuffer( bufferType, bufferGPU );
  37570. gl.bufferData( bufferType, array, usage );
  37571. gl.bindBuffer( bufferType, null );
  37572. return bufferGPU;
  37573. }
  37574. }
  37575. let initialized$1 = false, equationToGL, factorToGL;
  37576. class WebGLState {
  37577. constructor( backend ) {
  37578. this.backend = backend;
  37579. this.gl = this.backend.gl;
  37580. this.enabled = {};
  37581. this.currentFlipSided = null;
  37582. this.currentCullFace = null;
  37583. this.currentProgram = null;
  37584. this.currentBlendingEnabled = false;
  37585. this.currentBlending = null;
  37586. this.currentBlendSrc = null;
  37587. this.currentBlendDst = null;
  37588. this.currentBlendSrcAlpha = null;
  37589. this.currentBlendDstAlpha = null;
  37590. this.currentPremultipledAlpha = null;
  37591. this.currentPolygonOffsetFactor = null;
  37592. this.currentPolygonOffsetUnits = null;
  37593. this.currentColorMask = null;
  37594. this.currentDepthFunc = null;
  37595. this.currentDepthMask = null;
  37596. this.currentStencilFunc = null;
  37597. this.currentStencilRef = null;
  37598. this.currentStencilFuncMask = null;
  37599. this.currentStencilFail = null;
  37600. this.currentStencilZFail = null;
  37601. this.currentStencilZPass = null;
  37602. this.currentStencilMask = null;
  37603. this.currentLineWidth = null;
  37604. this.currentBoundFramebuffers = {};
  37605. this.currentDrawbuffers = new WeakMap();
  37606. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  37607. this.currentTextureSlot = null;
  37608. this.currentBoundTextures = {};
  37609. if ( initialized$1 === false ) {
  37610. this._init( this.gl );
  37611. initialized$1 = true;
  37612. }
  37613. }
  37614. _init( gl ) {
  37615. // Store only WebGL constants here.
  37616. equationToGL = {
  37617. [ AddEquation ]: gl.FUNC_ADD,
  37618. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  37619. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  37620. };
  37621. factorToGL = {
  37622. [ ZeroFactor ]: gl.ZERO,
  37623. [ OneFactor ]: gl.ONE,
  37624. [ SrcColorFactor ]: gl.SRC_COLOR,
  37625. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  37626. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  37627. [ DstColorFactor ]: gl.DST_COLOR,
  37628. [ DstAlphaFactor ]: gl.DST_ALPHA,
  37629. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  37630. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  37631. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  37632. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  37633. };
  37634. }
  37635. enable( id ) {
  37636. const { enabled } = this;
  37637. if ( enabled[ id ] !== true ) {
  37638. this.gl.enable( id );
  37639. enabled[ id ] = true;
  37640. }
  37641. }
  37642. disable( id ) {
  37643. const { enabled } = this;
  37644. if ( enabled[ id ] !== false ) {
  37645. this.gl.disable( id );
  37646. enabled[ id ] = false;
  37647. }
  37648. }
  37649. setFlipSided( flipSided ) {
  37650. if ( this.currentFlipSided !== flipSided ) {
  37651. const { gl } = this;
  37652. if ( flipSided ) {
  37653. gl.frontFace( gl.CW );
  37654. } else {
  37655. gl.frontFace( gl.CCW );
  37656. }
  37657. this.currentFlipSided = flipSided;
  37658. }
  37659. }
  37660. setCullFace( cullFace ) {
  37661. const { gl } = this;
  37662. if ( cullFace !== CullFaceNone ) {
  37663. this.enable( gl.CULL_FACE );
  37664. if ( cullFace !== this.currentCullFace ) {
  37665. if ( cullFace === CullFaceBack ) {
  37666. gl.cullFace( gl.BACK );
  37667. } else if ( cullFace === CullFaceFront ) {
  37668. gl.cullFace( gl.FRONT );
  37669. } else {
  37670. gl.cullFace( gl.FRONT_AND_BACK );
  37671. }
  37672. }
  37673. } else {
  37674. this.disable( gl.CULL_FACE );
  37675. }
  37676. this.currentCullFace = cullFace;
  37677. }
  37678. setLineWidth( width ) {
  37679. const { currentLineWidth, gl } = this;
  37680. if ( width !== currentLineWidth ) {
  37681. gl.lineWidth( width );
  37682. this.currentLineWidth = width;
  37683. }
  37684. }
  37685. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  37686. const { gl } = this;
  37687. if ( blending === NoBlending ) {
  37688. if ( this.currentBlendingEnabled === true ) {
  37689. this.disable( gl.BLEND );
  37690. this.currentBlendingEnabled = false;
  37691. }
  37692. return;
  37693. }
  37694. if ( this.currentBlendingEnabled === false ) {
  37695. this.enable( gl.BLEND );
  37696. this.currentBlendingEnabled = true;
  37697. }
  37698. if ( blending !== CustomBlending ) {
  37699. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  37700. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  37701. gl.blendEquation( gl.FUNC_ADD );
  37702. this.currentBlendEquation = AddEquation;
  37703. this.currentBlendEquationAlpha = AddEquation;
  37704. }
  37705. if ( premultipliedAlpha ) {
  37706. switch ( blending ) {
  37707. case NormalBlending:
  37708. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37709. break;
  37710. case AdditiveBlending:
  37711. gl.blendFunc( gl.ONE, gl.ONE );
  37712. break;
  37713. case SubtractiveBlending:
  37714. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37715. break;
  37716. case MultiplyBlending:
  37717. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  37718. break;
  37719. default:
  37720. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37721. break;
  37722. }
  37723. } else {
  37724. switch ( blending ) {
  37725. case NormalBlending:
  37726. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37727. break;
  37728. case AdditiveBlending:
  37729. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  37730. break;
  37731. case SubtractiveBlending:
  37732. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37733. break;
  37734. case MultiplyBlending:
  37735. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  37736. break;
  37737. default:
  37738. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37739. break;
  37740. }
  37741. }
  37742. this.currentBlendSrc = null;
  37743. this.currentBlendDst = null;
  37744. this.currentBlendSrcAlpha = null;
  37745. this.currentBlendDstAlpha = null;
  37746. this.currentBlending = blending;
  37747. this.currentPremultipledAlpha = premultipliedAlpha;
  37748. }
  37749. return;
  37750. }
  37751. // custom blending
  37752. blendEquationAlpha = blendEquationAlpha || blendEquation;
  37753. blendSrcAlpha = blendSrcAlpha || blendSrc;
  37754. blendDstAlpha = blendDstAlpha || blendDst;
  37755. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  37756. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  37757. this.currentBlendEquation = blendEquation;
  37758. this.currentBlendEquationAlpha = blendEquationAlpha;
  37759. }
  37760. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  37761. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  37762. this.currentBlendSrc = blendSrc;
  37763. this.currentBlendDst = blendDst;
  37764. this.currentBlendSrcAlpha = blendSrcAlpha;
  37765. this.currentBlendDstAlpha = blendDstAlpha;
  37766. }
  37767. this.currentBlending = blending;
  37768. this.currentPremultipledAlpha = false;
  37769. }
  37770. setColorMask( colorMask ) {
  37771. if ( this.currentColorMask !== colorMask ) {
  37772. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  37773. this.currentColorMask = colorMask;
  37774. }
  37775. }
  37776. setDepthTest( depthTest ) {
  37777. const { gl } = this;
  37778. if ( depthTest ) {
  37779. this.enable( gl.DEPTH_TEST );
  37780. } else {
  37781. this.disable( gl.DEPTH_TEST );
  37782. }
  37783. }
  37784. setDepthMask( depthMask ) {
  37785. if ( this.currentDepthMask !== depthMask ) {
  37786. this.gl.depthMask( depthMask );
  37787. this.currentDepthMask = depthMask;
  37788. }
  37789. }
  37790. setDepthFunc( depthFunc ) {
  37791. if ( this.currentDepthFunc !== depthFunc ) {
  37792. const { gl } = this;
  37793. switch ( depthFunc ) {
  37794. case NeverDepth:
  37795. gl.depthFunc( gl.NEVER );
  37796. break;
  37797. case AlwaysDepth:
  37798. gl.depthFunc( gl.ALWAYS );
  37799. break;
  37800. case LessDepth:
  37801. gl.depthFunc( gl.LESS );
  37802. break;
  37803. case LessEqualDepth:
  37804. gl.depthFunc( gl.LEQUAL );
  37805. break;
  37806. case EqualDepth:
  37807. gl.depthFunc( gl.EQUAL );
  37808. break;
  37809. case GreaterEqualDepth:
  37810. gl.depthFunc( gl.GEQUAL );
  37811. break;
  37812. case GreaterDepth:
  37813. gl.depthFunc( gl.GREATER );
  37814. break;
  37815. case NotEqualDepth:
  37816. gl.depthFunc( gl.NOTEQUAL );
  37817. break;
  37818. default:
  37819. gl.depthFunc( gl.LEQUAL );
  37820. }
  37821. this.currentDepthFunc = depthFunc;
  37822. }
  37823. }
  37824. setStencilTest( stencilTest ) {
  37825. const { gl } = this;
  37826. if ( stencilTest ) {
  37827. this.enable( gl.STENCIL_TEST );
  37828. } else {
  37829. this.disable( gl.STENCIL_TEST );
  37830. }
  37831. }
  37832. setStencilMask( stencilMask ) {
  37833. if ( this.currentStencilMask !== stencilMask ) {
  37834. this.gl.stencilMask( stencilMask );
  37835. this.currentStencilMask = stencilMask;
  37836. }
  37837. }
  37838. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  37839. if ( this.currentStencilFunc !== stencilFunc ||
  37840. this.currentStencilRef !== stencilRef ||
  37841. this.currentStencilFuncMask !== stencilMask ) {
  37842. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  37843. this.currentStencilFunc = stencilFunc;
  37844. this.currentStencilRef = stencilRef;
  37845. this.currentStencilFuncMask = stencilMask;
  37846. }
  37847. }
  37848. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  37849. if ( this.currentStencilFail !== stencilFail ||
  37850. this.currentStencilZFail !== stencilZFail ||
  37851. this.currentStencilZPass !== stencilZPass ) {
  37852. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  37853. this.currentStencilFail = stencilFail;
  37854. this.currentStencilZFail = stencilZFail;
  37855. this.currentStencilZPass = stencilZPass;
  37856. }
  37857. }
  37858. setMaterial( material, frontFaceCW ) {
  37859. const { gl } = this;
  37860. material.side === DoubleSide
  37861. ? this.disable( gl.CULL_FACE )
  37862. : this.enable( gl.CULL_FACE );
  37863. let flipSided = ( material.side === BackSide );
  37864. if ( frontFaceCW ) flipSided = ! flipSided;
  37865. this.setFlipSided( flipSided );
  37866. ( material.blending === NormalBlending && material.transparent === false )
  37867. ? this.setBlending( NoBlending )
  37868. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  37869. this.setDepthFunc( material.depthFunc );
  37870. this.setDepthTest( material.depthTest );
  37871. this.setDepthMask( material.depthWrite );
  37872. this.setColorMask( material.colorWrite );
  37873. const stencilWrite = material.stencilWrite;
  37874. this.setStencilTest( stencilWrite );
  37875. if ( stencilWrite ) {
  37876. this.setStencilMask( material.stencilWriteMask );
  37877. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  37878. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  37879. }
  37880. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  37881. material.alphaToCoverage === true
  37882. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  37883. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  37884. }
  37885. setPolygonOffset( polygonOffset, factor, units ) {
  37886. const { gl } = this;
  37887. if ( polygonOffset ) {
  37888. this.enable( gl.POLYGON_OFFSET_FILL );
  37889. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  37890. gl.polygonOffset( factor, units );
  37891. this.currentPolygonOffsetFactor = factor;
  37892. this.currentPolygonOffsetUnits = units;
  37893. }
  37894. } else {
  37895. this.disable( gl.POLYGON_OFFSET_FILL );
  37896. }
  37897. }
  37898. useProgram( program ) {
  37899. if ( this.currentProgram !== program ) {
  37900. this.gl.useProgram( program );
  37901. this.currentProgram = program;
  37902. return true;
  37903. }
  37904. return false;
  37905. }
  37906. // framebuffer
  37907. bindFramebuffer( target, framebuffer ) {
  37908. const { gl, currentBoundFramebuffers } = this;
  37909. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  37910. gl.bindFramebuffer( target, framebuffer );
  37911. currentBoundFramebuffers[ target ] = framebuffer;
  37912. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  37913. if ( target === gl.DRAW_FRAMEBUFFER ) {
  37914. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  37915. }
  37916. if ( target === gl.FRAMEBUFFER ) {
  37917. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  37918. }
  37919. return true;
  37920. }
  37921. return false;
  37922. }
  37923. drawBuffers( renderContext, framebuffer ) {
  37924. const { gl } = this;
  37925. let drawBuffers = [];
  37926. let needsUpdate = false;
  37927. if ( renderContext.textures !== null ) {
  37928. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  37929. if ( drawBuffers === undefined ) {
  37930. drawBuffers = [];
  37931. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  37932. }
  37933. const textures = renderContext.textures;
  37934. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  37935. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  37936. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  37937. }
  37938. drawBuffers.length = textures.length;
  37939. needsUpdate = true;
  37940. }
  37941. } else {
  37942. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  37943. drawBuffers[ 0 ] = gl.BACK;
  37944. needsUpdate = true;
  37945. }
  37946. }
  37947. if ( needsUpdate ) {
  37948. gl.drawBuffers( drawBuffers );
  37949. }
  37950. }
  37951. // texture
  37952. activeTexture( webglSlot ) {
  37953. const { gl, currentTextureSlot, maxTextures } = this;
  37954. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37955. if ( currentTextureSlot !== webglSlot ) {
  37956. gl.activeTexture( webglSlot );
  37957. this.currentTextureSlot = webglSlot;
  37958. }
  37959. }
  37960. bindTexture( webglType, webglTexture, webglSlot ) {
  37961. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  37962. if ( webglSlot === undefined ) {
  37963. if ( currentTextureSlot === null ) {
  37964. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37965. } else {
  37966. webglSlot = currentTextureSlot;
  37967. }
  37968. }
  37969. let boundTexture = currentBoundTextures[ webglSlot ];
  37970. if ( boundTexture === undefined ) {
  37971. boundTexture = { type: undefined, texture: undefined };
  37972. currentBoundTextures[ webglSlot ] = boundTexture;
  37973. }
  37974. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  37975. if ( currentTextureSlot !== webglSlot ) {
  37976. gl.activeTexture( webglSlot );
  37977. this.currentTextureSlot = webglSlot;
  37978. }
  37979. gl.bindTexture( webglType, webglTexture );
  37980. boundTexture.type = webglType;
  37981. boundTexture.texture = webglTexture;
  37982. }
  37983. }
  37984. unbindTexture() {
  37985. const { gl, currentTextureSlot, currentBoundTextures } = this;
  37986. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  37987. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  37988. gl.bindTexture( boundTexture.type, null );
  37989. boundTexture.type = undefined;
  37990. boundTexture.texture = undefined;
  37991. }
  37992. }
  37993. }
  37994. class WebGLUtils {
  37995. constructor( backend ) {
  37996. this.backend = backend;
  37997. this.gl = this.backend.gl;
  37998. this.extensions = backend.extensions;
  37999. }
  38000. convert( p, colorSpace = NoColorSpace ) {
  38001. const { gl, extensions } = this;
  38002. let extension;
  38003. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  38004. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  38005. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  38006. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  38007. if ( p === ByteType ) return gl.BYTE;
  38008. if ( p === ShortType ) return gl.SHORT;
  38009. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  38010. if ( p === IntType ) return gl.INT;
  38011. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  38012. if ( p === FloatType ) return gl.FLOAT;
  38013. if ( p === HalfFloatType ) {
  38014. return gl.HALF_FLOAT;
  38015. }
  38016. if ( p === AlphaFormat ) return gl.ALPHA;
  38017. if ( p === RGBFormat ) return gl.RGB;
  38018. if ( p === RGBAFormat ) return gl.RGBA;
  38019. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  38020. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  38021. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  38022. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  38023. // WebGL2 formats.
  38024. if ( p === RedFormat ) return gl.RED;
  38025. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  38026. if ( p === RGFormat ) return gl.RG;
  38027. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  38028. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  38029. // S3TC
  38030. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  38031. if ( colorSpace === SRGBColorSpace ) {
  38032. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  38033. if ( extension !== null ) {
  38034. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  38035. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  38036. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  38037. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  38038. } else {
  38039. return null;
  38040. }
  38041. } else {
  38042. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  38043. if ( extension !== null ) {
  38044. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  38045. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  38046. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  38047. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  38048. } else {
  38049. return null;
  38050. }
  38051. }
  38052. }
  38053. // PVRTC
  38054. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  38055. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  38056. if ( extension !== null ) {
  38057. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  38058. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  38059. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  38060. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  38061. } else {
  38062. return null;
  38063. }
  38064. }
  38065. // ETC
  38066. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  38067. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  38068. if ( extension !== null ) {
  38069. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  38070. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  38071. } else {
  38072. return null;
  38073. }
  38074. }
  38075. // ASTC
  38076. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  38077. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  38078. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  38079. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  38080. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  38081. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  38082. if ( extension !== null ) {
  38083. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  38084. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  38085. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  38086. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  38087. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  38088. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  38089. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  38090. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  38091. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  38092. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  38093. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  38094. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  38095. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  38096. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  38097. } else {
  38098. return null;
  38099. }
  38100. }
  38101. // BPTC
  38102. if ( p === RGBA_BPTC_Format ) {
  38103. extension = extensions.get( 'EXT_texture_compression_bptc' );
  38104. if ( extension !== null ) {
  38105. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  38106. } else {
  38107. return null;
  38108. }
  38109. }
  38110. // RGTC
  38111. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  38112. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  38113. if ( extension !== null ) {
  38114. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  38115. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  38116. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  38117. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  38118. } else {
  38119. return null;
  38120. }
  38121. }
  38122. //
  38123. if ( p === UnsignedInt248Type ) {
  38124. return gl.UNSIGNED_INT_24_8;
  38125. }
  38126. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  38127. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  38128. }
  38129. _clientWaitAsync() {
  38130. const { gl } = this;
  38131. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  38132. gl.flush();
  38133. return new Promise( ( resolve, reject ) => {
  38134. function test() {
  38135. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  38136. if ( res === gl.WAIT_FAILED ) {
  38137. gl.deleteSync( sync );
  38138. reject();
  38139. return;
  38140. }
  38141. if ( res === gl.TIMEOUT_EXPIRED ) {
  38142. requestAnimationFrame( test );
  38143. return;
  38144. }
  38145. gl.deleteSync( sync );
  38146. resolve();
  38147. }
  38148. test();
  38149. } );
  38150. }
  38151. }
  38152. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  38153. class WebGLTextureUtils {
  38154. constructor( backend ) {
  38155. this.backend = backend;
  38156. this.gl = backend.gl;
  38157. this.extensions = backend.extensions;
  38158. this.defaultTextures = {};
  38159. if ( initialized === false ) {
  38160. this._init( this.gl );
  38161. initialized = true;
  38162. }
  38163. }
  38164. _init( gl ) {
  38165. // Store only WebGL constants here.
  38166. wrappingToGL = {
  38167. [ RepeatWrapping ]: gl.REPEAT,
  38168. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  38169. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  38170. };
  38171. filterToGL = {
  38172. [ NearestFilter ]: gl.NEAREST,
  38173. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  38174. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  38175. [ LinearFilter ]: gl.LINEAR,
  38176. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  38177. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  38178. };
  38179. compareToGL = {
  38180. [ NeverCompare ]: gl.NEVER,
  38181. [ AlwaysCompare ]: gl.ALWAYS,
  38182. [ LessCompare ]: gl.LESS,
  38183. [ LessEqualCompare ]: gl.LEQUAL,
  38184. [ EqualCompare ]: gl.EQUAL,
  38185. [ GreaterEqualCompare ]: gl.GEQUAL,
  38186. [ GreaterCompare ]: gl.GREATER,
  38187. [ NotEqualCompare ]: gl.NOTEQUAL
  38188. };
  38189. }
  38190. filterFallback( f ) {
  38191. const { gl } = this;
  38192. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  38193. return gl.NEAREST;
  38194. }
  38195. return gl.LINEAR;
  38196. }
  38197. getGLTextureType( texture ) {
  38198. const { gl } = this;
  38199. let glTextureType;
  38200. if ( texture.isCubeTexture === true ) {
  38201. glTextureType = gl.TEXTURE_CUBE_MAP;
  38202. } else if ( texture.isDataArrayTexture === true ) {
  38203. glTextureType = gl.TEXTURE_2D_ARRAY;
  38204. } else if ( texture.isData3DTexture === true ) {
  38205. glTextureType = gl.TEXTURE_3D;
  38206. } else {
  38207. glTextureType = gl.TEXTURE_2D;
  38208. }
  38209. return glTextureType;
  38210. }
  38211. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  38212. const { gl, extensions } = this;
  38213. if ( internalFormatName !== null ) {
  38214. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  38215. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  38216. }
  38217. let internalFormat = glFormat;
  38218. if ( glFormat === gl.RED ) {
  38219. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  38220. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  38221. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  38222. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  38223. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38224. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38225. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38226. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38227. }
  38228. if ( glFormat === gl.RED_INTEGER ) {
  38229. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  38230. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  38231. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38232. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38233. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38234. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38235. }
  38236. if ( glFormat === gl.RG ) {
  38237. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  38238. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  38239. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  38240. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  38241. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38242. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38243. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38244. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38245. }
  38246. if ( glFormat === gl.RG_INTEGER ) {
  38247. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  38248. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  38249. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38250. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38251. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38252. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38253. }
  38254. if ( glFormat === gl.RGB ) {
  38255. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  38256. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  38257. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  38258. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  38259. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38260. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38261. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38262. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38263. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  38264. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  38265. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38266. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  38267. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  38268. }
  38269. if ( glFormat === gl.RGB_INTEGER ) {
  38270. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  38271. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  38272. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38273. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38274. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38275. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38276. }
  38277. if ( glFormat === gl.RGBA ) {
  38278. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  38279. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  38280. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  38281. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  38282. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38283. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38284. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38285. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38286. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  38287. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  38288. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38289. }
  38290. if ( glFormat === gl.RGBA_INTEGER ) {
  38291. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  38292. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  38293. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38294. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38295. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38296. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38297. }
  38298. if ( glFormat === gl.DEPTH_COMPONENT ) {
  38299. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  38300. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  38301. }
  38302. if ( glFormat === gl.DEPTH_STENCIL ) {
  38303. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  38304. }
  38305. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  38306. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  38307. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  38308. extensions.get( 'EXT_color_buffer_float' );
  38309. }
  38310. return internalFormat;
  38311. }
  38312. setTextureParameters( textureType, texture ) {
  38313. const { gl, extensions, backend } = this;
  38314. const { currentAnisotropy } = backend.get( texture );
  38315. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  38316. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  38317. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  38318. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  38319. }
  38320. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  38321. // follow WebGPU backend mapping for texture filtering
  38322. const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter;
  38323. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  38324. if ( texture.compareFunction ) {
  38325. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  38326. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  38327. }
  38328. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38329. if ( texture.magFilter === NearestFilter ) return;
  38330. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  38331. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  38332. if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) {
  38333. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38334. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  38335. backend.get( texture ).currentAnisotropy = texture.anisotropy;
  38336. }
  38337. }
  38338. }
  38339. createDefaultTexture( texture ) {
  38340. const { gl, backend, defaultTextures } = this;
  38341. const glTextureType = this.getGLTextureType( texture );
  38342. let textureGPU = defaultTextures[ glTextureType ];
  38343. if ( textureGPU === undefined ) {
  38344. textureGPU = gl.createTexture();
  38345. backend.state.bindTexture( glTextureType, textureGPU );
  38346. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  38347. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  38348. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  38349. defaultTextures[ glTextureType ] = textureGPU;
  38350. }
  38351. backend.set( texture, {
  38352. textureGPU,
  38353. glTextureType,
  38354. isDefault: true
  38355. } );
  38356. }
  38357. createTexture( texture, options ) {
  38358. const { gl, backend } = this;
  38359. const { levels, width, height, depth } = options;
  38360. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  38361. const glType = backend.utils.convert( texture.type );
  38362. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  38363. const textureGPU = gl.createTexture();
  38364. const glTextureType = this.getGLTextureType( texture );
  38365. backend.state.bindTexture( glTextureType, textureGPU );
  38366. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  38367. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  38368. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  38369. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  38370. this.setTextureParameters( glTextureType, texture );
  38371. if ( texture.isDataArrayTexture ) {
  38372. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  38373. } else if ( texture.isData3DTexture ) {
  38374. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  38375. } else if ( ! texture.isVideoTexture ) {
  38376. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  38377. }
  38378. backend.set( texture, {
  38379. textureGPU,
  38380. glTextureType,
  38381. glFormat,
  38382. glType,
  38383. glInternalFormat
  38384. } );
  38385. }
  38386. copyBufferToTexture( buffer, texture ) {
  38387. const { gl, backend } = this;
  38388. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  38389. const { width, height } = texture.source.data;
  38390. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  38391. backend.state.bindTexture( glTextureType, textureGPU );
  38392. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  38393. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  38394. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  38395. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  38396. backend.state.unbindTexture();
  38397. // debug
  38398. // const framebuffer = gl.createFramebuffer();
  38399. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  38400. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  38401. // const readout = new Float32Array( width * height * 4 );
  38402. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  38403. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  38404. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  38405. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  38406. // console.log( readout );
  38407. }
  38408. updateTexture( texture, options ) {
  38409. const { gl } = this;
  38410. const { width, height } = options;
  38411. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  38412. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  38413. return;
  38414. const getImage = ( source ) => {
  38415. if ( source.isDataTexture ) {
  38416. return source.image.data;
  38417. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  38418. return source;
  38419. }
  38420. return source.data;
  38421. };
  38422. this.backend.state.bindTexture( glTextureType, textureGPU );
  38423. if ( texture.isCompressedTexture ) {
  38424. const mipmaps = texture.mipmaps;
  38425. for ( let i = 0; i < mipmaps.length; i ++ ) {
  38426. const mipmap = mipmaps[ i ];
  38427. if ( texture.isCompressedArrayTexture ) {
  38428. const image = options.image;
  38429. if ( texture.format !== gl.RGBA ) {
  38430. if ( glFormat !== null ) {
  38431. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  38432. } else {
  38433. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  38434. }
  38435. } else {
  38436. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  38437. }
  38438. } else {
  38439. if ( glFormat !== null ) {
  38440. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  38441. } else {
  38442. console.warn( 'Unsupported compressed texture format' );
  38443. }
  38444. }
  38445. }
  38446. } else if ( texture.isCubeTexture ) {
  38447. const images = options.images;
  38448. for ( let i = 0; i < 6; i ++ ) {
  38449. const image = getImage( images[ i ] );
  38450. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  38451. }
  38452. } else if ( texture.isDataArrayTexture ) {
  38453. const image = options.image;
  38454. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38455. } else if ( texture.isData3DTexture ) {
  38456. const image = options.image;
  38457. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38458. } else if ( texture.isVideoTexture ) {
  38459. texture.update();
  38460. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  38461. } else {
  38462. const image = getImage( options.image );
  38463. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  38464. }
  38465. }
  38466. generateMipmaps( texture ) {
  38467. const { gl, backend } = this;
  38468. const { textureGPU, glTextureType } = backend.get( texture );
  38469. backend.state.bindTexture( glTextureType, textureGPU );
  38470. gl.generateMipmap( glTextureType );
  38471. }
  38472. deallocateRenderBuffers( renderTarget ) {
  38473. const { gl, backend } = this;
  38474. // remove framebuffer reference
  38475. if ( renderTarget ) {
  38476. const renderContextData = backend.get( renderTarget );
  38477. renderContextData.renderBufferStorageSetup = undefined;
  38478. if ( renderContextData.framebuffer ) {
  38479. gl.deleteFramebuffer( renderContextData.framebuffer );
  38480. renderContextData.framebuffer = undefined;
  38481. }
  38482. if ( renderContextData.depthRenderbuffer ) {
  38483. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  38484. renderContextData.depthRenderbuffer = undefined;
  38485. }
  38486. if ( renderContextData.stencilRenderbuffer ) {
  38487. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  38488. renderContextData.stencilRenderbuffer = undefined;
  38489. }
  38490. if ( renderContextData.msaaFrameBuffer ) {
  38491. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  38492. renderContextData.msaaFrameBuffer = undefined;
  38493. }
  38494. if ( renderContextData.msaaRenderbuffers ) {
  38495. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  38496. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  38497. }
  38498. renderContextData.msaaRenderbuffers = undefined;
  38499. }
  38500. }
  38501. }
  38502. destroyTexture( texture ) {
  38503. const { gl, backend } = this;
  38504. const { textureGPU, renderTarget } = backend.get( texture );
  38505. this.deallocateRenderBuffers( renderTarget );
  38506. gl.deleteTexture( textureGPU );
  38507. backend.delete( texture );
  38508. }
  38509. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38510. const { gl, backend } = this;
  38511. const { state } = this.backend;
  38512. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  38513. let width, height, minX, minY;
  38514. let dstX, dstY;
  38515. if ( srcRegion !== null ) {
  38516. width = srcRegion.max.x - srcRegion.min.x;
  38517. height = srcRegion.max.y - srcRegion.min.y;
  38518. minX = srcRegion.min.x;
  38519. minY = srcRegion.min.y;
  38520. } else {
  38521. width = srcTexture.image.width;
  38522. height = srcTexture.image.height;
  38523. minX = 0;
  38524. minY = 0;
  38525. }
  38526. if ( dstPosition !== null ) {
  38527. dstX = dstPosition.x;
  38528. dstY = dstPosition.y;
  38529. } else {
  38530. dstX = 0;
  38531. dstY = 0;
  38532. }
  38533. state.bindTexture( glTextureType, dstTextureGPU );
  38534. // As another texture upload may have changed pixelStorei
  38535. // parameters, make sure they are correct for the dstTexture
  38536. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38537. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  38538. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  38539. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38540. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  38541. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  38542. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  38543. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  38544. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  38545. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  38546. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  38547. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  38548. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  38549. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  38550. if ( srcTexture.isDataTexture ) {
  38551. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  38552. } else {
  38553. if ( srcTexture.isCompressedTexture ) {
  38554. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  38555. } else {
  38556. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  38557. }
  38558. }
  38559. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  38560. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  38561. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  38562. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  38563. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  38564. // Generate mipmaps only when copying level 0
  38565. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  38566. state.unbindTexture();
  38567. }
  38568. copyFramebufferToTexture( texture, renderContext ) {
  38569. const { gl } = this;
  38570. const { state } = this.backend;
  38571. const { textureGPU } = this.backend.get( texture );
  38572. const width = texture.image.width;
  38573. const height = texture.image.height;
  38574. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  38575. if ( requireDrawFrameBuffer ) {
  38576. let mask;
  38577. let attachment;
  38578. if ( texture.isDepthTexture === true ) {
  38579. mask = gl.DEPTH_BUFFER_BIT;
  38580. attachment = gl.DEPTH_ATTACHMENT;
  38581. if ( renderContext.stencil ) {
  38582. mask |= gl.STENCIL_BUFFER_BIT;
  38583. }
  38584. } else {
  38585. mask = gl.COLOR_BUFFER_BIT;
  38586. attachment = gl.COLOR_ATTACHMENT0;
  38587. }
  38588. const fb = gl.createFramebuffer();
  38589. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38590. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  38591. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  38592. gl.deleteFramebuffer( fb );
  38593. } else {
  38594. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  38595. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  38596. state.unbindTexture();
  38597. }
  38598. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  38599. this.backend._setFramebuffer( renderContext );
  38600. }
  38601. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  38602. setupRenderBufferStorage( renderbuffer, renderContext ) {
  38603. const { gl } = this;
  38604. const renderTarget = renderContext.renderTarget;
  38605. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  38606. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  38607. if ( depthBuffer && ! stencilBuffer ) {
  38608. let glInternalFormat = gl.DEPTH_COMPONENT24;
  38609. if ( samples > 0 ) {
  38610. if ( depthTexture && depthTexture.isDepthTexture ) {
  38611. if ( depthTexture.type === gl.FLOAT ) {
  38612. glInternalFormat = gl.DEPTH_COMPONENT32F;
  38613. }
  38614. }
  38615. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  38616. } else {
  38617. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  38618. }
  38619. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38620. } else if ( depthBuffer && stencilBuffer ) {
  38621. if ( samples > 0 ) {
  38622. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  38623. } else {
  38624. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  38625. }
  38626. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38627. }
  38628. }
  38629. async copyTextureToBuffer( texture, x, y, width, height ) {
  38630. const { backend, gl } = this;
  38631. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  38632. const fb = gl.createFramebuffer();
  38633. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  38634. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  38635. const typedArrayType = this._getTypedArrayType( glType );
  38636. const bytesPerTexel = this._getBytesPerTexel( glFormat );
  38637. const elementCount = width * height;
  38638. const byteLength = elementCount * bytesPerTexel;
  38639. const buffer = gl.createBuffer();
  38640. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38641. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  38642. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  38643. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38644. await backend.utils._clientWaitAsync();
  38645. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  38646. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38647. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  38648. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38649. gl.deleteFramebuffer( fb );
  38650. return dstBuffer;
  38651. }
  38652. _getTypedArrayType( glType ) {
  38653. const { gl } = this;
  38654. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  38655. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  38656. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  38657. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  38658. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  38659. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  38660. if ( glType === gl.FLOAT ) return Float32Array;
  38661. throw new Error( `Unsupported WebGL type: ${glType}` );
  38662. }
  38663. _getBytesPerTexel( glFormat ) {
  38664. const { gl } = this;
  38665. if ( glFormat === gl.RGBA ) return 4;
  38666. if ( glFormat === gl.RGB ) return 3;
  38667. if ( glFormat === gl.ALPHA ) return 1;
  38668. }
  38669. }
  38670. class WebGLExtensions {
  38671. constructor( backend ) {
  38672. this.backend = backend;
  38673. this.gl = this.backend.gl;
  38674. this.availableExtensions = this.gl.getSupportedExtensions();
  38675. this.extensions = {};
  38676. }
  38677. get( name ) {
  38678. let extension = this.extensions[ name ];
  38679. if ( extension === undefined ) {
  38680. extension = this.gl.getExtension( name );
  38681. this.extensions[ name ] = extension;
  38682. }
  38683. return extension;
  38684. }
  38685. has( name ) {
  38686. return this.availableExtensions.includes( name );
  38687. }
  38688. }
  38689. class WebGLCapabilities {
  38690. constructor( backend ) {
  38691. this.backend = backend;
  38692. this.maxAnisotropy = null;
  38693. }
  38694. getMaxAnisotropy() {
  38695. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  38696. const gl = this.backend.gl;
  38697. const extensions = this.backend.extensions;
  38698. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38699. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38700. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  38701. } else {
  38702. this.maxAnisotropy = 0;
  38703. }
  38704. return this.maxAnisotropy;
  38705. }
  38706. }
  38707. const GLFeatureName = {
  38708. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  38709. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  38710. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  38711. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  38712. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38713. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38714. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  38715. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  38716. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  38717. };
  38718. class WebGLBufferRenderer {
  38719. constructor( backend ) {
  38720. this.gl = backend.gl;
  38721. this.extensions = backend.extensions;
  38722. this.info = backend.renderer.info;
  38723. this.mode = null;
  38724. this.index = 0;
  38725. this.type = null;
  38726. this.object = null;
  38727. }
  38728. render( start, count ) {
  38729. const { gl, mode, object, type, info, index } = this;
  38730. if ( index !== 0 ) {
  38731. gl.drawElements( mode, count, type, start );
  38732. } else {
  38733. gl.drawArrays( mode, start, count );
  38734. }
  38735. info.update( object, count, mode, 1 );
  38736. }
  38737. renderInstances( start, count, primcount ) {
  38738. const { gl, mode, type, index, object, info } = this;
  38739. if ( primcount === 0 ) return;
  38740. if ( index !== 0 ) {
  38741. gl.drawElementsInstanced( mode, count, type, start, primcount );
  38742. } else {
  38743. gl.drawArraysInstanced( mode, start, count, primcount );
  38744. }
  38745. info.update( object, count, mode, primcount );
  38746. }
  38747. renderMultiDraw( starts, counts, drawCount ) {
  38748. const { extensions, mode, object, info } = this;
  38749. if ( drawCount === 0 ) return;
  38750. const extension = extensions.get( 'WEBGL_multi_draw' );
  38751. if ( extension === null ) {
  38752. for ( let i = 0; i < drawCount; i ++ ) {
  38753. this.render( starts[ i ], counts[ i ] );
  38754. }
  38755. } else {
  38756. if ( this.index !== 0 ) {
  38757. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  38758. } else {
  38759. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  38760. }
  38761. let elementCount = 0;
  38762. for ( let i = 0; i < drawCount; i ++ ) {
  38763. elementCount += counts[ i ];
  38764. }
  38765. info.update( object, elementCount, mode, 1 );
  38766. }
  38767. }
  38768. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  38769. const { extensions, mode, object, info } = this;
  38770. if ( drawCount === 0 ) return;
  38771. const extension = extensions.get( 'WEBGL_multi_draw' );
  38772. if ( extension === null ) {
  38773. for ( let i = 0; i < drawCount; i ++ ) {
  38774. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  38775. }
  38776. } else {
  38777. if ( this.index !== 0 ) {
  38778. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  38779. } else {
  38780. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  38781. }
  38782. let elementCount = 0;
  38783. for ( let i = 0; i < drawCount; i ++ ) {
  38784. elementCount += counts[ i ];
  38785. }
  38786. for ( let i = 0; i < primcount.length; i ++ ) {
  38787. info.update( object, elementCount, mode, primcount[ i ] );
  38788. }
  38789. }
  38790. }
  38791. //
  38792. }
  38793. //
  38794. class WebGLBackend extends Backend {
  38795. constructor( parameters = {} ) {
  38796. super( parameters );
  38797. this.isWebGLBackend = true;
  38798. }
  38799. init( renderer ) {
  38800. super.init( renderer );
  38801. //
  38802. const parameters = this.parameters;
  38803. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  38804. this.gl = glContext;
  38805. this.extensions = new WebGLExtensions( this );
  38806. this.capabilities = new WebGLCapabilities( this );
  38807. this.attributeUtils = new WebGLAttributeUtils( this );
  38808. this.textureUtils = new WebGLTextureUtils( this );
  38809. this.bufferRenderer = new WebGLBufferRenderer( this );
  38810. this.state = new WebGLState( this );
  38811. this.utils = new WebGLUtils( this );
  38812. this.vaoCache = {};
  38813. this.transformFeedbackCache = {};
  38814. this.discard = false;
  38815. this.trackTimestamp = ( parameters.trackTimestamp === true );
  38816. this.extensions.get( 'EXT_color_buffer_float' );
  38817. this.extensions.get( 'WEBGL_multi_draw' );
  38818. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  38819. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  38820. this._currentContext = null;
  38821. }
  38822. get coordinateSystem() {
  38823. return WebGLCoordinateSystem;
  38824. }
  38825. async getArrayBufferAsync( attribute ) {
  38826. return await this.attributeUtils.getArrayBufferAsync( attribute );
  38827. }
  38828. initTimestampQuery( renderContext ) {
  38829. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38830. const renderContextData = this.get( renderContext );
  38831. if ( this.queryRunning ) {
  38832. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  38833. renderContextData.queryQueue.push( renderContext );
  38834. return;
  38835. }
  38836. if ( renderContextData.activeQuery ) {
  38837. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38838. renderContextData.activeQuery = null;
  38839. }
  38840. renderContextData.activeQuery = this.gl.createQuery();
  38841. if ( renderContextData.activeQuery !== null ) {
  38842. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  38843. this.queryRunning = true;
  38844. }
  38845. }
  38846. // timestamp utils
  38847. prepareTimestampBuffer( renderContext ) {
  38848. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38849. const renderContextData = this.get( renderContext );
  38850. if ( renderContextData.activeQuery ) {
  38851. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38852. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38853. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  38854. renderContextData.activeQuery = null;
  38855. this.queryRunning = false;
  38856. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  38857. const nextRenderContext = renderContextData.queryQueue.shift();
  38858. this.initTimestampQuery( nextRenderContext );
  38859. }
  38860. }
  38861. }
  38862. async resolveTimestampAsync( renderContext, type = 'render' ) {
  38863. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38864. const renderContextData = this.get( renderContext );
  38865. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38866. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  38867. const queryInfo = renderContextData.gpuQueries[ i ];
  38868. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  38869. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  38870. if ( available && ! disjoint ) {
  38871. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  38872. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  38873. this.gl.deleteQuery( queryInfo.query );
  38874. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  38875. i --;
  38876. this.renderer.info.updateTimestamp( type, duration );
  38877. }
  38878. }
  38879. }
  38880. getContext() {
  38881. return this.gl;
  38882. }
  38883. beginRender( renderContext ) {
  38884. const { gl } = this;
  38885. const renderContextData = this.get( renderContext );
  38886. //
  38887. //
  38888. this.initTimestampQuery( renderContext );
  38889. renderContextData.previousContext = this._currentContext;
  38890. this._currentContext = renderContext;
  38891. this._setFramebuffer( renderContext );
  38892. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  38893. //
  38894. if ( renderContext.viewport ) {
  38895. this.updateViewport( renderContext );
  38896. } else {
  38897. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38898. }
  38899. if ( renderContext.scissor ) {
  38900. const { x, y, width, height } = renderContext.scissorValue;
  38901. gl.scissor( x, y, width, height );
  38902. }
  38903. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38904. if ( occlusionQueryCount > 0 ) {
  38905. // Get a reference to the array of objects with queries. The renderContextData property
  38906. // can be changed by another render pass before the async reading of all previous queries complete
  38907. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  38908. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  38909. renderContextData.lastOcclusionObject = null;
  38910. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  38911. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  38912. renderContextData.occlusionQueryIndex = 0;
  38913. }
  38914. }
  38915. finishRender( renderContext ) {
  38916. const { gl, state } = this;
  38917. const renderContextData = this.get( renderContext );
  38918. const previousContext = renderContextData.previousContext;
  38919. const textures = renderContext.textures;
  38920. if ( textures !== null ) {
  38921. for ( let i = 0; i < textures.length; i ++ ) {
  38922. const texture = textures[ i ];
  38923. if ( texture.generateMipmaps ) {
  38924. this.generateMipmaps( texture );
  38925. }
  38926. }
  38927. }
  38928. this._currentContext = previousContext;
  38929. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  38930. const renderTargetContextData = this.get( renderContext.renderTarget );
  38931. const { samples } = renderContext.renderTarget;
  38932. const fb = renderTargetContextData.framebuffer;
  38933. const mask = gl.COLOR_BUFFER_BIT;
  38934. if ( samples > 0 ) {
  38935. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  38936. const textures = renderContext.textures;
  38937. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  38938. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38939. for ( let i = 0; i < textures.length; i ++ ) {
  38940. // TODO Add support for MRT
  38941. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  38942. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  38943. }
  38944. }
  38945. }
  38946. if ( previousContext !== null ) {
  38947. this._setFramebuffer( previousContext );
  38948. if ( previousContext.viewport ) {
  38949. this.updateViewport( previousContext );
  38950. } else {
  38951. const gl = this.gl;
  38952. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38953. }
  38954. }
  38955. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38956. if ( occlusionQueryCount > 0 ) {
  38957. const renderContextData = this.get( renderContext );
  38958. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  38959. const { gl } = this;
  38960. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  38961. }
  38962. this.resolveOccludedAsync( renderContext );
  38963. }
  38964. this.prepareTimestampBuffer( renderContext );
  38965. }
  38966. resolveOccludedAsync( renderContext ) {
  38967. const renderContextData = this.get( renderContext );
  38968. // handle occlusion query results
  38969. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  38970. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  38971. const occluded = new WeakSet();
  38972. const { gl } = this;
  38973. renderContextData.currentOcclusionQueryObjects = null;
  38974. renderContextData.currentOcclusionQueries = null;
  38975. const check = () => {
  38976. let completed = 0;
  38977. // check all queries and requeue as appropriate
  38978. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  38979. const query = currentOcclusionQueries[ i ];
  38980. if ( query === null ) continue;
  38981. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  38982. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  38983. currentOcclusionQueries[ i ] = null;
  38984. gl.deleteQuery( query );
  38985. completed ++;
  38986. }
  38987. }
  38988. if ( completed < currentOcclusionQueries.length ) {
  38989. requestAnimationFrame( check );
  38990. } else {
  38991. renderContextData.occluded = occluded;
  38992. }
  38993. };
  38994. check();
  38995. }
  38996. }
  38997. isOccluded( renderContext, object ) {
  38998. const renderContextData = this.get( renderContext );
  38999. return renderContextData.occluded && renderContextData.occluded.has( object );
  39000. }
  39001. updateViewport( renderContext ) {
  39002. const gl = this.gl;
  39003. const { x, y, width, height } = renderContext.viewportValue;
  39004. gl.viewport( x, y, width, height );
  39005. }
  39006. setScissorTest( boolean ) {
  39007. const gl = this.gl;
  39008. if ( boolean ) {
  39009. gl.enable( gl.SCISSOR_TEST );
  39010. } else {
  39011. gl.disable( gl.SCISSOR_TEST );
  39012. }
  39013. }
  39014. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  39015. const { gl } = this;
  39016. if ( descriptor === null ) {
  39017. descriptor = {
  39018. textures: null,
  39019. clearColorValue: this.getClearColor()
  39020. };
  39021. }
  39022. //
  39023. let clear = 0;
  39024. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  39025. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  39026. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  39027. if ( clear !== 0 ) {
  39028. const clearColor = descriptor.clearColorValue || this.getClearColor();
  39029. if ( depth ) this.state.setDepthMask( true );
  39030. if ( descriptor.textures === null ) {
  39031. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  39032. gl.clear( clear );
  39033. } else {
  39034. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  39035. if ( color ) {
  39036. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  39037. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  39038. }
  39039. }
  39040. if ( depth && stencil ) {
  39041. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  39042. } else if ( depth ) {
  39043. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  39044. } else if ( stencil ) {
  39045. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  39046. }
  39047. }
  39048. }
  39049. }
  39050. beginCompute( computeGroup ) {
  39051. const gl = this.gl;
  39052. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39053. this.initTimestampQuery( computeGroup );
  39054. }
  39055. compute( computeGroup, computeNode, bindings, pipeline ) {
  39056. const gl = this.gl;
  39057. if ( ! this.discard ) {
  39058. // required here to handle async behaviour of render.compute()
  39059. gl.enable( gl.RASTERIZER_DISCARD );
  39060. this.discard = true;
  39061. }
  39062. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  39063. const vaoKey = this._getVaoKey( null, attributes );
  39064. const vaoGPU = this.vaoCache[ vaoKey ];
  39065. if ( vaoGPU === undefined ) {
  39066. this._createVao( null, attributes );
  39067. } else {
  39068. gl.bindVertexArray( vaoGPU );
  39069. }
  39070. gl.useProgram( programGPU );
  39071. this._bindUniforms( bindings );
  39072. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  39073. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39074. gl.beginTransformFeedback( gl.POINTS );
  39075. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  39076. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  39077. } else {
  39078. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  39079. }
  39080. gl.endTransformFeedback();
  39081. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39082. // switch active buffers
  39083. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39084. const dualAttributeData = transformBuffers[ i ];
  39085. if ( dualAttributeData.pbo ) {
  39086. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  39087. }
  39088. dualAttributeData.switchBuffers();
  39089. }
  39090. }
  39091. finishCompute( computeGroup ) {
  39092. const gl = this.gl;
  39093. this.discard = false;
  39094. gl.disable( gl.RASTERIZER_DISCARD );
  39095. this.prepareTimestampBuffer( computeGroup );
  39096. }
  39097. draw( renderObject/*, info*/ ) {
  39098. const { object, pipeline, material, context } = renderObject;
  39099. const { programGPU } = this.get( pipeline );
  39100. const { gl, state } = this;
  39101. const contextData = this.get( context );
  39102. //
  39103. this._bindUniforms( renderObject.getBindings() );
  39104. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  39105. state.setMaterial( material, frontFaceCW );
  39106. gl.useProgram( programGPU );
  39107. //
  39108. let vaoGPU = renderObject.staticVao;
  39109. if ( vaoGPU === undefined ) {
  39110. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  39111. vaoGPU = this.vaoCache[ vaoKey ];
  39112. if ( vaoGPU === undefined ) {
  39113. let staticVao;
  39114. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  39115. if ( staticVao ) renderObject.staticVao = vaoGPU;
  39116. }
  39117. }
  39118. gl.bindVertexArray( vaoGPU );
  39119. //
  39120. const index = renderObject.getIndex();
  39121. const geometry = renderObject.geometry;
  39122. const drawRange = renderObject.drawRange;
  39123. const firstVertex = drawRange.start;
  39124. //
  39125. const lastObject = contextData.lastOcclusionObject;
  39126. if ( lastObject !== object && lastObject !== undefined ) {
  39127. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  39128. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39129. contextData.occlusionQueryIndex ++;
  39130. }
  39131. if ( object.occlusionTest === true ) {
  39132. const query = gl.createQuery();
  39133. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  39134. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  39135. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  39136. }
  39137. contextData.lastOcclusionObject = object;
  39138. }
  39139. //
  39140. const renderer = this.bufferRenderer;
  39141. if ( object.isPoints ) renderer.mode = gl.POINTS;
  39142. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  39143. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  39144. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  39145. else {
  39146. if ( material.wireframe === true ) {
  39147. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  39148. renderer.mode = gl.LINES;
  39149. } else {
  39150. renderer.mode = gl.TRIANGLES;
  39151. }
  39152. }
  39153. //
  39154. let count;
  39155. renderer.object = object;
  39156. if ( index !== null ) {
  39157. const indexData = this.get( index );
  39158. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  39159. renderer.index = index.count;
  39160. renderer.type = indexData.type;
  39161. count = indexCount;
  39162. } else {
  39163. renderer.index = 0;
  39164. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  39165. count = vertexCount;
  39166. }
  39167. const instanceCount = this.getInstanceCount( renderObject );
  39168. if ( object.isBatchedMesh ) {
  39169. if ( object._multiDrawInstances !== null ) {
  39170. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  39171. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  39172. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  39173. } else {
  39174. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  39175. }
  39176. } else if ( instanceCount > 1 ) {
  39177. renderer.renderInstances( firstVertex, count, instanceCount );
  39178. } else {
  39179. renderer.render( firstVertex, count );
  39180. }
  39181. //
  39182. gl.bindVertexArray( null );
  39183. }
  39184. needsRenderUpdate( /*renderObject*/ ) {
  39185. return false;
  39186. }
  39187. getRenderCacheKey( renderObject ) {
  39188. return renderObject.id;
  39189. }
  39190. // textures
  39191. createDefaultTexture( texture ) {
  39192. this.textureUtils.createDefaultTexture( texture );
  39193. }
  39194. createTexture( texture, options ) {
  39195. this.textureUtils.createTexture( texture, options );
  39196. }
  39197. updateTexture( texture, options ) {
  39198. this.textureUtils.updateTexture( texture, options );
  39199. }
  39200. generateMipmaps( texture ) {
  39201. this.textureUtils.generateMipmaps( texture );
  39202. }
  39203. destroyTexture( texture ) {
  39204. this.textureUtils.destroyTexture( texture );
  39205. }
  39206. copyTextureToBuffer( texture, x, y, width, height ) {
  39207. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  39208. }
  39209. createSampler( /*texture*/ ) {
  39210. //console.warn( 'Abstract class.' );
  39211. }
  39212. destroySampler() {}
  39213. // node builder
  39214. createNodeBuilder( object, renderer ) {
  39215. return new GLSLNodeBuilder( object, renderer );
  39216. }
  39217. // program
  39218. createProgram( program ) {
  39219. const gl = this.gl;
  39220. const { stage, code } = program;
  39221. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  39222. gl.shaderSource( shader, code );
  39223. gl.compileShader( shader );
  39224. this.set( program, {
  39225. shaderGPU: shader
  39226. } );
  39227. }
  39228. destroyProgram( /*program*/ ) {
  39229. console.warn( 'Abstract class.' );
  39230. }
  39231. createRenderPipeline( renderObject, promises ) {
  39232. const gl = this.gl;
  39233. const pipeline = renderObject.pipeline;
  39234. // Program
  39235. const { fragmentProgram, vertexProgram } = pipeline;
  39236. const programGPU = gl.createProgram();
  39237. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39238. const vertexShader = this.get( vertexProgram ).shaderGPU;
  39239. gl.attachShader( programGPU, fragmentShader );
  39240. gl.attachShader( programGPU, vertexShader );
  39241. gl.linkProgram( programGPU );
  39242. this.set( pipeline, {
  39243. programGPU,
  39244. fragmentShader,
  39245. vertexShader
  39246. } );
  39247. if ( promises !== null && this.parallel ) {
  39248. const p = new Promise( ( resolve /*, reject*/ ) => {
  39249. const parallel = this.parallel;
  39250. const checkStatus = () => {
  39251. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  39252. this._completeCompile( renderObject, pipeline );
  39253. resolve();
  39254. } else {
  39255. requestAnimationFrame( checkStatus );
  39256. }
  39257. };
  39258. checkStatus();
  39259. } );
  39260. promises.push( p );
  39261. return;
  39262. }
  39263. this._completeCompile( renderObject, pipeline );
  39264. }
  39265. _handleSource( string, errorLine ) {
  39266. const lines = string.split( '\n' );
  39267. const lines2 = [];
  39268. const from = Math.max( errorLine - 6, 0 );
  39269. const to = Math.min( errorLine + 6, lines.length );
  39270. for ( let i = from; i < to; i ++ ) {
  39271. const line = i + 1;
  39272. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  39273. }
  39274. return lines2.join( '\n' );
  39275. }
  39276. _getShaderErrors( gl, shader, type ) {
  39277. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  39278. const errors = gl.getShaderInfoLog( shader ).trim();
  39279. if ( status && errors === '' ) return '';
  39280. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  39281. if ( errorMatches ) {
  39282. const errorLine = parseInt( errorMatches[ 1 ] );
  39283. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  39284. } else {
  39285. return errors;
  39286. }
  39287. }
  39288. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  39289. if ( this.renderer.debug.checkShaderErrors ) {
  39290. const gl = this.gl;
  39291. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  39292. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39293. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  39294. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  39295. } else {
  39296. // default error reporting
  39297. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  39298. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  39299. console.error(
  39300. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  39301. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  39302. 'Program Info Log: ' + programLog + '\n' +
  39303. vertexErrors + '\n' +
  39304. fragmentErrors
  39305. );
  39306. }
  39307. } else if ( programLog !== '' ) {
  39308. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  39309. }
  39310. }
  39311. }
  39312. _completeCompile( renderObject, pipeline ) {
  39313. const gl = this.gl;
  39314. const pipelineData = this.get( pipeline );
  39315. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  39316. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39317. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39318. }
  39319. gl.useProgram( programGPU );
  39320. // Bindings
  39321. const bindings = renderObject.getBindings();
  39322. this._setupBindings( bindings, programGPU );
  39323. //
  39324. this.set( pipeline, {
  39325. programGPU
  39326. } );
  39327. }
  39328. createComputePipeline( computePipeline, bindings ) {
  39329. const gl = this.gl;
  39330. // Program
  39331. const fragmentProgram = {
  39332. stage: 'fragment',
  39333. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  39334. };
  39335. this.createProgram( fragmentProgram );
  39336. const { computeProgram } = computePipeline;
  39337. const programGPU = gl.createProgram();
  39338. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39339. const vertexShader = this.get( computeProgram ).shaderGPU;
  39340. const transforms = computeProgram.transforms;
  39341. const transformVaryingNames = [];
  39342. const transformAttributeNodes = [];
  39343. for ( let i = 0; i < transforms.length; i ++ ) {
  39344. const transform = transforms[ i ];
  39345. transformVaryingNames.push( transform.varyingName );
  39346. transformAttributeNodes.push( transform.attributeNode );
  39347. }
  39348. gl.attachShader( programGPU, fragmentShader );
  39349. gl.attachShader( programGPU, vertexShader );
  39350. gl.transformFeedbackVaryings(
  39351. programGPU,
  39352. transformVaryingNames,
  39353. gl.SEPARATE_ATTRIBS
  39354. );
  39355. gl.linkProgram( programGPU );
  39356. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39357. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39358. }
  39359. gl.useProgram( programGPU );
  39360. // Bindings
  39361. this.createBindings( null, bindings );
  39362. this._setupBindings( bindings, programGPU );
  39363. const attributeNodes = computeProgram.attributes;
  39364. const attributes = [];
  39365. const transformBuffers = [];
  39366. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  39367. const attribute = attributeNodes[ i ].node.attribute;
  39368. attributes.push( attribute );
  39369. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39370. }
  39371. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  39372. const attribute = transformAttributeNodes[ i ].attribute;
  39373. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39374. const attributeData = this.get( attribute );
  39375. transformBuffers.push( attributeData );
  39376. }
  39377. //
  39378. this.set( computePipeline, {
  39379. programGPU,
  39380. transformBuffers,
  39381. attributes
  39382. } );
  39383. }
  39384. createBindings( bindGroup, bindings ) {
  39385. this.updateBindings( bindGroup, bindings );
  39386. }
  39387. updateBindings( bindGroup, bindings ) {
  39388. const { gl } = this;
  39389. let groupIndex = 0;
  39390. let textureIndex = 0;
  39391. for ( const bindGroup of bindings ) {
  39392. for ( const binding of bindGroup.bindings ) {
  39393. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39394. const bufferGPU = gl.createBuffer();
  39395. const data = binding.buffer;
  39396. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39397. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39398. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  39399. this.set( binding, {
  39400. index: groupIndex ++,
  39401. bufferGPU
  39402. } );
  39403. } else if ( binding.isSampledTexture ) {
  39404. const { textureGPU, glTextureType } = this.get( binding.texture );
  39405. this.set( binding, {
  39406. index: textureIndex ++,
  39407. textureGPU,
  39408. glTextureType
  39409. } );
  39410. }
  39411. }
  39412. }
  39413. }
  39414. updateBinding( binding ) {
  39415. const gl = this.gl;
  39416. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39417. const bindingData = this.get( binding );
  39418. const bufferGPU = bindingData.bufferGPU;
  39419. const data = binding.buffer;
  39420. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39421. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39422. }
  39423. }
  39424. // attributes
  39425. createIndexAttribute( attribute ) {
  39426. const gl = this.gl;
  39427. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  39428. }
  39429. createAttribute( attribute ) {
  39430. if ( this.has( attribute ) ) return;
  39431. const gl = this.gl;
  39432. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39433. }
  39434. createStorageAttribute( attribute ) {
  39435. if ( this.has( attribute ) ) return;
  39436. const gl = this.gl;
  39437. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39438. }
  39439. updateAttribute( attribute ) {
  39440. this.attributeUtils.updateAttribute( attribute );
  39441. }
  39442. destroyAttribute( attribute ) {
  39443. this.attributeUtils.destroyAttribute( attribute );
  39444. }
  39445. updateSize() {
  39446. //console.warn( 'Abstract class.' );
  39447. }
  39448. hasFeature( name ) {
  39449. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  39450. const extensions = this.extensions;
  39451. for ( let i = 0; i < keysMatching.length; i ++ ) {
  39452. if ( extensions.has( keysMatching[ i ] ) ) return true;
  39453. }
  39454. return false;
  39455. }
  39456. getMaxAnisotropy() {
  39457. return this.capabilities.getMaxAnisotropy();
  39458. }
  39459. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  39460. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  39461. }
  39462. copyFramebufferToTexture( texture, renderContext ) {
  39463. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  39464. }
  39465. _setFramebuffer( renderContext ) {
  39466. const { gl, state } = this;
  39467. let currentFrameBuffer = null;
  39468. if ( renderContext.textures !== null ) {
  39469. const renderTarget = renderContext.renderTarget;
  39470. const renderTargetContextData = this.get( renderTarget );
  39471. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  39472. const cubeFace = this.renderer._activeCubeFace;
  39473. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  39474. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  39475. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  39476. let fb;
  39477. if ( isCube ) {
  39478. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  39479. renderTargetContextData.cubeFramebuffers = [];
  39480. }
  39481. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  39482. } else {
  39483. fb = renderTargetContextData.framebuffer;
  39484. }
  39485. if ( fb === undefined ) {
  39486. fb = gl.createFramebuffer();
  39487. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  39488. const textures = renderContext.textures;
  39489. if ( isCube ) {
  39490. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  39491. const { textureGPU } = this.get( textures[ 0 ] );
  39492. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  39493. } else {
  39494. for ( let i = 0; i < textures.length; i ++ ) {
  39495. const texture = textures[ i ];
  39496. const textureData = this.get( texture );
  39497. textureData.renderTarget = renderContext.renderTarget;
  39498. const attachment = gl.COLOR_ATTACHMENT0 + i;
  39499. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39500. }
  39501. renderTargetContextData.framebuffer = fb;
  39502. state.drawBuffers( renderContext, fb );
  39503. }
  39504. if ( renderContext.depthTexture !== null ) {
  39505. const textureData = this.get( renderContext.depthTexture );
  39506. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39507. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39508. }
  39509. }
  39510. if ( samples > 0 ) {
  39511. if ( msaaFb === undefined ) {
  39512. const invalidationArray = [];
  39513. msaaFb = gl.createFramebuffer();
  39514. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  39515. const msaaRenderbuffers = [];
  39516. const textures = renderContext.textures;
  39517. for ( let i = 0; i < textures.length; i ++ ) {
  39518. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  39519. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39520. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  39521. if ( depthBuffer ) {
  39522. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39523. invalidationArray.push( depthStyle );
  39524. }
  39525. const texture = renderContext.textures[ i ];
  39526. const textureData = this.get( texture );
  39527. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  39528. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39529. }
  39530. renderTargetContextData.msaaFrameBuffer = msaaFb;
  39531. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  39532. if ( depthRenderbuffer === undefined ) {
  39533. depthRenderbuffer = gl.createRenderbuffer();
  39534. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  39535. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  39536. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39537. invalidationArray.push( depthStyle );
  39538. }
  39539. renderTargetContextData.invalidationArray = invalidationArray;
  39540. }
  39541. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39542. } else {
  39543. currentFrameBuffer = fb;
  39544. }
  39545. }
  39546. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  39547. }
  39548. _getVaoKey( index, attributes ) {
  39549. let key = [];
  39550. if ( index !== null ) {
  39551. const indexData = this.get( index );
  39552. key += ':' + indexData.id;
  39553. }
  39554. for ( let i = 0; i < attributes.length; i ++ ) {
  39555. const attributeData = this.get( attributes[ i ] );
  39556. key += ':' + attributeData.id;
  39557. }
  39558. return key;
  39559. }
  39560. _createVao( index, attributes ) {
  39561. const { gl } = this;
  39562. const vaoGPU = gl.createVertexArray();
  39563. let key = '';
  39564. let staticVao = true;
  39565. gl.bindVertexArray( vaoGPU );
  39566. if ( index !== null ) {
  39567. const indexData = this.get( index );
  39568. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  39569. key += ':' + indexData.id;
  39570. }
  39571. for ( let i = 0; i < attributes.length; i ++ ) {
  39572. const attribute = attributes[ i ];
  39573. const attributeData = this.get( attribute );
  39574. key += ':' + attributeData.id;
  39575. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  39576. gl.enableVertexAttribArray( i );
  39577. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  39578. let stride, offset;
  39579. if ( attribute.isInterleavedBufferAttribute === true ) {
  39580. stride = attribute.data.stride * attributeData.bytesPerElement;
  39581. offset = attribute.offset * attributeData.bytesPerElement;
  39582. } else {
  39583. stride = 0;
  39584. offset = 0;
  39585. }
  39586. if ( attributeData.isInteger ) {
  39587. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  39588. } else {
  39589. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  39590. }
  39591. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  39592. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  39593. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  39594. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  39595. }
  39596. }
  39597. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  39598. this.vaoCache[ key ] = vaoGPU;
  39599. return { vaoGPU, staticVao };
  39600. }
  39601. _getTransformFeedback( transformBuffers ) {
  39602. let key = '';
  39603. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39604. key += ':' + transformBuffers[ i ].id;
  39605. }
  39606. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  39607. if ( transformFeedbackGPU !== undefined ) {
  39608. return transformFeedbackGPU;
  39609. }
  39610. const gl = this.gl;
  39611. transformFeedbackGPU = gl.createTransformFeedback();
  39612. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39613. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39614. const attributeData = transformBuffers[ i ];
  39615. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  39616. }
  39617. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39618. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  39619. return transformFeedbackGPU;
  39620. }
  39621. _setupBindings( bindings, programGPU ) {
  39622. const gl = this.gl;
  39623. for ( const bindGroup of bindings ) {
  39624. for ( const binding of bindGroup.bindings ) {
  39625. const bindingData = this.get( binding );
  39626. const index = bindingData.index;
  39627. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39628. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  39629. gl.uniformBlockBinding( programGPU, location, index );
  39630. } else if ( binding.isSampledTexture ) {
  39631. const location = gl.getUniformLocation( programGPU, binding.name );
  39632. gl.uniform1i( location, index );
  39633. }
  39634. }
  39635. }
  39636. }
  39637. _bindUniforms( bindings ) {
  39638. const { gl, state } = this;
  39639. for ( const bindGroup of bindings ) {
  39640. for ( const binding of bindGroup.bindings ) {
  39641. const bindingData = this.get( binding );
  39642. const index = bindingData.index;
  39643. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39644. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  39645. } else if ( binding.isSampledTexture ) {
  39646. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  39647. }
  39648. }
  39649. }
  39650. }
  39651. }
  39652. class Sampler extends Binding {
  39653. constructor( name, texture ) {
  39654. super( name );
  39655. this.texture = texture;
  39656. this.version = texture ? texture.version : 0;
  39657. this.isSampler = true;
  39658. }
  39659. }
  39660. class NodeSampler extends Sampler {
  39661. constructor( name, textureNode, groupNode ) {
  39662. super( name, textureNode ? textureNode.value : null );
  39663. this.textureNode = textureNode;
  39664. this.groupNode = groupNode;
  39665. }
  39666. update() {
  39667. this.texture = this.textureNode.value;
  39668. }
  39669. }
  39670. class StorageBuffer extends Buffer {
  39671. constructor( name, attribute ) {
  39672. super( name, attribute ? attribute.array : null );
  39673. this.attribute = attribute;
  39674. this.isStorageBuffer = true;
  39675. }
  39676. }
  39677. let _id = 0;
  39678. class NodeStorageBuffer extends StorageBuffer {
  39679. constructor( nodeUniform, groupNode ) {
  39680. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  39681. this.nodeUniform = nodeUniform;
  39682. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  39683. this.groupNode = groupNode;
  39684. }
  39685. get buffer() {
  39686. return this.nodeUniform.value;
  39687. }
  39688. }
  39689. class WebGPUTexturePassUtils {
  39690. constructor( device ) {
  39691. this.device = device;
  39692. const mipmapVertexSource = `
  39693. struct VarysStruct {
  39694. @builtin( position ) Position: vec4<f32>,
  39695. @location( 0 ) vTex : vec2<f32>
  39696. };
  39697. @vertex
  39698. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  39699. var Varys : VarysStruct;
  39700. var pos = array< vec2<f32>, 4 >(
  39701. vec2<f32>( -1.0, 1.0 ),
  39702. vec2<f32>( 1.0, 1.0 ),
  39703. vec2<f32>( -1.0, -1.0 ),
  39704. vec2<f32>( 1.0, -1.0 )
  39705. );
  39706. var tex = array< vec2<f32>, 4 >(
  39707. vec2<f32>( 0.0, 0.0 ),
  39708. vec2<f32>( 1.0, 0.0 ),
  39709. vec2<f32>( 0.0, 1.0 ),
  39710. vec2<f32>( 1.0, 1.0 )
  39711. );
  39712. Varys.vTex = tex[ vertexIndex ];
  39713. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  39714. return Varys;
  39715. }
  39716. `;
  39717. const mipmapFragmentSource = `
  39718. @group( 0 ) @binding( 0 )
  39719. var imgSampler : sampler;
  39720. @group( 0 ) @binding( 1 )
  39721. var img : texture_2d<f32>;
  39722. @fragment
  39723. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39724. return textureSample( img, imgSampler, vTex );
  39725. }
  39726. `;
  39727. const flipYFragmentSource = `
  39728. @group( 0 ) @binding( 0 )
  39729. var imgSampler : sampler;
  39730. @group( 0 ) @binding( 1 )
  39731. var img : texture_2d<f32>;
  39732. @fragment
  39733. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39734. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  39735. }
  39736. `;
  39737. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  39738. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  39739. // We'll need a new pipeline for every texture format used.
  39740. this.transferPipelines = {};
  39741. this.flipYPipelines = {};
  39742. this.mipmapVertexShaderModule = device.createShaderModule( {
  39743. label: 'mipmapVertex',
  39744. code: mipmapVertexSource
  39745. } );
  39746. this.mipmapFragmentShaderModule = device.createShaderModule( {
  39747. label: 'mipmapFragment',
  39748. code: mipmapFragmentSource
  39749. } );
  39750. this.flipYFragmentShaderModule = device.createShaderModule( {
  39751. label: 'flipYFragment',
  39752. code: flipYFragmentSource
  39753. } );
  39754. }
  39755. getTransferPipeline( format ) {
  39756. let pipeline = this.transferPipelines[ format ];
  39757. if ( pipeline === undefined ) {
  39758. pipeline = this.device.createRenderPipeline( {
  39759. vertex: {
  39760. module: this.mipmapVertexShaderModule,
  39761. entryPoint: 'main'
  39762. },
  39763. fragment: {
  39764. module: this.mipmapFragmentShaderModule,
  39765. entryPoint: 'main',
  39766. targets: [ { format } ]
  39767. },
  39768. primitive: {
  39769. topology: GPUPrimitiveTopology.TriangleStrip,
  39770. stripIndexFormat: GPUIndexFormat.Uint32
  39771. },
  39772. layout: 'auto'
  39773. } );
  39774. this.transferPipelines[ format ] = pipeline;
  39775. }
  39776. return pipeline;
  39777. }
  39778. getFlipYPipeline( format ) {
  39779. let pipeline = this.flipYPipelines[ format ];
  39780. if ( pipeline === undefined ) {
  39781. pipeline = this.device.createRenderPipeline( {
  39782. vertex: {
  39783. module: this.mipmapVertexShaderModule,
  39784. entryPoint: 'main'
  39785. },
  39786. fragment: {
  39787. module: this.flipYFragmentShaderModule,
  39788. entryPoint: 'main',
  39789. targets: [ { format } ]
  39790. },
  39791. primitive: {
  39792. topology: GPUPrimitiveTopology.TriangleStrip,
  39793. stripIndexFormat: GPUIndexFormat.Uint32
  39794. },
  39795. layout: 'auto'
  39796. } );
  39797. this.flipYPipelines[ format ] = pipeline;
  39798. }
  39799. return pipeline;
  39800. }
  39801. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39802. const format = textureGPUDescriptor.format;
  39803. const { width, height } = textureGPUDescriptor.size;
  39804. const transferPipeline = this.getTransferPipeline( format );
  39805. const flipYPipeline = this.getFlipYPipeline( format );
  39806. const tempTexture = this.device.createTexture( {
  39807. size: { width, height, depthOrArrayLayers: 1 },
  39808. format,
  39809. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  39810. } );
  39811. const srcView = textureGPU.createView( {
  39812. baseMipLevel: 0,
  39813. mipLevelCount: 1,
  39814. dimension: GPUTextureViewDimension.TwoD,
  39815. baseArrayLayer
  39816. } );
  39817. const dstView = tempTexture.createView( {
  39818. baseMipLevel: 0,
  39819. mipLevelCount: 1,
  39820. dimension: GPUTextureViewDimension.TwoD,
  39821. baseArrayLayer: 0
  39822. } );
  39823. const commandEncoder = this.device.createCommandEncoder( {} );
  39824. const pass = ( pipeline, sourceView, destinationView ) => {
  39825. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39826. const bindGroup = this.device.createBindGroup( {
  39827. layout: bindGroupLayout,
  39828. entries: [ {
  39829. binding: 0,
  39830. resource: this.flipYSampler
  39831. }, {
  39832. binding: 1,
  39833. resource: sourceView
  39834. } ]
  39835. } );
  39836. const passEncoder = commandEncoder.beginRenderPass( {
  39837. colorAttachments: [ {
  39838. view: destinationView,
  39839. loadOp: GPULoadOp.Clear,
  39840. storeOp: GPUStoreOp.Store,
  39841. clearValue: [ 0, 0, 0, 0 ]
  39842. } ]
  39843. } );
  39844. passEncoder.setPipeline( pipeline );
  39845. passEncoder.setBindGroup( 0, bindGroup );
  39846. passEncoder.draw( 4, 1, 0, 0 );
  39847. passEncoder.end();
  39848. };
  39849. pass( transferPipeline, srcView, dstView );
  39850. pass( flipYPipeline, dstView, srcView );
  39851. this.device.queue.submit( [ commandEncoder.finish() ] );
  39852. tempTexture.destroy();
  39853. }
  39854. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39855. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  39856. const commandEncoder = this.device.createCommandEncoder( {} );
  39857. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39858. let srcView = textureGPU.createView( {
  39859. baseMipLevel: 0,
  39860. mipLevelCount: 1,
  39861. dimension: GPUTextureViewDimension.TwoD,
  39862. baseArrayLayer
  39863. } );
  39864. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  39865. const bindGroup = this.device.createBindGroup( {
  39866. layout: bindGroupLayout,
  39867. entries: [ {
  39868. binding: 0,
  39869. resource: this.mipmapSampler
  39870. }, {
  39871. binding: 1,
  39872. resource: srcView
  39873. } ]
  39874. } );
  39875. const dstView = textureGPU.createView( {
  39876. baseMipLevel: i,
  39877. mipLevelCount: 1,
  39878. dimension: GPUTextureViewDimension.TwoD,
  39879. baseArrayLayer
  39880. } );
  39881. const passEncoder = commandEncoder.beginRenderPass( {
  39882. colorAttachments: [ {
  39883. view: dstView,
  39884. loadOp: GPULoadOp.Clear,
  39885. storeOp: GPUStoreOp.Store,
  39886. clearValue: [ 0, 0, 0, 0 ]
  39887. } ]
  39888. } );
  39889. passEncoder.setPipeline( pipeline );
  39890. passEncoder.setBindGroup( 0, bindGroup );
  39891. passEncoder.draw( 4, 1, 0, 0 );
  39892. passEncoder.end();
  39893. srcView = dstView;
  39894. }
  39895. this.device.queue.submit( [ commandEncoder.finish() ] );
  39896. }
  39897. }
  39898. const _compareToWebGPU = {
  39899. [ NeverCompare ]: 'never',
  39900. [ LessCompare ]: 'less',
  39901. [ EqualCompare ]: 'equal',
  39902. [ LessEqualCompare ]: 'less-equal',
  39903. [ GreaterCompare ]: 'greater',
  39904. [ GreaterEqualCompare ]: 'greater-equal',
  39905. [ AlwaysCompare ]: 'always',
  39906. [ NotEqualCompare ]: 'not-equal'
  39907. };
  39908. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  39909. class WebGPUTextureUtils {
  39910. constructor( backend ) {
  39911. this.backend = backend;
  39912. this._passUtils = null;
  39913. this.defaultTexture = {};
  39914. this.defaultCubeTexture = {};
  39915. this.colorBuffer = null;
  39916. this.depthTexture = new DepthTexture();
  39917. this.depthTexture.name = 'depthBuffer';
  39918. }
  39919. createSampler( texture ) {
  39920. const backend = this.backend;
  39921. const device = backend.device;
  39922. const textureGPU = backend.get( texture );
  39923. const samplerDescriptorGPU = {
  39924. addressModeU: this._convertAddressMode( texture.wrapS ),
  39925. addressModeV: this._convertAddressMode( texture.wrapT ),
  39926. addressModeW: this._convertAddressMode( texture.wrapR ),
  39927. magFilter: this._convertFilterMode( texture.magFilter ),
  39928. minFilter: this._convertFilterMode( texture.minFilter ),
  39929. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  39930. maxAnisotropy: texture.anisotropy
  39931. };
  39932. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  39933. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  39934. }
  39935. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  39936. }
  39937. createDefaultTexture( texture ) {
  39938. let textureGPU;
  39939. const format = getFormat( texture );
  39940. if ( texture.isCubeTexture ) {
  39941. textureGPU = this._getDefaultCubeTextureGPU( format );
  39942. } else {
  39943. textureGPU = this._getDefaultTextureGPU( format );
  39944. }
  39945. this.backend.get( texture ).texture = textureGPU;
  39946. }
  39947. createTexture( texture, options = {} ) {
  39948. const backend = this.backend;
  39949. const textureData = backend.get( texture );
  39950. if ( textureData.initialized ) {
  39951. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  39952. }
  39953. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  39954. if ( options.levels === undefined ) options.levels = 1;
  39955. if ( options.depth === undefined ) options.depth = 1;
  39956. const { width, height, depth, levels } = options;
  39957. const dimension = this._getDimension( texture );
  39958. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  39959. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  39960. if ( sampleCount > 1 ) {
  39961. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  39962. sampleCount = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  39963. if ( sampleCount === 2 ) {
  39964. sampleCount = 4;
  39965. }
  39966. }
  39967. const primarySampleCount = texture.isRenderTargetTexture ? 1 : sampleCount;
  39968. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  39969. if ( texture.isStorageTexture === true ) {
  39970. usage |= GPUTextureUsage.STORAGE_BINDING;
  39971. }
  39972. if ( texture.isCompressedTexture !== true ) {
  39973. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  39974. }
  39975. const textureDescriptorGPU = {
  39976. label: texture.name,
  39977. size: {
  39978. width: width,
  39979. height: height,
  39980. depthOrArrayLayers: depth,
  39981. },
  39982. mipLevelCount: levels,
  39983. sampleCount: primarySampleCount,
  39984. dimension: dimension,
  39985. format: format,
  39986. usage: usage
  39987. };
  39988. // texture creation
  39989. if ( texture.isVideoTexture ) {
  39990. const video = texture.source.data;
  39991. const videoFrame = new VideoFrame( video );
  39992. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  39993. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  39994. videoFrame.close();
  39995. textureData.externalTexture = video;
  39996. } else {
  39997. if ( format === undefined ) {
  39998. console.warn( 'WebGPURenderer: Texture format not supported.' );
  39999. return this.createDefaultTexture( texture );
  40000. }
  40001. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  40002. }
  40003. if ( texture.isRenderTargetTexture && sampleCount > 1 ) {
  40004. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  40005. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  40006. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  40007. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  40008. }
  40009. textureData.initialized = true;
  40010. textureData.textureDescriptorGPU = textureDescriptorGPU;
  40011. }
  40012. destroyTexture( texture ) {
  40013. const backend = this.backend;
  40014. const textureData = backend.get( texture );
  40015. textureData.texture.destroy();
  40016. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  40017. backend.delete( texture );
  40018. }
  40019. destroySampler( texture ) {
  40020. const backend = this.backend;
  40021. const textureData = backend.get( texture );
  40022. delete textureData.sampler;
  40023. }
  40024. generateMipmaps( texture ) {
  40025. const textureData = this.backend.get( texture );
  40026. if ( texture.isCubeTexture ) {
  40027. for ( let i = 0; i < 6; i ++ ) {
  40028. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  40029. }
  40030. } else {
  40031. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU );
  40032. }
  40033. }
  40034. getColorBuffer() {
  40035. if ( this.colorBuffer ) this.colorBuffer.destroy();
  40036. const backend = this.backend;
  40037. const { width, height } = backend.getDrawingBufferSize();
  40038. this.colorBuffer = backend.device.createTexture( {
  40039. label: 'colorBuffer',
  40040. size: {
  40041. width: width,
  40042. height: height,
  40043. depthOrArrayLayers: 1
  40044. },
  40045. sampleCount: backend.parameters.sampleCount,
  40046. format: GPUTextureFormat.BGRA8Unorm,
  40047. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  40048. } );
  40049. return this.colorBuffer;
  40050. }
  40051. getDepthBuffer( depth = true, stencil = false ) {
  40052. const backend = this.backend;
  40053. const { width, height } = backend.getDrawingBufferSize();
  40054. const depthTexture = this.depthTexture;
  40055. const depthTextureGPU = backend.get( depthTexture ).texture;
  40056. let format, type;
  40057. if ( stencil ) {
  40058. format = DepthStencilFormat;
  40059. type = UnsignedInt248Type;
  40060. } else if ( depth ) {
  40061. format = DepthFormat;
  40062. type = UnsignedIntType;
  40063. }
  40064. if ( depthTextureGPU !== undefined ) {
  40065. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  40066. return depthTextureGPU;
  40067. }
  40068. this.destroyTexture( depthTexture );
  40069. }
  40070. depthTexture.name = 'depthBuffer';
  40071. depthTexture.format = format;
  40072. depthTexture.type = type;
  40073. depthTexture.image.width = width;
  40074. depthTexture.image.height = height;
  40075. this.createTexture( depthTexture, { sampleCount: backend.parameters.sampleCount, width, height } );
  40076. return backend.get( depthTexture ).texture;
  40077. }
  40078. updateTexture( texture, options ) {
  40079. const textureData = this.backend.get( texture );
  40080. const { textureDescriptorGPU } = textureData;
  40081. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  40082. return;
  40083. // transfer texture data
  40084. if ( texture.isDataTexture ) {
  40085. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40086. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  40087. for ( let i = 0; i < options.image.depth; i ++ ) {
  40088. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  40089. }
  40090. } else if ( texture.isCompressedTexture ) {
  40091. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  40092. } else if ( texture.isCubeTexture ) {
  40093. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  40094. } else if ( texture.isVideoTexture ) {
  40095. const video = texture.source.data;
  40096. textureData.externalTexture = video;
  40097. } else {
  40098. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40099. }
  40100. //
  40101. textureData.version = texture.version;
  40102. if ( texture.onUpdate ) texture.onUpdate( texture );
  40103. }
  40104. async copyTextureToBuffer( texture, x, y, width, height ) {
  40105. const device = this.backend.device;
  40106. const textureData = this.backend.get( texture );
  40107. const textureGPU = textureData.texture;
  40108. const format = textureData.textureDescriptorGPU.format;
  40109. const bytesPerTexel = this._getBytesPerTexel( format );
  40110. let bytesPerRow = width * bytesPerTexel;
  40111. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  40112. const readBuffer = device.createBuffer(
  40113. {
  40114. size: width * height * bytesPerTexel,
  40115. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  40116. }
  40117. );
  40118. const encoder = device.createCommandEncoder();
  40119. encoder.copyTextureToBuffer(
  40120. {
  40121. texture: textureGPU,
  40122. origin: { x, y },
  40123. },
  40124. {
  40125. buffer: readBuffer,
  40126. bytesPerRow: bytesPerRow
  40127. },
  40128. {
  40129. width: width,
  40130. height: height
  40131. }
  40132. );
  40133. const typedArrayType = this._getTypedArrayType( format );
  40134. device.queue.submit( [ encoder.finish() ] );
  40135. await readBuffer.mapAsync( GPUMapMode.READ );
  40136. const buffer = readBuffer.getMappedRange();
  40137. return new typedArrayType( buffer );
  40138. }
  40139. _isEnvironmentTexture( texture ) {
  40140. const mapping = texture.mapping;
  40141. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  40142. }
  40143. _getDefaultTextureGPU( format ) {
  40144. let defaultTexture = this.defaultTexture[ format ];
  40145. if ( defaultTexture === undefined ) {
  40146. const texture = new Texture();
  40147. texture.minFilter = NearestFilter;
  40148. texture.magFilter = NearestFilter;
  40149. this.createTexture( texture, { width: 1, height: 1, format } );
  40150. this.defaultTexture[ format ] = defaultTexture = texture;
  40151. }
  40152. return this.backend.get( defaultTexture ).texture;
  40153. }
  40154. _getDefaultCubeTextureGPU( format ) {
  40155. let defaultCubeTexture = this.defaultTexture[ format ];
  40156. if ( defaultCubeTexture === undefined ) {
  40157. const texture = new CubeTexture();
  40158. texture.minFilter = NearestFilter;
  40159. texture.magFilter = NearestFilter;
  40160. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  40161. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  40162. }
  40163. return this.backend.get( defaultCubeTexture ).texture;
  40164. }
  40165. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  40166. for ( let i = 0; i < 6; i ++ ) {
  40167. const image = images[ i ];
  40168. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  40169. if ( image.isDataTexture ) {
  40170. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40171. } else {
  40172. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40173. }
  40174. }
  40175. }
  40176. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  40177. const device = this.backend.device;
  40178. device.queue.copyExternalImageToTexture(
  40179. {
  40180. source: image
  40181. }, {
  40182. texture: textureGPU,
  40183. mipLevel: 0,
  40184. origin: { x: 0, y: 0, z: originDepth }
  40185. }, {
  40186. width: image.width,
  40187. height: image.height,
  40188. depthOrArrayLayers: 1
  40189. }
  40190. );
  40191. if ( flipY === true ) {
  40192. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40193. }
  40194. }
  40195. _getPassUtils() {
  40196. let passUtils = this._passUtils;
  40197. if ( passUtils === null ) {
  40198. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  40199. }
  40200. return passUtils;
  40201. }
  40202. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  40203. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  40204. }
  40205. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  40206. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  40207. }
  40208. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  40209. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40210. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  40211. const device = this.backend.device;
  40212. const data = image.data;
  40213. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  40214. const bytesPerRow = image.width * bytesPerTexel;
  40215. device.queue.writeTexture(
  40216. {
  40217. texture: textureGPU,
  40218. mipLevel: 0,
  40219. origin: { x: 0, y: 0, z: originDepth }
  40220. },
  40221. data,
  40222. {
  40223. offset: image.width * image.height * bytesPerTexel * depth,
  40224. bytesPerRow
  40225. },
  40226. {
  40227. width: image.width,
  40228. height: image.height,
  40229. depthOrArrayLayers: 1
  40230. } );
  40231. if ( flipY === true ) {
  40232. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40233. }
  40234. }
  40235. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  40236. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40237. const device = this.backend.device;
  40238. const blockData = this._getBlockData( textureDescriptorGPU.format );
  40239. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40240. const mipmap = mipmaps[ i ];
  40241. const width = mipmap.width;
  40242. const height = mipmap.height;
  40243. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  40244. device.queue.writeTexture(
  40245. {
  40246. texture: textureGPU,
  40247. mipLevel: i
  40248. },
  40249. mipmap.data,
  40250. {
  40251. offset: 0,
  40252. bytesPerRow
  40253. },
  40254. {
  40255. width: Math.ceil( width / blockData.width ) * blockData.width,
  40256. height: Math.ceil( height / blockData.width ) * blockData.width,
  40257. depthOrArrayLayers: 1
  40258. }
  40259. );
  40260. }
  40261. }
  40262. _getBlockData( format ) {
  40263. // this method is only relevant for compressed texture formats
  40264. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  40265. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  40266. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  40267. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  40268. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  40269. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  40270. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  40271. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40272. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40273. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40274. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  40275. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  40276. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  40277. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  40278. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40279. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  40280. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  40281. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  40282. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  40283. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  40284. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  40285. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  40286. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  40287. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  40288. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  40289. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  40290. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  40291. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  40292. }
  40293. _convertAddressMode( value ) {
  40294. let addressMode = GPUAddressMode.ClampToEdge;
  40295. if ( value === RepeatWrapping ) {
  40296. addressMode = GPUAddressMode.Repeat;
  40297. } else if ( value === MirroredRepeatWrapping ) {
  40298. addressMode = GPUAddressMode.MirrorRepeat;
  40299. }
  40300. return addressMode;
  40301. }
  40302. _convertFilterMode( value ) {
  40303. let filterMode = GPUFilterMode.Linear;
  40304. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  40305. filterMode = GPUFilterMode.Nearest;
  40306. }
  40307. return filterMode;
  40308. }
  40309. _getBytesPerTexel( format ) {
  40310. // 8-bit formats
  40311. if ( format === GPUTextureFormat.R8Unorm ||
  40312. format === GPUTextureFormat.R8Snorm ||
  40313. format === GPUTextureFormat.R8Uint ||
  40314. format === GPUTextureFormat.R8Sint ) return 1;
  40315. // 16-bit formats
  40316. if ( format === GPUTextureFormat.R16Uint ||
  40317. format === GPUTextureFormat.R16Sint ||
  40318. format === GPUTextureFormat.R16Float ||
  40319. format === GPUTextureFormat.RG8Unorm ||
  40320. format === GPUTextureFormat.RG8Snorm ||
  40321. format === GPUTextureFormat.RG8Uint ||
  40322. format === GPUTextureFormat.RG8Sint ) return 2;
  40323. // 32-bit formats
  40324. if ( format === GPUTextureFormat.R32Uint ||
  40325. format === GPUTextureFormat.R32Sint ||
  40326. format === GPUTextureFormat.R32Float ||
  40327. format === GPUTextureFormat.RG16Uint ||
  40328. format === GPUTextureFormat.RG16Sint ||
  40329. format === GPUTextureFormat.RG16Float ||
  40330. format === GPUTextureFormat.RGBA8Unorm ||
  40331. format === GPUTextureFormat.RGBA8UnormSRGB ||
  40332. format === GPUTextureFormat.RGBA8Snorm ||
  40333. format === GPUTextureFormat.RGBA8Uint ||
  40334. format === GPUTextureFormat.RGBA8Sint ||
  40335. format === GPUTextureFormat.BGRA8Unorm ||
  40336. format === GPUTextureFormat.BGRA8UnormSRGB ||
  40337. // Packed 32-bit formats
  40338. format === GPUTextureFormat.RGB9E5UFloat ||
  40339. format === GPUTextureFormat.RGB10A2Unorm ||
  40340. format === GPUTextureFormat.RG11B10UFloat ||
  40341. format === GPUTextureFormat.Depth32Float ||
  40342. format === GPUTextureFormat.Depth24Plus ||
  40343. format === GPUTextureFormat.Depth24PlusStencil8 ||
  40344. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  40345. // 64-bit formats
  40346. if ( format === GPUTextureFormat.RG32Uint ||
  40347. format === GPUTextureFormat.RG32Sint ||
  40348. format === GPUTextureFormat.RG32Float ||
  40349. format === GPUTextureFormat.RGBA16Uint ||
  40350. format === GPUTextureFormat.RGBA16Sint ||
  40351. format === GPUTextureFormat.RGBA16Float ) return 8;
  40352. // 128-bit formats
  40353. if ( format === GPUTextureFormat.RGBA32Uint ||
  40354. format === GPUTextureFormat.RGBA32Sint ||
  40355. format === GPUTextureFormat.RGBA32Float ) return 16;
  40356. }
  40357. _getTypedArrayType( format ) {
  40358. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  40359. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  40360. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  40361. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  40362. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  40363. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  40364. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  40365. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  40366. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  40367. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  40368. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  40369. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  40370. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  40371. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  40372. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  40373. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  40374. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  40375. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  40376. if ( format === GPUTextureFormat.R16Float ) return Float32Array;
  40377. if ( format === GPUTextureFormat.RG16Float ) return Float32Array;
  40378. if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array;
  40379. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  40380. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  40381. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  40382. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  40383. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  40384. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  40385. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  40386. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  40387. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  40388. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  40389. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  40390. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  40391. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  40392. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  40393. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  40394. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  40395. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  40396. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  40397. }
  40398. _getDimension( texture ) {
  40399. let dimension;
  40400. if ( texture.isData3DTexture ) {
  40401. dimension = GPUTextureDimension.ThreeD;
  40402. } else {
  40403. dimension = GPUTextureDimension.TwoD;
  40404. }
  40405. return dimension;
  40406. }
  40407. }
  40408. function getFormat( texture, device = null ) {
  40409. const format = texture.format;
  40410. const type = texture.type;
  40411. const colorSpace = texture.colorSpace;
  40412. let formatGPU;
  40413. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  40414. formatGPU = GPUTextureFormat.BGRA8Unorm;
  40415. } else if ( texture.isCompressedTexture === true ) {
  40416. switch ( format ) {
  40417. case RGBA_S3TC_DXT1_Format:
  40418. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  40419. break;
  40420. case RGBA_S3TC_DXT3_Format:
  40421. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  40422. break;
  40423. case RGBA_S3TC_DXT5_Format:
  40424. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  40425. break;
  40426. case RGB_ETC2_Format:
  40427. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  40428. break;
  40429. case RGBA_ETC2_EAC_Format:
  40430. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  40431. break;
  40432. case RGBA_ASTC_4x4_Format:
  40433. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  40434. break;
  40435. case RGBA_ASTC_5x4_Format:
  40436. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  40437. break;
  40438. case RGBA_ASTC_5x5_Format:
  40439. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  40440. break;
  40441. case RGBA_ASTC_6x5_Format:
  40442. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  40443. break;
  40444. case RGBA_ASTC_6x6_Format:
  40445. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  40446. break;
  40447. case RGBA_ASTC_8x5_Format:
  40448. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  40449. break;
  40450. case RGBA_ASTC_8x6_Format:
  40451. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  40452. break;
  40453. case RGBA_ASTC_8x8_Format:
  40454. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  40455. break;
  40456. case RGBA_ASTC_10x5_Format:
  40457. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  40458. break;
  40459. case RGBA_ASTC_10x6_Format:
  40460. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  40461. break;
  40462. case RGBA_ASTC_10x8_Format:
  40463. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  40464. break;
  40465. case RGBA_ASTC_10x10_Format:
  40466. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  40467. break;
  40468. case RGBA_ASTC_12x10_Format:
  40469. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  40470. break;
  40471. case RGBA_ASTC_12x12_Format:
  40472. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  40473. break;
  40474. default:
  40475. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40476. }
  40477. } else {
  40478. switch ( format ) {
  40479. case RGBAFormat:
  40480. switch ( type ) {
  40481. case ByteType:
  40482. formatGPU = GPUTextureFormat.RGBA8Snorm;
  40483. break;
  40484. case ShortType:
  40485. formatGPU = GPUTextureFormat.RGBA16Sint;
  40486. break;
  40487. case UnsignedShortType:
  40488. formatGPU = GPUTextureFormat.RGBA16Uint;
  40489. break;
  40490. case UnsignedIntType:
  40491. formatGPU = GPUTextureFormat.RGBA32Uint;
  40492. break;
  40493. case IntType:
  40494. formatGPU = GPUTextureFormat.RGBA32Sint;
  40495. break;
  40496. case UnsignedByteType:
  40497. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  40498. break;
  40499. case HalfFloatType:
  40500. formatGPU = GPUTextureFormat.RGBA16Float;
  40501. break;
  40502. case FloatType:
  40503. formatGPU = GPUTextureFormat.RGBA32Float;
  40504. break;
  40505. default:
  40506. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  40507. }
  40508. break;
  40509. case RGBFormat:
  40510. switch ( type ) {
  40511. case UnsignedInt5999Type:
  40512. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  40513. break;
  40514. default:
  40515. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  40516. }
  40517. break;
  40518. case RedFormat:
  40519. switch ( type ) {
  40520. case ByteType:
  40521. formatGPU = GPUTextureFormat.R8Snorm;
  40522. break;
  40523. case ShortType:
  40524. formatGPU = GPUTextureFormat.R16Sint;
  40525. break;
  40526. case UnsignedShortType:
  40527. formatGPU = GPUTextureFormat.R16Uint;
  40528. break;
  40529. case UnsignedIntType:
  40530. formatGPU = GPUTextureFormat.R32Uint;
  40531. break;
  40532. case IntType:
  40533. formatGPU = GPUTextureFormat.R32Sint;
  40534. break;
  40535. case UnsignedByteType:
  40536. formatGPU = GPUTextureFormat.R8Unorm;
  40537. break;
  40538. case HalfFloatType:
  40539. formatGPU = GPUTextureFormat.R16Float;
  40540. break;
  40541. case FloatType:
  40542. formatGPU = GPUTextureFormat.R32Float;
  40543. break;
  40544. default:
  40545. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  40546. }
  40547. break;
  40548. case RGFormat:
  40549. switch ( type ) {
  40550. case ByteType:
  40551. formatGPU = GPUTextureFormat.RG8Snorm;
  40552. break;
  40553. case ShortType:
  40554. formatGPU = GPUTextureFormat.RG16Sint;
  40555. break;
  40556. case UnsignedShortType:
  40557. formatGPU = GPUTextureFormat.RG16Uint;
  40558. break;
  40559. case UnsignedIntType:
  40560. formatGPU = GPUTextureFormat.RG32Uint;
  40561. break;
  40562. case IntType:
  40563. formatGPU = GPUTextureFormat.RG32Sint;
  40564. break;
  40565. case UnsignedByteType:
  40566. formatGPU = GPUTextureFormat.RG8Unorm;
  40567. break;
  40568. case HalfFloatType:
  40569. formatGPU = GPUTextureFormat.RG16Float;
  40570. break;
  40571. case FloatType:
  40572. formatGPU = GPUTextureFormat.RG32Float;
  40573. break;
  40574. default:
  40575. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  40576. }
  40577. break;
  40578. case DepthFormat:
  40579. switch ( type ) {
  40580. case UnsignedShortType:
  40581. formatGPU = GPUTextureFormat.Depth16Unorm;
  40582. break;
  40583. case UnsignedIntType:
  40584. formatGPU = GPUTextureFormat.Depth24Plus;
  40585. break;
  40586. case FloatType:
  40587. formatGPU = GPUTextureFormat.Depth32Float;
  40588. break;
  40589. default:
  40590. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  40591. }
  40592. break;
  40593. case DepthStencilFormat:
  40594. switch ( type ) {
  40595. case UnsignedInt248Type:
  40596. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  40597. break;
  40598. case FloatType:
  40599. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  40600. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  40601. }
  40602. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  40603. break;
  40604. default:
  40605. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  40606. }
  40607. break;
  40608. case RedIntegerFormat:
  40609. switch ( type ) {
  40610. case IntType:
  40611. formatGPU = GPUTextureFormat.R32Sint;
  40612. break;
  40613. case UnsignedIntType:
  40614. formatGPU = GPUTextureFormat.R32Uint;
  40615. break;
  40616. default:
  40617. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  40618. }
  40619. break;
  40620. case RGIntegerFormat:
  40621. switch ( type ) {
  40622. case IntType:
  40623. formatGPU = GPUTextureFormat.RG32Sint;
  40624. break;
  40625. case UnsignedIntType:
  40626. formatGPU = GPUTextureFormat.RG32Uint;
  40627. break;
  40628. default:
  40629. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  40630. }
  40631. break;
  40632. case RGBAIntegerFormat:
  40633. switch ( type ) {
  40634. case IntType:
  40635. formatGPU = GPUTextureFormat.RGBA32Sint;
  40636. break;
  40637. case UnsignedIntType:
  40638. formatGPU = GPUTextureFormat.RGBA32Uint;
  40639. break;
  40640. default:
  40641. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  40642. }
  40643. break;
  40644. default:
  40645. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40646. }
  40647. }
  40648. return formatGPU;
  40649. }
  40650. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  40651. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  40652. const wgslTypeLib$1 = {
  40653. 'f32': 'float',
  40654. 'i32': 'int',
  40655. 'u32': 'uint',
  40656. 'bool': 'bool',
  40657. 'vec2<f32>': 'vec2',
  40658. 'vec2<i32>': 'ivec2',
  40659. 'vec2<u32>': 'uvec2',
  40660. 'vec2<bool>': 'bvec2',
  40661. 'vec2f': 'vec2',
  40662. 'vec2i': 'ivec2',
  40663. 'vec2u': 'uvec2',
  40664. 'vec2b': 'bvec2',
  40665. 'vec3<f32>': 'vec3',
  40666. 'vec3<i32>': 'ivec3',
  40667. 'vec3<u32>': 'uvec3',
  40668. 'vec3<bool>': 'bvec3',
  40669. 'vec3f': 'vec3',
  40670. 'vec3i': 'ivec3',
  40671. 'vec3u': 'uvec3',
  40672. 'vec3b': 'bvec3',
  40673. 'vec4<f32>': 'vec4',
  40674. 'vec4<i32>': 'ivec4',
  40675. 'vec4<u32>': 'uvec4',
  40676. 'vec4<bool>': 'bvec4',
  40677. 'vec4f': 'vec4',
  40678. 'vec4i': 'ivec4',
  40679. 'vec4u': 'uvec4',
  40680. 'vec4b': 'bvec4',
  40681. 'mat2x2<f32>': 'mat2',
  40682. 'mat2x2f': 'mat2',
  40683. 'mat3x3<f32>': 'mat3',
  40684. 'mat3x3f': 'mat3',
  40685. 'mat4x4<f32>': 'mat4',
  40686. 'mat4x4f': 'mat4',
  40687. 'sampler': 'sampler',
  40688. 'texture_2d': 'texture',
  40689. 'texture_cube': 'cubeTexture',
  40690. 'texture_depth_2d': 'depthTexture',
  40691. 'texture_storage_2d': 'storageTexture',
  40692. 'texture_3d': 'texture3D'
  40693. };
  40694. const parse = ( source ) => {
  40695. source = source.trim();
  40696. const declaration = source.match( declarationRegexp );
  40697. if ( declaration !== null && declaration.length === 4 ) {
  40698. const inputsCode = declaration[ 2 ];
  40699. const propsMatches = [];
  40700. let match = null;
  40701. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  40702. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  40703. }
  40704. // Process matches to correctly pair names and types
  40705. const inputs = [];
  40706. for ( let i = 0; i < propsMatches.length; i ++ ) {
  40707. const { name, type } = propsMatches[ i ];
  40708. let resolvedType = type;
  40709. if ( resolvedType.startsWith( 'texture' ) ) {
  40710. resolvedType = type.split( '<' )[ 0 ];
  40711. }
  40712. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  40713. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  40714. }
  40715. const blockCode = source.substring( declaration[ 0 ].length );
  40716. const outputType = declaration[ 3 ] || 'void';
  40717. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  40718. const type = wgslTypeLib$1[ outputType ] || outputType;
  40719. return {
  40720. type,
  40721. inputs,
  40722. name,
  40723. inputsCode,
  40724. blockCode,
  40725. outputType
  40726. };
  40727. } else {
  40728. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  40729. }
  40730. };
  40731. class WGSLNodeFunction extends NodeFunction {
  40732. constructor( source ) {
  40733. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  40734. super( type, inputs, name );
  40735. this.inputsCode = inputsCode;
  40736. this.blockCode = blockCode;
  40737. this.outputType = outputType;
  40738. }
  40739. getCode( name = this.name ) {
  40740. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  40741. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  40742. }
  40743. }
  40744. class WGSLNodeParser extends NodeParser {
  40745. parseFunction( source ) {
  40746. return new WGSLNodeFunction( source );
  40747. }
  40748. }
  40749. // GPUShaderStage is not defined in browsers not supporting WebGPU
  40750. const GPUShaderStage = self.GPUShaderStage;
  40751. const gpuShaderStageLib = {
  40752. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  40753. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  40754. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  40755. };
  40756. const supports = {
  40757. instance: true,
  40758. swizzleAssign: false,
  40759. storageBuffer: true
  40760. };
  40761. const wgslFnOpLib = {
  40762. '^^': 'threejs_xor'
  40763. };
  40764. const wgslTypeLib = {
  40765. float: 'f32',
  40766. int: 'i32',
  40767. uint: 'u32',
  40768. bool: 'bool',
  40769. color: 'vec3<f32>',
  40770. vec2: 'vec2<f32>',
  40771. ivec2: 'vec2<i32>',
  40772. uvec2: 'vec2<u32>',
  40773. bvec2: 'vec2<bool>',
  40774. vec3: 'vec3<f32>',
  40775. ivec3: 'vec3<i32>',
  40776. uvec3: 'vec3<u32>',
  40777. bvec3: 'vec3<bool>',
  40778. vec4: 'vec4<f32>',
  40779. ivec4: 'vec4<i32>',
  40780. uvec4: 'vec4<u32>',
  40781. bvec4: 'vec4<bool>',
  40782. mat2: 'mat2x2<f32>',
  40783. imat2: 'mat2x2<i32>',
  40784. umat2: 'mat2x2<u32>',
  40785. bmat2: 'mat2x2<bool>',
  40786. mat3: 'mat3x3<f32>',
  40787. imat3: 'mat3x3<i32>',
  40788. umat3: 'mat3x3<u32>',
  40789. bmat3: 'mat3x3<bool>',
  40790. mat4: 'mat4x4<f32>',
  40791. imat4: 'mat4x4<i32>',
  40792. umat4: 'mat4x4<u32>',
  40793. bmat4: 'mat4x4<bool>'
  40794. };
  40795. const wgslMethods = {
  40796. dFdx: 'dpdx',
  40797. dFdy: '- dpdy',
  40798. mod_float: 'threejs_mod_float',
  40799. mod_vec2: 'threejs_mod_vec2',
  40800. mod_vec3: 'threejs_mod_vec3',
  40801. mod_vec4: 'threejs_mod_vec4',
  40802. equals_bool: 'threejs_equals_bool',
  40803. equals_bvec2: 'threejs_equals_bvec2',
  40804. equals_bvec3: 'threejs_equals_bvec3',
  40805. equals_bvec4: 'threejs_equals_bvec4',
  40806. lessThanEqual: 'threejs_lessThanEqual',
  40807. greaterThan: 'threejs_greaterThan',
  40808. inversesqrt: 'inverseSqrt',
  40809. bitcast: 'bitcast<f32>'
  40810. };
  40811. const wgslPolyfill = {
  40812. threejs_xor: new CodeNode( `
  40813. fn threejs_xor( a : bool, b : bool ) -> bool {
  40814. return ( a || b ) && !( a && b );
  40815. }
  40816. ` ),
  40817. lessThanEqual: new CodeNode( `
  40818. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  40819. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  40820. }
  40821. ` ),
  40822. greaterThan: new CodeNode( `
  40823. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  40824. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  40825. }
  40826. ` ),
  40827. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  40828. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  40829. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  40830. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  40831. equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  40832. equals_bvec2: new CodeNode( 'fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  40833. equals_bvec3: new CodeNode( 'fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  40834. equals_bvec4: new CodeNode( 'fn threejs_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 ); }' ),
  40835. repeatWrapping: new CodeNode( `
  40836. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  40837. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  40838. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  40839. }
  40840. ` ),
  40841. biquadraticTexture: new CodeNode( `
  40842. fn threejs_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  40843. let res = vec2f( textureDimensions( map, level ) );
  40844. let uvScaled = coord * res;
  40845. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  40846. // https://www.shadertoy.com/view/WtyXRy
  40847. let uv = uvWrapping - 0.5;
  40848. let iuv = floor( uv );
  40849. let f = fract( uv );
  40850. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  40851. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  40852. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  40853. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  40854. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  40855. }
  40856. ` )
  40857. };
  40858. class WGSLNodeBuilder extends NodeBuilder {
  40859. constructor( object, renderer ) {
  40860. super( object, renderer, new WGSLNodeParser() );
  40861. this.uniformGroups = {};
  40862. this.builtins = {};
  40863. }
  40864. needsColorSpaceToLinear( texture ) {
  40865. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  40866. }
  40867. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40868. if ( shaderStage === 'fragment' ) {
  40869. if ( depthSnippet ) {
  40870. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  40871. } else {
  40872. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  40873. }
  40874. } else if ( this.isFilteredTexture( texture ) ) {
  40875. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  40876. } else {
  40877. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  40878. }
  40879. }
  40880. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  40881. if ( shaderStage === 'fragment' ) {
  40882. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  40883. } else {
  40884. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  40885. }
  40886. }
  40887. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40888. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  40889. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  40890. } else if ( this.isFilteredTexture( texture ) ) {
  40891. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  40892. } else {
  40893. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  40894. }
  40895. }
  40896. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  40897. this._include( 'biquadraticTexture' );
  40898. return `threejs_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  40899. }
  40900. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  40901. this._include( 'repeatWrapping' );
  40902. const dimension = `textureDimensions( ${ textureProperty }, 0 )`;
  40903. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  40904. }
  40905. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  40906. if ( depthSnippet ) {
  40907. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  40908. } else {
  40909. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  40910. }
  40911. }
  40912. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  40913. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  40914. }
  40915. isUnfilterable( texture ) {
  40916. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( texture.isDataTexture === true && texture.type === FloatType );
  40917. }
  40918. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40919. let snippet = null;
  40920. if ( texture.isVideoTexture === true ) {
  40921. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  40922. } else if ( this.isUnfilterable( texture ) ) {
  40923. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  40924. } else {
  40925. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  40926. }
  40927. return snippet;
  40928. }
  40929. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40930. if ( shaderStage === 'fragment' ) {
  40931. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  40932. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  40933. } else {
  40934. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  40935. }
  40936. }
  40937. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40938. if ( shaderStage === 'fragment' ) {
  40939. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  40940. } else {
  40941. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  40942. }
  40943. }
  40944. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40945. let snippet = null;
  40946. if ( texture.isVideoTexture === true ) {
  40947. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  40948. } else {
  40949. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  40950. }
  40951. return snippet;
  40952. }
  40953. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40954. if ( shaderStage === 'fragment' ) {
  40955. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  40956. } else {
  40957. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  40958. }
  40959. }
  40960. getPropertyName( node, shaderStage = this.shaderStage ) {
  40961. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  40962. if ( shaderStage === 'vertex' ) {
  40963. return `varyings.${ node.name }`;
  40964. }
  40965. } else if ( node.isNodeUniform === true ) {
  40966. const name = node.name;
  40967. const type = node.type;
  40968. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  40969. return name;
  40970. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  40971. return `NodeBuffer_${ node.id }.${name}`;
  40972. } else {
  40973. return node.groupNode.name + '.' + name;
  40974. }
  40975. }
  40976. return super.getPropertyName( node );
  40977. }
  40978. getOutputStructName() {
  40979. return 'output';
  40980. }
  40981. _getUniformGroupCount( shaderStage ) {
  40982. return Object.keys( this.uniforms[ shaderStage ] ).length;
  40983. }
  40984. getFunctionOperator( op ) {
  40985. const fnOp = wgslFnOpLib[ op ];
  40986. if ( fnOp !== undefined ) {
  40987. this._include( fnOp );
  40988. return fnOp;
  40989. }
  40990. return null;
  40991. }
  40992. getStorageAccess( node ) {
  40993. if ( node.isStorageTextureNode ) {
  40994. switch ( node.access ) {
  40995. case GPUStorageTextureAccess.ReadOnly:
  40996. return 'read';
  40997. case GPUStorageTextureAccess.WriteOnly:
  40998. return 'write';
  40999. default:
  41000. return 'read_write';
  41001. }
  41002. } else {
  41003. switch ( node.access ) {
  41004. case GPUBufferBindingType.Storage:
  41005. return 'read_write';
  41006. case GPUBufferBindingType.ReadOnlyStorage:
  41007. return 'read';
  41008. default:
  41009. return 'write';
  41010. }
  41011. }
  41012. }
  41013. getUniformFromNode( node, type, shaderStage, name = null ) {
  41014. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  41015. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  41016. if ( nodeData.uniformGPU === undefined ) {
  41017. let uniformGPU;
  41018. const group = node.groupNode;
  41019. const groupName = group.name;
  41020. const bindings = this.getBindGroupArray( groupName, shaderStage );
  41021. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  41022. let texture = null;
  41023. if ( type === 'texture' || type === 'storageTexture' ) {
  41024. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  41025. } else if ( type === 'cubeTexture' ) {
  41026. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  41027. } else if ( type === 'texture3D' ) {
  41028. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  41029. }
  41030. texture.store = node.isStorageTextureNode === true;
  41031. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41032. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  41033. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  41034. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41035. bindings.push( sampler, texture );
  41036. uniformGPU = [ sampler, texture ];
  41037. } else {
  41038. bindings.push( texture );
  41039. uniformGPU = [ texture ];
  41040. }
  41041. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  41042. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  41043. const buffer = new bufferClass( node, group );
  41044. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41045. bindings.push( buffer );
  41046. uniformGPU = buffer;
  41047. } else {
  41048. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  41049. let uniformsGroup = uniformsStage[ groupName ];
  41050. if ( uniformsGroup === undefined ) {
  41051. uniformsGroup = new NodeUniformsGroup( groupName, group );
  41052. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41053. uniformsStage[ groupName ] = uniformsGroup;
  41054. bindings.push( uniformsGroup );
  41055. }
  41056. uniformGPU = this.getNodeUniform( uniformNode, type );
  41057. uniformsGroup.addUniform( uniformGPU );
  41058. }
  41059. nodeData.uniformGPU = uniformGPU;
  41060. }
  41061. return uniformNode;
  41062. }
  41063. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  41064. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  41065. if ( map.has( name ) === false ) {
  41066. map.set( name, {
  41067. name,
  41068. property,
  41069. type
  41070. } );
  41071. }
  41072. return property;
  41073. }
  41074. getVertexIndex() {
  41075. if ( this.shaderStage === 'vertex' ) {
  41076. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  41077. }
  41078. return 'vertexIndex';
  41079. }
  41080. buildFunctionCode( shaderNode ) {
  41081. const layout = shaderNode.layout;
  41082. const flowData = this.flowShaderNode( shaderNode );
  41083. const parameters = [];
  41084. for ( const input of layout.inputs ) {
  41085. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  41086. }
  41087. //
  41088. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  41089. ${ flowData.vars }
  41090. ${ flowData.code }
  41091. return ${ flowData.result };
  41092. }`;
  41093. //
  41094. return code;
  41095. }
  41096. getInstanceIndex() {
  41097. if ( this.shaderStage === 'vertex' ) {
  41098. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  41099. }
  41100. return 'instanceIndex';
  41101. }
  41102. getDrawIndex() {
  41103. return null;
  41104. }
  41105. getFrontFacing() {
  41106. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  41107. }
  41108. getFragCoord() {
  41109. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xyz';
  41110. }
  41111. getFragDepth() {
  41112. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  41113. }
  41114. isFlipY() {
  41115. return false;
  41116. }
  41117. getBuiltins( shaderStage ) {
  41118. const snippets = [];
  41119. const builtins = this.builtins[ shaderStage ];
  41120. if ( builtins !== undefined ) {
  41121. for ( const { name, property, type } of builtins.values() ) {
  41122. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  41123. }
  41124. }
  41125. return snippets.join( ',\n\t' );
  41126. }
  41127. getAttributes( shaderStage ) {
  41128. const snippets = [];
  41129. if ( shaderStage === 'compute' ) {
  41130. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  41131. }
  41132. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41133. const builtins = this.getBuiltins( 'attribute' );
  41134. if ( builtins ) snippets.push( builtins );
  41135. const attributes = this.getAttributesArray();
  41136. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  41137. const attribute = attributes[ index ];
  41138. const name = attribute.name;
  41139. const type = this.getType( attribute.type );
  41140. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  41141. }
  41142. }
  41143. return snippets.join( ',\n\t' );
  41144. }
  41145. getStructMembers( struct ) {
  41146. const snippets = [];
  41147. const members = struct.getMemberTypes();
  41148. for ( let i = 0; i < members.length; i ++ ) {
  41149. const member = members[ i ];
  41150. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  41151. }
  41152. const builtins = this.getBuiltins( 'output' );
  41153. if ( builtins ) snippets.push( builtins );
  41154. return snippets.join( ',\n' );
  41155. }
  41156. getStructs( shaderStage ) {
  41157. const snippets = [];
  41158. const structs = this.structs[ shaderStage ];
  41159. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  41160. const struct = structs[ index ];
  41161. const name = struct.name;
  41162. let snippet = `\struct ${ name } {\n`;
  41163. snippet += this.getStructMembers( struct );
  41164. snippet += '\n}';
  41165. snippets.push( snippet );
  41166. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  41167. }
  41168. return snippets.join( '\n\n' );
  41169. }
  41170. getVar( type, name ) {
  41171. return `var ${ name } : ${ this.getType( type ) }`;
  41172. }
  41173. getVars( shaderStage ) {
  41174. const snippets = [];
  41175. const vars = this.vars[ shaderStage ];
  41176. if ( vars !== undefined ) {
  41177. for ( const variable of vars ) {
  41178. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  41179. }
  41180. }
  41181. return `\n${ snippets.join( '\n' ) }\n`;
  41182. }
  41183. getVaryings( shaderStage ) {
  41184. const snippets = [];
  41185. if ( shaderStage === 'vertex' ) {
  41186. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  41187. }
  41188. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  41189. const varyings = this.varyings;
  41190. const vars = this.vars[ shaderStage ];
  41191. for ( let index = 0; index < varyings.length; index ++ ) {
  41192. const varying = varyings[ index ];
  41193. if ( varying.needsInterpolation ) {
  41194. let attributesSnippet = `@location( ${index} )`;
  41195. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  41196. attributesSnippet += ' @interpolate( flat )';
  41197. }
  41198. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  41199. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  41200. vars.push( varying );
  41201. }
  41202. }
  41203. }
  41204. const builtins = this.getBuiltins( shaderStage );
  41205. if ( builtins ) snippets.push( builtins );
  41206. const code = snippets.join( ',\n\t' );
  41207. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  41208. }
  41209. getUniforms( shaderStage ) {
  41210. const uniforms = this.uniforms[ shaderStage ];
  41211. const bindingSnippets = [];
  41212. const bufferSnippets = [];
  41213. const structSnippets = [];
  41214. const uniformGroups = {};
  41215. for ( const uniform of uniforms ) {
  41216. const groundName = uniform.groupNode.name;
  41217. const uniformIndexes = this.bindingsIndexes[ groundName ];
  41218. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  41219. const texture = uniform.node.value;
  41220. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  41221. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  41222. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  41223. } else {
  41224. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  41225. }
  41226. }
  41227. let textureType;
  41228. if ( texture.isCubeTexture === true ) {
  41229. textureType = 'texture_cube<f32>';
  41230. } else if ( texture.isDataArrayTexture === true ) {
  41231. textureType = 'texture_2d_array<f32>';
  41232. } else if ( texture.isDepthTexture === true ) {
  41233. textureType = 'texture_depth_2d';
  41234. } else if ( texture.isVideoTexture === true ) {
  41235. textureType = 'texture_external';
  41236. } else if ( texture.isData3DTexture === true ) {
  41237. textureType = 'texture_3d<f32>';
  41238. } else if ( uniform.node.isStorageTextureNode === true ) {
  41239. const format = getFormat( texture );
  41240. const access = this.getStorageAccess( uniform.node );
  41241. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  41242. } else {
  41243. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  41244. textureType = `texture_2d<${ componentPrefix }32>`;
  41245. }
  41246. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  41247. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  41248. const bufferNode = uniform.node;
  41249. const bufferType = this.getType( bufferNode.bufferType );
  41250. const bufferCount = bufferNode.bufferCount;
  41251. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  41252. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferType }${ bufferCountSnippet } >\n`;
  41253. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  41254. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  41255. } else {
  41256. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  41257. const groupName = uniform.groupNode.name;
  41258. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  41259. index: uniformIndexes.binding ++,
  41260. id: uniformIndexes.group,
  41261. snippets: []
  41262. } );
  41263. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  41264. }
  41265. }
  41266. for ( const name in uniformGroups ) {
  41267. const group = uniformGroups[ name ];
  41268. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  41269. }
  41270. let code = bindingSnippets.join( '\n' );
  41271. code += bufferSnippets.join( '\n' );
  41272. code += structSnippets.join( '\n' );
  41273. return code;
  41274. }
  41275. buildCode() {
  41276. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  41277. for ( const shaderStage in shadersData ) {
  41278. const stageData = shadersData[ shaderStage ];
  41279. stageData.uniforms = this.getUniforms( shaderStage );
  41280. stageData.attributes = this.getAttributes( shaderStage );
  41281. stageData.varyings = this.getVaryings( shaderStage );
  41282. stageData.structs = this.getStructs( shaderStage );
  41283. stageData.vars = this.getVars( shaderStage );
  41284. stageData.codes = this.getCodes( shaderStage );
  41285. //
  41286. let flow = '// code\n\n';
  41287. flow += this.flowCode[ shaderStage ];
  41288. const flowNodes = this.flowNodes[ shaderStage ];
  41289. const mainNode = flowNodes[ flowNodes.length - 1 ];
  41290. const outputNode = mainNode.outputNode;
  41291. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  41292. for ( const node of flowNodes ) {
  41293. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  41294. const slotName = node.name;
  41295. if ( slotName ) {
  41296. if ( flow.length > 0 ) flow += '\n';
  41297. flow += `\t// flow -> ${ slotName }\n\t`;
  41298. }
  41299. flow += `${ flowSlotData.code }\n\t`;
  41300. if ( node === mainNode && shaderStage !== 'compute' ) {
  41301. flow += '// result\n\n\t';
  41302. if ( shaderStage === 'vertex' ) {
  41303. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  41304. } else if ( shaderStage === 'fragment' ) {
  41305. if ( isOutputStruct ) {
  41306. stageData.returnType = outputNode.nodeType;
  41307. flow += `return ${ flowSlotData.result };`;
  41308. } else {
  41309. let structSnippet = '\t@location(0) color: vec4<f32>';
  41310. const builtins = this.getBuiltins( 'output' );
  41311. if ( builtins ) structSnippet += ',\n\t' + builtins;
  41312. stageData.returnType = 'OutputStruct';
  41313. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  41314. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  41315. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  41316. }
  41317. }
  41318. }
  41319. }
  41320. stageData.flow = flow;
  41321. }
  41322. if ( this.material !== null ) {
  41323. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  41324. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  41325. } else {
  41326. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  41327. }
  41328. }
  41329. getMethod( method, output = null ) {
  41330. let wgslMethod;
  41331. if ( output !== null ) {
  41332. wgslMethod = this._getWGSLMethod( method + '_' + output );
  41333. }
  41334. if ( wgslMethod === undefined ) {
  41335. wgslMethod = this._getWGSLMethod( method );
  41336. }
  41337. return wgslMethod || method;
  41338. }
  41339. getType( type ) {
  41340. return wgslTypeLib[ type ] || type;
  41341. }
  41342. isAvailable( name ) {
  41343. let result = supports[ name ];
  41344. if ( result === undefined ) {
  41345. if ( name === 'float32Filterable' ) {
  41346. result = this.renderer.hasFeature( 'float32-filterable' );
  41347. }
  41348. supports[ name ] = result;
  41349. }
  41350. return result;
  41351. }
  41352. _getWGSLMethod( method ) {
  41353. if ( wgslPolyfill[ method ] !== undefined ) {
  41354. this._include( method );
  41355. }
  41356. return wgslMethods[ method ];
  41357. }
  41358. _include( name ) {
  41359. const codeNode = wgslPolyfill[ name ];
  41360. codeNode.build( this );
  41361. if ( this.currentFunctionNode !== null ) {
  41362. this.currentFunctionNode.includes.push( codeNode );
  41363. }
  41364. return codeNode;
  41365. }
  41366. _getWGSLVertexCode( shaderData ) {
  41367. return `${ this.getSignature() }
  41368. // uniforms
  41369. ${shaderData.uniforms}
  41370. // varyings
  41371. ${shaderData.varyings}
  41372. var<private> varyings : VaryingsStruct;
  41373. // codes
  41374. ${shaderData.codes}
  41375. @vertex
  41376. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  41377. // vars
  41378. ${shaderData.vars}
  41379. // flow
  41380. ${shaderData.flow}
  41381. return varyings;
  41382. }
  41383. `;
  41384. }
  41385. _getWGSLFragmentCode( shaderData ) {
  41386. return `${ this.getSignature() }
  41387. // uniforms
  41388. ${shaderData.uniforms}
  41389. // structs
  41390. ${shaderData.structs}
  41391. // codes
  41392. ${shaderData.codes}
  41393. @fragment
  41394. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  41395. // vars
  41396. ${shaderData.vars}
  41397. // flow
  41398. ${shaderData.flow}
  41399. }
  41400. `;
  41401. }
  41402. _getWGSLComputeCode( shaderData, workgroupSize ) {
  41403. return `${ this.getSignature() }
  41404. // system
  41405. var<private> instanceIndex : u32;
  41406. // uniforms
  41407. ${shaderData.uniforms}
  41408. // codes
  41409. ${shaderData.codes}
  41410. @compute @workgroup_size( ${workgroupSize} )
  41411. fn main( ${shaderData.attributes} ) {
  41412. // system
  41413. instanceIndex = id.x;
  41414. // vars
  41415. ${shaderData.vars}
  41416. // flow
  41417. ${shaderData.flow}
  41418. }
  41419. `;
  41420. }
  41421. _getWGSLStruct( name, vars ) {
  41422. return `
  41423. struct ${name} {
  41424. ${vars}
  41425. };`;
  41426. }
  41427. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  41428. const structName = name + 'Struct';
  41429. const structSnippet = this._getWGSLStruct( structName, vars );
  41430. return `${structSnippet}
  41431. @binding( ${binding} ) @group( ${group} )
  41432. var<${access}> ${name} : ${structName};`;
  41433. }
  41434. }
  41435. class WebGPUUtils {
  41436. constructor( backend ) {
  41437. this.backend = backend;
  41438. }
  41439. getCurrentDepthStencilFormat( renderContext ) {
  41440. let format;
  41441. if ( renderContext.depthTexture !== null ) {
  41442. format = this.getTextureFormatGPU( renderContext.depthTexture );
  41443. } else if ( renderContext.depth && renderContext.stencil ) {
  41444. format = GPUTextureFormat.Depth24PlusStencil8;
  41445. } else if ( renderContext.depth ) {
  41446. format = GPUTextureFormat.Depth24Plus;
  41447. }
  41448. return format;
  41449. }
  41450. getTextureFormatGPU( texture ) {
  41451. return this.backend.get( texture ).texture.format;
  41452. }
  41453. getCurrentColorFormat( renderContext ) {
  41454. let format;
  41455. if ( renderContext.textures !== null ) {
  41456. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  41457. } else {
  41458. format = GPUTextureFormat.BGRA8Unorm; // default context format
  41459. }
  41460. return format;
  41461. }
  41462. getCurrentColorSpace( renderContext ) {
  41463. if ( renderContext.textures !== null ) {
  41464. return renderContext.textures[ 0 ].colorSpace;
  41465. }
  41466. return this.backend.renderer.outputColorSpace;
  41467. }
  41468. getPrimitiveTopology( object, material ) {
  41469. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  41470. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  41471. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  41472. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  41473. }
  41474. getSampleCount( renderContext ) {
  41475. if ( renderContext.textures !== null ) {
  41476. return renderContext.sampleCount;
  41477. }
  41478. return this.backend.parameters.sampleCount;
  41479. }
  41480. }
  41481. const typedArraysToVertexFormatPrefix = new Map( [
  41482. [ Int8Array, [ 'sint8', 'snorm8' ]],
  41483. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  41484. [ Int16Array, [ 'sint16', 'snorm16' ]],
  41485. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  41486. [ Int32Array, [ 'sint32', 'snorm32' ]],
  41487. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  41488. [ Float32Array, [ 'float32', ]],
  41489. ] );
  41490. const typedAttributeToVertexFormatPrefix = new Map( [
  41491. [ Float16BufferAttribute, [ 'float16', ]],
  41492. ] );
  41493. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  41494. [ Int32Array, 'sint32' ],
  41495. [ Int16Array, 'sint32' ], // patch for INT16
  41496. [ Uint32Array, 'uint32' ],
  41497. [ Uint16Array, 'uint32' ], // patch for UINT16
  41498. [ Float32Array, 'float32' ]
  41499. ] );
  41500. class WebGPUAttributeUtils {
  41501. constructor( backend ) {
  41502. this.backend = backend;
  41503. }
  41504. createAttribute( attribute, usage ) {
  41505. const bufferAttribute = this._getBufferAttribute( attribute );
  41506. const backend = this.backend;
  41507. const bufferData = backend.get( bufferAttribute );
  41508. let buffer = bufferData.buffer;
  41509. if ( buffer === undefined ) {
  41510. const device = backend.device;
  41511. let array = bufferAttribute.array;
  41512. // patch for INT16 and UINT16
  41513. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  41514. const tempArray = new Uint32Array( array.length );
  41515. for ( let i = 0; i < array.length; i ++ ) {
  41516. tempArray[ i ] = array[ i ];
  41517. }
  41518. array = tempArray;
  41519. }
  41520. bufferAttribute.array = array;
  41521. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  41522. array = new array.constructor( bufferAttribute.count * 4 );
  41523. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  41524. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  41525. }
  41526. // Update BufferAttribute
  41527. bufferAttribute.itemSize = 4;
  41528. bufferAttribute.array = array;
  41529. }
  41530. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  41531. buffer = device.createBuffer( {
  41532. label: bufferAttribute.name,
  41533. size: size,
  41534. usage: usage,
  41535. mappedAtCreation: true
  41536. } );
  41537. new array.constructor( buffer.getMappedRange() ).set( array );
  41538. buffer.unmap();
  41539. bufferData.buffer = buffer;
  41540. }
  41541. }
  41542. updateAttribute( attribute ) {
  41543. const bufferAttribute = this._getBufferAttribute( attribute );
  41544. const backend = this.backend;
  41545. const device = backend.device;
  41546. const buffer = backend.get( bufferAttribute ).buffer;
  41547. const array = bufferAttribute.array;
  41548. const updateRanges = bufferAttribute.updateRanges;
  41549. if ( updateRanges.length === 0 ) {
  41550. // Not using update ranges
  41551. device.queue.writeBuffer(
  41552. buffer,
  41553. 0,
  41554. array,
  41555. 0
  41556. );
  41557. } else {
  41558. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41559. const range = updateRanges[ i ];
  41560. device.queue.writeBuffer(
  41561. buffer,
  41562. 0,
  41563. array,
  41564. range.start * array.BYTES_PER_ELEMENT,
  41565. range.count * array.BYTES_PER_ELEMENT
  41566. );
  41567. }
  41568. bufferAttribute.clearUpdateRanges();
  41569. }
  41570. }
  41571. createShaderVertexBuffers( renderObject ) {
  41572. const attributes = renderObject.getAttributes();
  41573. const vertexBuffers = new Map();
  41574. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  41575. const geometryAttribute = attributes[ slot ];
  41576. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  41577. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  41578. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  41579. if ( vertexBufferLayout === undefined ) {
  41580. let arrayStride, stepMode;
  41581. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  41582. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  41583. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41584. } else {
  41585. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  41586. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41587. }
  41588. // patch for INT16 and UINT16
  41589. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  41590. arrayStride = 4;
  41591. }
  41592. vertexBufferLayout = {
  41593. arrayStride,
  41594. attributes: [],
  41595. stepMode
  41596. };
  41597. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  41598. }
  41599. const format = this._getVertexFormat( geometryAttribute );
  41600. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  41601. vertexBufferLayout.attributes.push( {
  41602. shaderLocation: slot,
  41603. offset,
  41604. format
  41605. } );
  41606. }
  41607. return Array.from( vertexBuffers.values() );
  41608. }
  41609. destroyAttribute( attribute ) {
  41610. const backend = this.backend;
  41611. const data = backend.get( this._getBufferAttribute( attribute ) );
  41612. data.buffer.destroy();
  41613. backend.delete( attribute );
  41614. }
  41615. async getArrayBufferAsync( attribute ) {
  41616. const backend = this.backend;
  41617. const device = backend.device;
  41618. const data = backend.get( this._getBufferAttribute( attribute ) );
  41619. const bufferGPU = data.buffer;
  41620. const size = bufferGPU.size;
  41621. let readBufferGPU = data.readBuffer;
  41622. let needsUnmap = true;
  41623. if ( readBufferGPU === undefined ) {
  41624. readBufferGPU = device.createBuffer( {
  41625. label: attribute.name,
  41626. size,
  41627. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41628. } );
  41629. needsUnmap = false;
  41630. data.readBuffer = readBufferGPU;
  41631. }
  41632. const cmdEncoder = device.createCommandEncoder( {} );
  41633. cmdEncoder.copyBufferToBuffer(
  41634. bufferGPU,
  41635. 0,
  41636. readBufferGPU,
  41637. 0,
  41638. size
  41639. );
  41640. if ( needsUnmap ) readBufferGPU.unmap();
  41641. const gpuCommands = cmdEncoder.finish();
  41642. device.queue.submit( [ gpuCommands ] );
  41643. await readBufferGPU.mapAsync( GPUMapMode.READ );
  41644. const arrayBuffer = readBufferGPU.getMappedRange();
  41645. return arrayBuffer;
  41646. }
  41647. _getVertexFormat( geometryAttribute ) {
  41648. const { itemSize, normalized } = geometryAttribute;
  41649. const ArrayType = geometryAttribute.array.constructor;
  41650. const AttributeType = geometryAttribute.constructor;
  41651. let format;
  41652. if ( itemSize == 1 ) {
  41653. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  41654. } else {
  41655. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  41656. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  41657. if ( prefix ) {
  41658. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  41659. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  41660. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  41661. if ( paddedItemSize % 1 ) {
  41662. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  41663. }
  41664. format = `${prefix}x${paddedItemSize}`;
  41665. }
  41666. }
  41667. if ( ! format ) {
  41668. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  41669. }
  41670. return format;
  41671. }
  41672. _getBufferAttribute( attribute ) {
  41673. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  41674. return attribute;
  41675. }
  41676. }
  41677. class WebGPUBindingUtils {
  41678. constructor( backend ) {
  41679. this.backend = backend;
  41680. }
  41681. createBindingsLayout( bindGroup ) {
  41682. const backend = this.backend;
  41683. const device = backend.device;
  41684. const entries = [];
  41685. let index = 0;
  41686. for ( const binding of bindGroup.bindings ) {
  41687. const bindingGPU = {
  41688. binding: index ++,
  41689. visibility: binding.visibility
  41690. };
  41691. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  41692. const buffer = {}; // GPUBufferBindingLayout
  41693. if ( binding.isStorageBuffer ) {
  41694. buffer.type = binding.access;
  41695. }
  41696. bindingGPU.buffer = buffer;
  41697. } else if ( binding.isSampler ) {
  41698. const sampler = {}; // GPUSamplerBindingLayout
  41699. if ( binding.texture.isDepthTexture ) {
  41700. if ( binding.texture.compareFunction !== null ) {
  41701. sampler.type = 'comparison';
  41702. }
  41703. }
  41704. bindingGPU.sampler = sampler;
  41705. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  41706. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  41707. } else if ( binding.isSampledTexture && binding.store ) {
  41708. const format = this.backend.get( binding.texture ).texture.format;
  41709. const access = binding.access;
  41710. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  41711. } else if ( binding.isSampledTexture ) {
  41712. const texture = {}; // GPUTextureBindingLayout
  41713. if ( binding.texture.isDepthTexture ) {
  41714. texture.sampleType = GPUTextureSampleType.Depth;
  41715. } else if ( binding.texture.isDataTexture ) {
  41716. const type = binding.texture.type;
  41717. if ( type === IntType ) {
  41718. texture.sampleType = GPUTextureSampleType.SInt;
  41719. } else if ( type === UnsignedIntType ) {
  41720. texture.sampleType = GPUTextureSampleType.UInt;
  41721. } else if ( type === FloatType ) {
  41722. // @TODO: Add support for this soon: backend.hasFeature( 'float32-filterable' )
  41723. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  41724. }
  41725. }
  41726. if ( binding.isSampledCubeTexture ) {
  41727. texture.viewDimension = GPUTextureViewDimension.Cube;
  41728. } else if ( binding.texture.isDataArrayTexture ) {
  41729. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  41730. } else if ( binding.isSampledTexture3D ) {
  41731. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  41732. }
  41733. bindingGPU.texture = texture;
  41734. } else {
  41735. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  41736. }
  41737. entries.push( bindingGPU );
  41738. }
  41739. return device.createBindGroupLayout( { entries } );
  41740. }
  41741. createBindings( bindGroup ) {
  41742. const backend = this.backend;
  41743. const bindingsData = backend.get( bindGroup );
  41744. // setup (static) binding layout and (dynamic) binding group
  41745. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  41746. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  41747. bindingsData.layout = bindLayoutGPU;
  41748. bindingsData.group = bindGroupGPU;
  41749. }
  41750. updateBinding( binding ) {
  41751. const backend = this.backend;
  41752. const device = backend.device;
  41753. const buffer = binding.buffer;
  41754. const bufferGPU = backend.get( binding ).buffer;
  41755. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  41756. }
  41757. createBindGroup( bindGroup, layoutGPU ) {
  41758. const backend = this.backend;
  41759. const device = backend.device;
  41760. let bindingPoint = 0;
  41761. const entriesGPU = [];
  41762. for ( const binding of bindGroup.bindings ) {
  41763. if ( binding.isUniformBuffer ) {
  41764. const bindingData = backend.get( binding );
  41765. if ( bindingData.buffer === undefined ) {
  41766. const byteLength = binding.byteLength;
  41767. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  41768. const bufferGPU = device.createBuffer( {
  41769. label: 'bindingBuffer_' + binding.name,
  41770. size: byteLength,
  41771. usage: usage
  41772. } );
  41773. bindingData.buffer = bufferGPU;
  41774. }
  41775. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  41776. } else if ( binding.isStorageBuffer ) {
  41777. const bindingData = backend.get( binding );
  41778. if ( bindingData.buffer === undefined ) {
  41779. const attribute = binding.attribute;
  41780. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  41781. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  41782. bindingData.buffer = backend.get( attribute ).buffer;
  41783. }
  41784. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  41785. } else if ( binding.isSampler ) {
  41786. const textureGPU = backend.get( binding.texture );
  41787. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  41788. } else if ( binding.isSampledTexture ) {
  41789. const textureData = backend.get( binding.texture );
  41790. let dimensionViewGPU;
  41791. if ( binding.isSampledCubeTexture ) {
  41792. dimensionViewGPU = GPUTextureViewDimension.Cube;
  41793. } else if ( binding.isSampledTexture3D ) {
  41794. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  41795. } else if ( binding.texture.isDataArrayTexture ) {
  41796. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  41797. } else {
  41798. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  41799. }
  41800. let resourceGPU;
  41801. if ( textureData.externalTexture !== undefined ) {
  41802. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  41803. } else {
  41804. const aspectGPU = GPUTextureAspect.All;
  41805. resourceGPU = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount: binding.store ? 1 : textureData.mipLevelCount } );
  41806. }
  41807. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  41808. }
  41809. bindingPoint ++;
  41810. }
  41811. return device.createBindGroup( {
  41812. label: 'bindGroup_' + bindGroup.name,
  41813. layout: layoutGPU,
  41814. entries: entriesGPU
  41815. } );
  41816. }
  41817. }
  41818. class WebGPUPipelineUtils {
  41819. constructor( backend ) {
  41820. this.backend = backend;
  41821. }
  41822. _getSampleCount( renderObjectContext ) {
  41823. let sampleCount = this.backend.utils.getSampleCount( renderObjectContext );
  41824. if ( sampleCount > 1 ) {
  41825. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  41826. sampleCount = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  41827. if ( sampleCount === 2 ) {
  41828. sampleCount = 4;
  41829. }
  41830. }
  41831. return sampleCount;
  41832. }
  41833. createRenderPipeline( renderObject, promises ) {
  41834. const { object, material, geometry, pipeline } = renderObject;
  41835. const { vertexProgram, fragmentProgram } = pipeline;
  41836. const backend = this.backend;
  41837. const device = backend.device;
  41838. const utils = backend.utils;
  41839. const pipelineData = backend.get( pipeline );
  41840. // bind group layouts
  41841. const bindGroupLayouts = [];
  41842. for ( const bindGroup of renderObject.getBindings() ) {
  41843. const bindingsData = backend.get( bindGroup );
  41844. bindGroupLayouts.push( bindingsData.layout );
  41845. }
  41846. // vertex buffers
  41847. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  41848. // blending
  41849. let blending;
  41850. if ( material.transparent === true && material.blending !== NoBlending ) {
  41851. blending = this._getBlending( material );
  41852. }
  41853. // stencil
  41854. let stencilFront = {};
  41855. if ( material.stencilWrite === true ) {
  41856. stencilFront = {
  41857. compare: this._getStencilCompare( material ),
  41858. failOp: this._getStencilOperation( material.stencilFail ),
  41859. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  41860. passOp: this._getStencilOperation( material.stencilZPass )
  41861. };
  41862. }
  41863. const colorWriteMask = this._getColorWriteMask( material );
  41864. const targets = [];
  41865. if ( renderObject.context.textures !== null ) {
  41866. const textures = renderObject.context.textures;
  41867. for ( let i = 0; i < textures.length; i ++ ) {
  41868. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  41869. targets.push( {
  41870. format: colorFormat,
  41871. blend: blending,
  41872. writeMask: colorWriteMask
  41873. } );
  41874. }
  41875. } else {
  41876. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  41877. targets.push( {
  41878. format: colorFormat,
  41879. blend: blending,
  41880. writeMask: colorWriteMask
  41881. } );
  41882. }
  41883. const vertexModule = backend.get( vertexProgram ).module;
  41884. const fragmentModule = backend.get( fragmentProgram ).module;
  41885. const primitiveState = this._getPrimitiveState( object, geometry, material );
  41886. const depthCompare = this._getDepthCompare( material );
  41887. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  41888. const sampleCount = this._getSampleCount( renderObject.context );
  41889. const pipelineDescriptor = {
  41890. label: 'renderPipeline',
  41891. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  41892. fragment: Object.assign( {}, fragmentModule, { targets } ),
  41893. primitive: primitiveState,
  41894. depthStencil: {
  41895. format: depthStencilFormat,
  41896. depthWriteEnabled: material.depthWrite,
  41897. depthCompare: depthCompare,
  41898. stencilFront: stencilFront,
  41899. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  41900. stencilReadMask: material.stencilFuncMask,
  41901. stencilWriteMask: material.stencilWriteMask
  41902. },
  41903. multisample: {
  41904. count: sampleCount,
  41905. alphaToCoverageEnabled: material.alphaToCoverage
  41906. },
  41907. layout: device.createPipelineLayout( {
  41908. bindGroupLayouts
  41909. } )
  41910. };
  41911. if ( promises === null ) {
  41912. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  41913. } else {
  41914. const p = new Promise( ( resolve /*, reject*/ ) => {
  41915. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  41916. pipelineData.pipeline = pipeline;
  41917. resolve();
  41918. } );
  41919. } );
  41920. promises.push( p );
  41921. }
  41922. }
  41923. createBundleEncoder( renderContext, renderObject ) {
  41924. const backend = this.backend;
  41925. const { utils, device } = backend;
  41926. const renderContextData = backend.get( renderContext );
  41927. const renderObjectData = backend.get( renderObject );
  41928. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  41929. const colorFormat = utils.getCurrentColorFormat( renderContext );
  41930. const sampleCount = this._getSampleCount( renderObject.context );
  41931. const descriptor = {
  41932. label: 'renderBundleEncoder',
  41933. colorFormats: [ colorFormat ],
  41934. depthStencilFormat,
  41935. sampleCount
  41936. };
  41937. const bundleEncoder = device.createRenderBundleEncoder( descriptor );
  41938. renderObjectData.bundleEncoder = bundleEncoder;
  41939. renderContextData.currentSets = { attributes: {} };
  41940. renderContextData._renderBundleViewport = renderContext.width + '_' + renderContext.height;
  41941. return bundleEncoder;
  41942. }
  41943. createComputePipeline( pipeline, bindings ) {
  41944. const backend = this.backend;
  41945. const device = backend.device;
  41946. const computeProgram = backend.get( pipeline.computeProgram ).module;
  41947. const pipelineGPU = backend.get( pipeline );
  41948. // bind group layouts
  41949. const bindGroupLayouts = [];
  41950. for ( const bindingsGroup of bindings ) {
  41951. const bindingsData = backend.get( bindingsGroup );
  41952. bindGroupLayouts.push( bindingsData.layout );
  41953. }
  41954. pipelineGPU.pipeline = device.createComputePipeline( {
  41955. compute: computeProgram,
  41956. layout: device.createPipelineLayout( {
  41957. bindGroupLayouts
  41958. } )
  41959. } );
  41960. }
  41961. _getBlending( material ) {
  41962. let color, alpha;
  41963. const blending = material.blending;
  41964. const blendSrc = material.blendSrc;
  41965. const blendDst = material.blendDst;
  41966. const blendEquation = material.blendEquation;
  41967. if ( blending === CustomBlending ) {
  41968. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  41969. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  41970. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  41971. color = {
  41972. srcFactor: this._getBlendFactor( blendSrc ),
  41973. dstFactor: this._getBlendFactor( blendDst ),
  41974. operation: this._getBlendOperation( blendEquation )
  41975. };
  41976. alpha = {
  41977. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  41978. dstFactor: this._getBlendFactor( blendDstAlpha ),
  41979. operation: this._getBlendOperation( blendEquationAlpha )
  41980. };
  41981. } else {
  41982. const premultipliedAlpha = material.premultipliedAlpha;
  41983. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  41984. color = {
  41985. srcFactor: srcRGB,
  41986. dstFactor: dstRGB,
  41987. operation: GPUBlendOperation.Add
  41988. };
  41989. alpha = {
  41990. srcFactor: srcAlpha,
  41991. dstFactor: dstAlpha,
  41992. operation: GPUBlendOperation.Add
  41993. };
  41994. };
  41995. if ( premultipliedAlpha ) {
  41996. switch ( blending ) {
  41997. case NormalBlending:
  41998. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  41999. break;
  42000. case AdditiveBlending:
  42001. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  42002. break;
  42003. case SubtractiveBlending:
  42004. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42005. break;
  42006. case MultiplyBlending:
  42007. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  42008. break;
  42009. }
  42010. } else {
  42011. switch ( blending ) {
  42012. case NormalBlending:
  42013. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  42014. break;
  42015. case AdditiveBlending:
  42016. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  42017. break;
  42018. case SubtractiveBlending:
  42019. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42020. break;
  42021. case MultiplyBlending:
  42022. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  42023. break;
  42024. }
  42025. }
  42026. }
  42027. if ( color !== undefined && alpha !== undefined ) {
  42028. return { color, alpha };
  42029. } else {
  42030. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  42031. }
  42032. }
  42033. _getBlendFactor( blend ) {
  42034. let blendFactor;
  42035. switch ( blend ) {
  42036. case ZeroFactor:
  42037. blendFactor = GPUBlendFactor.Zero;
  42038. break;
  42039. case OneFactor:
  42040. blendFactor = GPUBlendFactor.One;
  42041. break;
  42042. case SrcColorFactor:
  42043. blendFactor = GPUBlendFactor.Src;
  42044. break;
  42045. case OneMinusSrcColorFactor:
  42046. blendFactor = GPUBlendFactor.OneMinusSrc;
  42047. break;
  42048. case SrcAlphaFactor:
  42049. blendFactor = GPUBlendFactor.SrcAlpha;
  42050. break;
  42051. case OneMinusSrcAlphaFactor:
  42052. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  42053. break;
  42054. case DstColorFactor:
  42055. blendFactor = GPUBlendFactor.Dst;
  42056. break;
  42057. case OneMinusDstColorFactor:
  42058. blendFactor = GPUBlendFactor.OneMinusDstColor;
  42059. break;
  42060. case DstAlphaFactor:
  42061. blendFactor = GPUBlendFactor.DstAlpha;
  42062. break;
  42063. case OneMinusDstAlphaFactor:
  42064. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  42065. break;
  42066. case SrcAlphaSaturateFactor:
  42067. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  42068. break;
  42069. case BlendColorFactor:
  42070. blendFactor = GPUBlendFactor.Constant;
  42071. break;
  42072. case OneMinusBlendColorFactor:
  42073. blendFactor = GPUBlendFactor.OneMinusConstant;
  42074. break;
  42075. default:
  42076. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  42077. }
  42078. return blendFactor;
  42079. }
  42080. _getStencilCompare( material ) {
  42081. let stencilCompare;
  42082. const stencilFunc = material.stencilFunc;
  42083. switch ( stencilFunc ) {
  42084. case NeverStencilFunc:
  42085. stencilCompare = GPUCompareFunction.Never;
  42086. break;
  42087. case AlwaysStencilFunc:
  42088. stencilCompare = GPUCompareFunction.Always;
  42089. break;
  42090. case LessStencilFunc:
  42091. stencilCompare = GPUCompareFunction.Less;
  42092. break;
  42093. case LessEqualStencilFunc:
  42094. stencilCompare = GPUCompareFunction.LessEqual;
  42095. break;
  42096. case EqualStencilFunc:
  42097. stencilCompare = GPUCompareFunction.Equal;
  42098. break;
  42099. case GreaterEqualStencilFunc:
  42100. stencilCompare = GPUCompareFunction.GreaterEqual;
  42101. break;
  42102. case GreaterStencilFunc:
  42103. stencilCompare = GPUCompareFunction.Greater;
  42104. break;
  42105. case NotEqualStencilFunc:
  42106. stencilCompare = GPUCompareFunction.NotEqual;
  42107. break;
  42108. default:
  42109. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  42110. }
  42111. return stencilCompare;
  42112. }
  42113. _getStencilOperation( op ) {
  42114. let stencilOperation;
  42115. switch ( op ) {
  42116. case KeepStencilOp:
  42117. stencilOperation = GPUStencilOperation.Keep;
  42118. break;
  42119. case ZeroStencilOp:
  42120. stencilOperation = GPUStencilOperation.Zero;
  42121. break;
  42122. case ReplaceStencilOp:
  42123. stencilOperation = GPUStencilOperation.Replace;
  42124. break;
  42125. case InvertStencilOp:
  42126. stencilOperation = GPUStencilOperation.Invert;
  42127. break;
  42128. case IncrementStencilOp:
  42129. stencilOperation = GPUStencilOperation.IncrementClamp;
  42130. break;
  42131. case DecrementStencilOp:
  42132. stencilOperation = GPUStencilOperation.DecrementClamp;
  42133. break;
  42134. case IncrementWrapStencilOp:
  42135. stencilOperation = GPUStencilOperation.IncrementWrap;
  42136. break;
  42137. case DecrementWrapStencilOp:
  42138. stencilOperation = GPUStencilOperation.DecrementWrap;
  42139. break;
  42140. default:
  42141. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  42142. }
  42143. return stencilOperation;
  42144. }
  42145. _getBlendOperation( blendEquation ) {
  42146. let blendOperation;
  42147. switch ( blendEquation ) {
  42148. case AddEquation:
  42149. blendOperation = GPUBlendOperation.Add;
  42150. break;
  42151. case SubtractEquation:
  42152. blendOperation = GPUBlendOperation.Subtract;
  42153. break;
  42154. case ReverseSubtractEquation:
  42155. blendOperation = GPUBlendOperation.ReverseSubtract;
  42156. break;
  42157. case MinEquation:
  42158. blendOperation = GPUBlendOperation.Min;
  42159. break;
  42160. case MaxEquation:
  42161. blendOperation = GPUBlendOperation.Max;
  42162. break;
  42163. default:
  42164. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  42165. }
  42166. return blendOperation;
  42167. }
  42168. _getPrimitiveState( object, geometry, material ) {
  42169. const descriptor = {};
  42170. const utils = this.backend.utils;
  42171. descriptor.topology = utils.getPrimitiveTopology( object, material );
  42172. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  42173. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42174. }
  42175. switch ( material.side ) {
  42176. case FrontSide:
  42177. descriptor.frontFace = GPUFrontFace.CCW;
  42178. descriptor.cullMode = GPUCullMode.Back;
  42179. break;
  42180. case BackSide:
  42181. descriptor.frontFace = GPUFrontFace.CCW;
  42182. descriptor.cullMode = GPUCullMode.Front;
  42183. break;
  42184. case DoubleSide:
  42185. descriptor.frontFace = GPUFrontFace.CCW;
  42186. descriptor.cullMode = GPUCullMode.None;
  42187. break;
  42188. default:
  42189. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  42190. break;
  42191. }
  42192. return descriptor;
  42193. }
  42194. _getColorWriteMask( material ) {
  42195. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  42196. }
  42197. _getDepthCompare( material ) {
  42198. let depthCompare;
  42199. if ( material.depthTest === false ) {
  42200. depthCompare = GPUCompareFunction.Always;
  42201. } else {
  42202. const depthFunc = material.depthFunc;
  42203. switch ( depthFunc ) {
  42204. case NeverDepth:
  42205. depthCompare = GPUCompareFunction.Never;
  42206. break;
  42207. case AlwaysDepth:
  42208. depthCompare = GPUCompareFunction.Always;
  42209. break;
  42210. case LessDepth:
  42211. depthCompare = GPUCompareFunction.Less;
  42212. break;
  42213. case LessEqualDepth:
  42214. depthCompare = GPUCompareFunction.LessEqual;
  42215. break;
  42216. case EqualDepth:
  42217. depthCompare = GPUCompareFunction.Equal;
  42218. break;
  42219. case GreaterEqualDepth:
  42220. depthCompare = GPUCompareFunction.GreaterEqual;
  42221. break;
  42222. case GreaterDepth:
  42223. depthCompare = GPUCompareFunction.Greater;
  42224. break;
  42225. case NotEqualDepth:
  42226. depthCompare = GPUCompareFunction.NotEqual;
  42227. break;
  42228. default:
  42229. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  42230. }
  42231. }
  42232. return depthCompare;
  42233. }
  42234. }
  42235. /*// debugger tools
  42236. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  42237. //*/
  42238. //
  42239. class WebGPUBackend extends Backend {
  42240. constructor( parameters = {} ) {
  42241. super( parameters );
  42242. this.isWebGPUBackend = true;
  42243. // some parameters require default values other than "undefined"
  42244. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  42245. this.parameters.antialias = ( parameters.antialias === true );
  42246. if ( this.parameters.antialias === true ) {
  42247. this.parameters.sampleCount = ( parameters.sampleCount === undefined ) ? 4 : parameters.sampleCount;
  42248. } else {
  42249. this.parameters.sampleCount = 1;
  42250. }
  42251. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  42252. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42253. this.device = null;
  42254. this.context = null;
  42255. this.colorBuffer = null;
  42256. this.defaultRenderPassdescriptor = null;
  42257. this.utils = new WebGPUUtils( this );
  42258. this.attributeUtils = new WebGPUAttributeUtils( this );
  42259. this.bindingUtils = new WebGPUBindingUtils( this );
  42260. this.pipelineUtils = new WebGPUPipelineUtils( this );
  42261. this.textureUtils = new WebGPUTextureUtils( this );
  42262. this.occludedResolveCache = new Map();
  42263. }
  42264. async init( renderer ) {
  42265. await super.init( renderer );
  42266. //
  42267. const parameters = this.parameters;
  42268. // create the device if it is not passed with parameters
  42269. let device;
  42270. if ( parameters.device === undefined ) {
  42271. const adapterOptions = {
  42272. powerPreference: parameters.powerPreference
  42273. };
  42274. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  42275. if ( adapter === null ) {
  42276. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  42277. }
  42278. // feature support
  42279. const features = Object.values( GPUFeatureName );
  42280. const supportedFeatures = [];
  42281. for ( const name of features ) {
  42282. if ( adapter.features.has( name ) ) {
  42283. supportedFeatures.push( name );
  42284. }
  42285. }
  42286. const deviceDescriptor = {
  42287. requiredFeatures: supportedFeatures,
  42288. requiredLimits: parameters.requiredLimits
  42289. };
  42290. device = await adapter.requestDevice( deviceDescriptor );
  42291. } else {
  42292. device = parameters.device;
  42293. }
  42294. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  42295. this.device = device;
  42296. this.context = context;
  42297. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  42298. this.context.configure( {
  42299. device: this.device,
  42300. format: GPUTextureFormat.BGRA8Unorm,
  42301. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  42302. alphaMode: alphaMode
  42303. } );
  42304. this.updateSize();
  42305. }
  42306. get coordinateSystem() {
  42307. return WebGPUCoordinateSystem;
  42308. }
  42309. async getArrayBufferAsync( attribute ) {
  42310. return await this.attributeUtils.getArrayBufferAsync( attribute );
  42311. }
  42312. getContext() {
  42313. return this.context;
  42314. }
  42315. _getDefaultRenderPassDescriptor() {
  42316. let descriptor = this.defaultRenderPassdescriptor;
  42317. const antialias = this.parameters.antialias;
  42318. if ( descriptor === null ) {
  42319. const renderer = this.renderer;
  42320. descriptor = {
  42321. colorAttachments: [ {
  42322. view: null
  42323. } ],
  42324. depthStencilAttachment: {
  42325. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  42326. }
  42327. };
  42328. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42329. if ( antialias === true ) {
  42330. colorAttachment.view = this.colorBuffer.createView();
  42331. } else {
  42332. colorAttachment.resolveTarget = undefined;
  42333. }
  42334. this.defaultRenderPassdescriptor = descriptor;
  42335. }
  42336. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42337. if ( antialias === true ) {
  42338. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  42339. } else {
  42340. colorAttachment.view = this.context.getCurrentTexture().createView();
  42341. }
  42342. return descriptor;
  42343. }
  42344. _getRenderPassDescriptor( renderContext ) {
  42345. const renderTarget = renderContext.renderTarget;
  42346. const renderTargetData = this.get( renderTarget );
  42347. let descriptors = renderTargetData.descriptors;
  42348. if ( descriptors === undefined ) {
  42349. descriptors = [];
  42350. renderTargetData.descriptors = descriptors;
  42351. }
  42352. if ( renderTargetData.width !== renderTarget.width ||
  42353. renderTargetData.height !== renderTarget.height ||
  42354. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  42355. renderTargetData.samples !== renderTarget.samples
  42356. ) {
  42357. descriptors.length = 0;
  42358. }
  42359. let descriptor = descriptors[ renderContext.activeCubeFace ];
  42360. if ( descriptor === undefined ) {
  42361. const textures = renderContext.textures;
  42362. const colorAttachments = [];
  42363. for ( let i = 0; i < textures.length; i ++ ) {
  42364. const textureData = this.get( textures[ i ] );
  42365. const textureView = textureData.texture.createView( {
  42366. baseMipLevel: renderContext.activeMipmapLevel,
  42367. mipLevelCount: 1,
  42368. baseArrayLayer: renderContext.activeCubeFace,
  42369. dimension: GPUTextureViewDimension.TwoD
  42370. } );
  42371. let view, resolveTarget;
  42372. if ( textureData.msaaTexture !== undefined ) {
  42373. view = textureData.msaaTexture.createView();
  42374. resolveTarget = textureView;
  42375. } else {
  42376. view = textureView;
  42377. resolveTarget = undefined;
  42378. }
  42379. colorAttachments.push( {
  42380. view,
  42381. resolveTarget,
  42382. loadOp: GPULoadOp.Load,
  42383. storeOp: GPUStoreOp.Store
  42384. } );
  42385. }
  42386. const depthTextureData = this.get( renderContext.depthTexture );
  42387. const depthStencilAttachment = {
  42388. view: depthTextureData.texture.createView(),
  42389. };
  42390. descriptor = {
  42391. colorAttachments,
  42392. depthStencilAttachment
  42393. };
  42394. descriptors[ renderContext.activeCubeFace ] = descriptor;
  42395. renderTargetData.width = renderTarget.width;
  42396. renderTargetData.height = renderTarget.height;
  42397. renderTargetData.samples = renderTarget.samples;
  42398. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  42399. }
  42400. return descriptor;
  42401. }
  42402. beginRender( renderContext ) {
  42403. const renderContextData = this.get( renderContext );
  42404. const device = this.device;
  42405. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42406. let occlusionQuerySet;
  42407. if ( occlusionQueryCount > 0 ) {
  42408. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  42409. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  42410. // Get a reference to the array of objects with queries. The renderContextData property
  42411. // can be changed by another render pass before the buffer.mapAsyc() completes.
  42412. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  42413. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  42414. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42415. //
  42416. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  42417. renderContextData.occlusionQuerySet = occlusionQuerySet;
  42418. renderContextData.occlusionQueryIndex = 0;
  42419. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42420. renderContextData.lastOcclusionObject = null;
  42421. }
  42422. let descriptor;
  42423. if ( renderContext.textures === null ) {
  42424. descriptor = this._getDefaultRenderPassDescriptor();
  42425. } else {
  42426. descriptor = this._getRenderPassDescriptor( renderContext );
  42427. }
  42428. this.initTimestampQuery( renderContext, descriptor );
  42429. descriptor.occlusionQuerySet = occlusionQuerySet;
  42430. const depthStencilAttachment = descriptor.depthStencilAttachment;
  42431. if ( renderContext.textures !== null ) {
  42432. const colorAttachments = descriptor.colorAttachments;
  42433. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  42434. const colorAttachment = colorAttachments[ i ];
  42435. if ( renderContext.clearColor ) {
  42436. colorAttachment.clearValue = renderContext.clearColorValue;
  42437. colorAttachment.loadOp = GPULoadOp.Clear;
  42438. colorAttachment.storeOp = GPUStoreOp.Store;
  42439. } else {
  42440. colorAttachment.loadOp = GPULoadOp.Load;
  42441. colorAttachment.storeOp = GPUStoreOp.Store;
  42442. }
  42443. }
  42444. } else {
  42445. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42446. if ( renderContext.clearColor ) {
  42447. colorAttachment.clearValue = renderContext.clearColorValue;
  42448. colorAttachment.loadOp = GPULoadOp.Clear;
  42449. colorAttachment.storeOp = GPUStoreOp.Store;
  42450. } else {
  42451. colorAttachment.loadOp = GPULoadOp.Load;
  42452. colorAttachment.storeOp = GPUStoreOp.Store;
  42453. }
  42454. }
  42455. //
  42456. if ( renderContext.depth ) {
  42457. if ( renderContext.clearDepth ) {
  42458. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  42459. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42460. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42461. } else {
  42462. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42463. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42464. }
  42465. }
  42466. if ( renderContext.stencil ) {
  42467. if ( renderContext.clearStencil ) {
  42468. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  42469. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42470. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42471. } else {
  42472. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42473. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42474. }
  42475. }
  42476. //
  42477. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  42478. const currentPass = encoder.beginRenderPass( descriptor );
  42479. //
  42480. renderContextData.descriptor = descriptor;
  42481. renderContextData.encoder = encoder;
  42482. renderContextData.currentPass = currentPass;
  42483. renderContextData.currentSets = { attributes: {} };
  42484. //
  42485. if ( renderContext.viewport ) {
  42486. this.updateViewport( renderContext );
  42487. }
  42488. if ( renderContext.scissor ) {
  42489. const { x, y, width, height } = renderContext.scissorValue;
  42490. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  42491. }
  42492. }
  42493. finishRender( renderContext ) {
  42494. const renderContextData = this.get( renderContext );
  42495. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42496. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  42497. renderContextData.registerBundlesPhase = false;
  42498. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  42499. }
  42500. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  42501. renderContextData.currentPass.endOcclusionQuery();
  42502. }
  42503. renderContextData.currentPass.end();
  42504. if ( occlusionQueryCount > 0 ) {
  42505. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  42506. //
  42507. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  42508. if ( queryResolveBuffer === undefined ) {
  42509. queryResolveBuffer = this.device.createBuffer(
  42510. {
  42511. size: bufferSize,
  42512. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  42513. }
  42514. );
  42515. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  42516. }
  42517. //
  42518. const readBuffer = this.device.createBuffer(
  42519. {
  42520. size: bufferSize,
  42521. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42522. }
  42523. );
  42524. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  42525. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  42526. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  42527. renderContextData.occlusionQueryBuffer = readBuffer;
  42528. //
  42529. this.resolveOccludedAsync( renderContext );
  42530. }
  42531. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  42532. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  42533. //
  42534. if ( renderContext.textures !== null ) {
  42535. const textures = renderContext.textures;
  42536. for ( let i = 0; i < textures.length; i ++ ) {
  42537. const texture = textures[ i ];
  42538. if ( texture.generateMipmaps === true ) {
  42539. this.textureUtils.generateMipmaps( texture );
  42540. }
  42541. }
  42542. }
  42543. }
  42544. isOccluded( renderContext, object ) {
  42545. const renderContextData = this.get( renderContext );
  42546. return renderContextData.occluded && renderContextData.occluded.has( object );
  42547. }
  42548. async resolveOccludedAsync( renderContext ) {
  42549. const renderContextData = this.get( renderContext );
  42550. // handle occlusion query results
  42551. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  42552. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  42553. const occluded = new WeakSet();
  42554. renderContextData.currentOcclusionQueryObjects = null;
  42555. renderContextData.currentOcclusionQueryBuffer = null;
  42556. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  42557. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  42558. const results = new BigUint64Array( buffer );
  42559. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  42560. if ( results[ i ] !== BigInt( 0 ) ) {
  42561. occluded.add( currentOcclusionQueryObjects[ i ] );
  42562. }
  42563. }
  42564. currentOcclusionQueryBuffer.destroy();
  42565. renderContextData.occluded = occluded;
  42566. }
  42567. }
  42568. updateViewport( renderContext ) {
  42569. const { currentPass } = this.get( renderContext );
  42570. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  42571. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  42572. }
  42573. clear( color, depth, stencil, renderTargetData = null ) {
  42574. const device = this.device;
  42575. const renderer = this.renderer;
  42576. let colorAttachments = [];
  42577. let depthStencilAttachment;
  42578. let clearValue;
  42579. let supportsDepth;
  42580. let supportsStencil;
  42581. if ( color ) {
  42582. const clearColor = this.getClearColor();
  42583. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  42584. }
  42585. if ( renderTargetData === null ) {
  42586. supportsDepth = renderer.depth;
  42587. supportsStencil = renderer.stencil;
  42588. const descriptor = this._getDefaultRenderPassDescriptor();
  42589. if ( color ) {
  42590. colorAttachments = descriptor.colorAttachments;
  42591. const colorAttachment = colorAttachments[ 0 ];
  42592. colorAttachment.clearValue = clearValue;
  42593. colorAttachment.loadOp = GPULoadOp.Clear;
  42594. colorAttachment.storeOp = GPUStoreOp.Store;
  42595. }
  42596. if ( supportsDepth || supportsStencil ) {
  42597. depthStencilAttachment = descriptor.depthStencilAttachment;
  42598. }
  42599. } else {
  42600. supportsDepth = renderTargetData.depth;
  42601. supportsStencil = renderTargetData.stencil;
  42602. if ( color ) {
  42603. for ( const texture of renderTargetData.textures ) {
  42604. const textureData = this.get( texture );
  42605. const textureView = textureData.texture.createView();
  42606. let view, resolveTarget;
  42607. if ( textureData.msaaTexture !== undefined ) {
  42608. view = textureData.msaaTexture.createView();
  42609. resolveTarget = textureView;
  42610. } else {
  42611. view = textureView;
  42612. resolveTarget = undefined;
  42613. }
  42614. colorAttachments.push( {
  42615. view,
  42616. resolveTarget,
  42617. clearValue,
  42618. loadOp: GPULoadOp.Clear,
  42619. storeOp: GPUStoreOp.Store
  42620. } );
  42621. }
  42622. }
  42623. if ( supportsDepth || supportsStencil ) {
  42624. const depthTextureData = this.get( renderTargetData.depthTexture );
  42625. depthStencilAttachment = {
  42626. view: depthTextureData.texture.createView()
  42627. };
  42628. }
  42629. }
  42630. //
  42631. if ( supportsDepth ) {
  42632. if ( depth ) {
  42633. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42634. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  42635. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42636. } else {
  42637. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42638. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42639. }
  42640. }
  42641. //
  42642. if ( supportsStencil ) {
  42643. if ( stencil ) {
  42644. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42645. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  42646. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42647. } else {
  42648. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42649. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42650. }
  42651. }
  42652. //
  42653. const encoder = device.createCommandEncoder( {} );
  42654. const currentPass = encoder.beginRenderPass( {
  42655. colorAttachments,
  42656. depthStencilAttachment
  42657. } );
  42658. currentPass.end();
  42659. device.queue.submit( [ encoder.finish() ] );
  42660. }
  42661. // compute
  42662. beginCompute( computeGroup ) {
  42663. const groupGPU = this.get( computeGroup );
  42664. const descriptor = {};
  42665. this.initTimestampQuery( computeGroup, descriptor );
  42666. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  42667. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  42668. }
  42669. compute( computeGroup, computeNode, bindings, pipeline ) {
  42670. const { passEncoderGPU } = this.get( computeGroup );
  42671. // pipeline
  42672. const pipelineGPU = this.get( pipeline ).pipeline;
  42673. passEncoderGPU.setPipeline( pipelineGPU );
  42674. // bind groups
  42675. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42676. const bindGroup = bindings[ i ];
  42677. const bindingsData = this.get( bindGroup );
  42678. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42679. }
  42680. passEncoderGPU.dispatchWorkgroups( computeNode.dispatchCount );
  42681. }
  42682. finishCompute( computeGroup ) {
  42683. const groupData = this.get( computeGroup );
  42684. groupData.passEncoderGPU.end();
  42685. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  42686. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  42687. }
  42688. // render object
  42689. draw( renderObject, info ) {
  42690. const { object, geometry, context, pipeline } = renderObject;
  42691. const bindings = renderObject.getBindings();
  42692. const contextData = this.get( context );
  42693. const pipelineGPU = this.get( pipeline ).pipeline;
  42694. const currentSets = contextData.currentSets;
  42695. const renderObjectData = this.get( renderObject );
  42696. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  42697. const renderContextData = this.get( context );
  42698. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  42699. renderContextData.renderBundles.push( renderBundle );
  42700. return;
  42701. }
  42702. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  42703. // pipeline
  42704. if ( currentSets.pipeline !== pipelineGPU ) {
  42705. passEncoderGPU.setPipeline( pipelineGPU );
  42706. currentSets.pipeline = pipelineGPU;
  42707. }
  42708. // bind groups
  42709. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42710. const bindGroup = bindings[ i ];
  42711. const bindingsData = this.get( bindGroup );
  42712. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42713. }
  42714. // attributes
  42715. const index = renderObject.getIndex();
  42716. const hasIndex = ( index !== null );
  42717. // index
  42718. if ( hasIndex === true ) {
  42719. if ( currentSets.index !== index ) {
  42720. const buffer = this.get( index ).buffer;
  42721. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42722. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  42723. currentSets.index = index;
  42724. }
  42725. }
  42726. // vertex buffers
  42727. const vertexBuffers = renderObject.getVertexBuffers();
  42728. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  42729. const vertexBuffer = vertexBuffers[ i ];
  42730. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  42731. const buffer = this.get( vertexBuffer ).buffer;
  42732. passEncoderGPU.setVertexBuffer( i, buffer );
  42733. currentSets.attributes[ i ] = vertexBuffer;
  42734. }
  42735. }
  42736. // occlusion queries - handle multiple consecutive draw calls for an object
  42737. if ( contextData.occlusionQuerySet !== undefined ) {
  42738. const lastObject = contextData.lastOcclusionObject;
  42739. if ( lastObject !== object ) {
  42740. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42741. passEncoderGPU.endOcclusionQuery();
  42742. contextData.occlusionQueryIndex ++;
  42743. }
  42744. if ( object.occlusionTest === true ) {
  42745. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  42746. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42747. }
  42748. contextData.lastOcclusionObject = object;
  42749. }
  42750. }
  42751. // draw
  42752. const drawRange = renderObject.drawRange;
  42753. const firstVertex = drawRange.start;
  42754. const instanceCount = this.getInstanceCount( renderObject );
  42755. if ( instanceCount === 0 ) return;
  42756. if ( object.isBatchedMesh === true ) {
  42757. const starts = object._multiDrawStarts;
  42758. const counts = object._multiDrawCounts;
  42759. const drawCount = object._multiDrawCount;
  42760. const drawInstances = object._multiDrawInstances;
  42761. const bytesPerElement = index.bytesPerElement || 1;
  42762. for ( let i = 0; i < drawCount; i ++ ) {
  42763. const count = drawInstances ? drawInstances[ i ] : 1;
  42764. const firstInstance = count > 1 ? 0 : i;
  42765. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, count, starts[ i ] / 4, 0, firstInstance );
  42766. }
  42767. } else if ( hasIndex === true ) {
  42768. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  42769. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  42770. info.update( object, indexCount, instanceCount );
  42771. } else {
  42772. const positionAttribute = geometry.attributes.position;
  42773. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  42774. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  42775. info.update( object, vertexCount, instanceCount );
  42776. }
  42777. if ( this.renderer._currentRenderBundle ) {
  42778. const renderBundle = passEncoderGPU.finish();
  42779. renderObjectData.lastPipelineGPU = pipelineGPU;
  42780. renderObjectData.renderBundle = renderBundle;
  42781. renderObjectData.bundleEncoder = passEncoderGPU;
  42782. }
  42783. }
  42784. // cache key
  42785. needsRenderUpdate( renderObject ) {
  42786. const data = this.get( renderObject );
  42787. const { object, material } = renderObject;
  42788. const utils = this.utils;
  42789. const sampleCount = utils.getSampleCount( renderObject.context );
  42790. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  42791. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  42792. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  42793. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  42794. let needsUpdate = false;
  42795. if ( data.material !== material || data.materialVersion !== material.version ||
  42796. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  42797. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  42798. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  42799. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  42800. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  42801. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  42802. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  42803. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  42804. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  42805. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  42806. data.primitiveTopology !== primitiveTopology ||
  42807. data.clippingContextVersion !== renderObject.clippingContextVersion
  42808. ) {
  42809. data.material = material; data.materialVersion = material.version;
  42810. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  42811. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  42812. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  42813. data.colorWrite = material.colorWrite;
  42814. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  42815. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  42816. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  42817. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  42818. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  42819. data.sampleCount = sampleCount;
  42820. data.colorSpace = colorSpace;
  42821. data.colorFormat = colorFormat;
  42822. data.depthStencilFormat = depthStencilFormat;
  42823. data.primitiveTopology = primitiveTopology;
  42824. data.clippingContextVersion = renderObject.clippingContextVersion;
  42825. needsUpdate = true;
  42826. }
  42827. return needsUpdate;
  42828. }
  42829. getRenderCacheKey( renderObject ) {
  42830. const { object, material } = renderObject;
  42831. const utils = this.utils;
  42832. const renderContext = renderObject.context;
  42833. return [
  42834. material.transparent, material.blending, material.premultipliedAlpha,
  42835. material.blendSrc, material.blendDst, material.blendEquation,
  42836. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  42837. material.colorWrite,
  42838. material.depthWrite, material.depthTest, material.depthFunc,
  42839. material.stencilWrite, material.stencilFunc,
  42840. material.stencilFail, material.stencilZFail, material.stencilZPass,
  42841. material.stencilFuncMask, material.stencilWriteMask,
  42842. material.side,
  42843. utils.getSampleCount( renderContext ),
  42844. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  42845. utils.getPrimitiveTopology( object, material ),
  42846. renderObject.clippingContextVersion
  42847. ].join();
  42848. }
  42849. // textures
  42850. createSampler( texture ) {
  42851. this.textureUtils.createSampler( texture );
  42852. }
  42853. destroySampler( texture ) {
  42854. this.textureUtils.destroySampler( texture );
  42855. }
  42856. createDefaultTexture( texture ) {
  42857. this.textureUtils.createDefaultTexture( texture );
  42858. }
  42859. createTexture( texture, options ) {
  42860. this.textureUtils.createTexture( texture, options );
  42861. }
  42862. updateTexture( texture, options ) {
  42863. this.textureUtils.updateTexture( texture, options );
  42864. }
  42865. generateMipmaps( texture ) {
  42866. this.textureUtils.generateMipmaps( texture );
  42867. }
  42868. destroyTexture( texture ) {
  42869. this.textureUtils.destroyTexture( texture );
  42870. }
  42871. copyTextureToBuffer( texture, x, y, width, height ) {
  42872. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  42873. }
  42874. initTimestampQuery( renderContext, descriptor ) {
  42875. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42876. const renderContextData = this.get( renderContext );
  42877. if ( ! renderContextData.timeStampQuerySet ) {
  42878. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  42879. // beginning and one for the end of compute pass execution.
  42880. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  42881. const timestampWrites = {
  42882. querySet: timeStampQuerySet,
  42883. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  42884. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  42885. };
  42886. Object.assign( descriptor, {
  42887. timestampWrites,
  42888. } );
  42889. renderContextData.timeStampQuerySet = timeStampQuerySet;
  42890. }
  42891. }
  42892. // timestamp utils
  42893. prepareTimestampBuffer( renderContext, encoder ) {
  42894. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42895. const renderContextData = this.get( renderContext );
  42896. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  42897. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  42898. renderContextData.currentTimestampQueryBuffers = {
  42899. resolveBuffer: this.device.createBuffer( {
  42900. label: 'timestamp resolve buffer',
  42901. size: size,
  42902. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  42903. } ),
  42904. resultBuffer: this.device.createBuffer( {
  42905. label: 'timestamp result buffer',
  42906. size: size,
  42907. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  42908. } ),
  42909. isMappingPending: false,
  42910. };
  42911. }
  42912. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  42913. if ( isMappingPending === true ) return;
  42914. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  42915. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  42916. }
  42917. async resolveTimestampAsync( renderContext, type = 'render' ) {
  42918. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42919. const renderContextData = this.get( renderContext );
  42920. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  42921. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  42922. if ( isMappingPending === true ) return;
  42923. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  42924. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  42925. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  42926. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  42927. this.renderer.info.updateTimestamp( type, duration );
  42928. resultBuffer.unmap();
  42929. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  42930. } );
  42931. }
  42932. // node builder
  42933. createNodeBuilder( object, renderer ) {
  42934. return new WGSLNodeBuilder( object, renderer );
  42935. }
  42936. // program
  42937. createProgram( program ) {
  42938. const programGPU = this.get( program );
  42939. programGPU.module = {
  42940. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  42941. entryPoint: 'main'
  42942. };
  42943. }
  42944. destroyProgram( program ) {
  42945. this.delete( program );
  42946. }
  42947. // pipelines
  42948. createRenderPipeline( renderObject, promises ) {
  42949. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  42950. }
  42951. createComputePipeline( computePipeline, bindings ) {
  42952. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  42953. }
  42954. createBundleEncoder( renderContext, renderObject ) {
  42955. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  42956. }
  42957. // bindings
  42958. createBindings( bindGroup ) {
  42959. this.bindingUtils.createBindings( bindGroup );
  42960. }
  42961. updateBindings( bindGroup ) {
  42962. this.bindingUtils.createBindings( bindGroup );
  42963. }
  42964. updateBinding( binding ) {
  42965. this.bindingUtils.updateBinding( binding );
  42966. }
  42967. // attributes
  42968. createIndexAttribute( attribute ) {
  42969. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  42970. }
  42971. createAttribute( attribute ) {
  42972. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  42973. }
  42974. createStorageAttribute( attribute ) {
  42975. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  42976. }
  42977. updateAttribute( attribute ) {
  42978. this.attributeUtils.updateAttribute( attribute );
  42979. }
  42980. destroyAttribute( attribute ) {
  42981. this.attributeUtils.destroyAttribute( attribute );
  42982. }
  42983. // canvas
  42984. updateSize() {
  42985. this.colorBuffer = this.textureUtils.getColorBuffer();
  42986. this.defaultRenderPassdescriptor = null;
  42987. }
  42988. // utils public
  42989. getMaxAnisotropy() {
  42990. return 16;
  42991. }
  42992. hasFeature( name ) {
  42993. return this.device.features.has( name );
  42994. }
  42995. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  42996. let dstX = 0;
  42997. let dstY = 0;
  42998. let srcX = 0;
  42999. let srcY = 0;
  43000. let srcWidth = srcTexture.image.width;
  43001. let srcHeight = srcTexture.image.height;
  43002. if ( srcRegion !== null ) {
  43003. srcX = srcRegion.x;
  43004. srcY = srcRegion.y;
  43005. srcWidth = srcRegion.width;
  43006. srcHeight = srcRegion.height;
  43007. }
  43008. if ( dstPosition !== null ) {
  43009. dstX = dstPosition.x;
  43010. dstY = dstPosition.y;
  43011. }
  43012. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  43013. const sourceGPU = this.get( srcTexture ).texture;
  43014. const destinationGPU = this.get( dstTexture ).texture;
  43015. encoder.copyTextureToTexture(
  43016. {
  43017. texture: sourceGPU,
  43018. mipLevel: level,
  43019. origin: { x: srcX, y: srcY, z: 0 }
  43020. },
  43021. {
  43022. texture: destinationGPU,
  43023. mipLevel: level,
  43024. origin: { x: dstX, y: dstY, z: 0 }
  43025. },
  43026. [
  43027. srcWidth,
  43028. srcHeight
  43029. ]
  43030. );
  43031. this.device.queue.submit( [ encoder.finish() ] );
  43032. }
  43033. copyFramebufferToTexture( texture, renderContext ) {
  43034. const renderContextData = this.get( renderContext );
  43035. const { encoder, descriptor } = renderContextData;
  43036. let sourceGPU = null;
  43037. if ( renderContext.renderTarget ) {
  43038. if ( texture.isDepthTexture ) {
  43039. sourceGPU = this.get( renderContext.depthTexture ).texture;
  43040. } else {
  43041. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  43042. }
  43043. } else {
  43044. if ( texture.isDepthTexture ) {
  43045. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  43046. } else {
  43047. sourceGPU = this.context.getCurrentTexture();
  43048. }
  43049. }
  43050. const destinationGPU = this.get( texture ).texture;
  43051. if ( sourceGPU.format !== destinationGPU.format ) {
  43052. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  43053. return;
  43054. }
  43055. renderContextData.currentPass.end();
  43056. encoder.copyTextureToTexture(
  43057. {
  43058. texture: sourceGPU,
  43059. origin: { x: 0, y: 0, z: 0 }
  43060. },
  43061. {
  43062. texture: destinationGPU
  43063. },
  43064. [
  43065. texture.image.width,
  43066. texture.image.height
  43067. ]
  43068. );
  43069. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  43070. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  43071. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43072. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43073. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  43074. renderContextData.currentSets = { attributes: {} };
  43075. }
  43076. }
  43077. /*
  43078. const debugHandler = {
  43079. get: function ( target, name ) {
  43080. // Add |update
  43081. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  43082. return target[ name ];
  43083. }
  43084. };
  43085. */
  43086. class WebGPURenderer extends Renderer {
  43087. constructor( parameters = {} ) {
  43088. let BackendClass;
  43089. if ( parameters.forceWebGL ) {
  43090. BackendClass = WebGLBackend;
  43091. } else if ( WebGPU.isAvailable() ) {
  43092. BackendClass = WebGPUBackend;
  43093. } else {
  43094. BackendClass = WebGLBackend;
  43095. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  43096. }
  43097. const backend = new BackendClass( parameters );
  43098. //super( new Proxy( backend, debugHandler ) );
  43099. super( backend, parameters );
  43100. this.isWebGPURenderer = true;
  43101. }
  43102. }
  43103. const quadMesh = new QuadMesh( new NodeMaterial() );
  43104. class PostProcessing {
  43105. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  43106. this.renderer = renderer;
  43107. this.outputNode = outputNode;
  43108. this.outputColorTransform = true;
  43109. this.needsUpdate = true;
  43110. }
  43111. render() {
  43112. this.update();
  43113. const renderer = this.renderer;
  43114. const toneMapping = renderer.toneMapping;
  43115. const outputColorSpace = renderer.outputColorSpace;
  43116. renderer.toneMapping = NoToneMapping;
  43117. renderer.outputColorSpace = LinearSRGBColorSpace;
  43118. //
  43119. quadMesh.render( this.renderer );
  43120. //
  43121. renderer.toneMapping = toneMapping;
  43122. renderer.outputColorSpace = outputColorSpace;
  43123. }
  43124. update() {
  43125. if ( this.needsUpdate === true ) {
  43126. const renderer = this.renderer;
  43127. const toneMapping = renderer.toneMapping;
  43128. const outputColorSpace = renderer.outputColorSpace;
  43129. quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  43130. quadMesh.material.needsUpdate = true;
  43131. this.needsUpdate = false;
  43132. }
  43133. }
  43134. async renderAsync() {
  43135. this.update();
  43136. const renderer = this.renderer;
  43137. const toneMapping = renderer.toneMapping;
  43138. const outputColorSpace = renderer.outputColorSpace;
  43139. renderer.toneMapping = NoToneMapping;
  43140. renderer.outputColorSpace = LinearSRGBColorSpace;
  43141. //
  43142. await quadMesh.renderAsync( this.renderer );
  43143. //
  43144. renderer.toneMapping = toneMapping;
  43145. renderer.outputColorSpace = outputColorSpace;
  43146. }
  43147. }
  43148. class StorageTexture extends Texture {
  43149. constructor( width = 1, height = 1 ) {
  43150. super();
  43151. this.image = { width, height };
  43152. this.magFilter = LinearFilter;
  43153. this.minFilter = LinearFilter;
  43154. this.isStorageTexture = true;
  43155. }
  43156. }
  43157. class StorageBufferAttribute extends BufferAttribute {
  43158. constructor( array, itemSize, typeClass = Float32Array ) {
  43159. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43160. super( array, itemSize );
  43161. this.isStorageBufferAttribute = true;
  43162. }
  43163. }
  43164. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  43165. constructor( array, itemSize, typeClass = Float32Array ) {
  43166. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43167. super( array, itemSize );
  43168. this.isStorageInstancedBufferAttribute = true;
  43169. }
  43170. }
  43171. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43172. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43173. revision: REVISION,
  43174. } } ) );
  43175. }
  43176. if ( typeof window !== 'undefined' ) {
  43177. if ( window.__THREE__ ) {
  43178. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43179. } else {
  43180. window.__THREE__ = REVISION;
  43181. }
  43182. }
  43183. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AfterImageNode, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnamorphicNode, 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, BasicShadowMap, BatchNode, BatchedMesh, BlendModeNode, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CheckerNode, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorAdjustmentNode, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, CondNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, 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, DepthOfFieldNode, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, DiscardNode, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DotScreenNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, FilmNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GaussianBlurNode, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HashNode, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, 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, LightNode, LightProbe, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, Lut3DNode, MOUSE, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathNode, MathUtils, 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, NodeKeywords, NodeLoader, NodeMaterial, NodeMaterialLoader, 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, OperatorNode, OrthographicCamera, OscNode, OutputStructNode, P3Primaries, PCFShadowMap, PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, PackingNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, 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, RGBFormat, RGBIntegerFormat, RGBShiftNode, 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, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, RotateUVNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, SobelOperatorNode, 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, TextureBicubicNode, TextureLoader, TextureNode, TextureSizeNode, TimerNode, ToneMappingNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UniformsNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acos, add, addLightNode, addNodeClass, addNodeElement, addNodeMaterial, afterImage, all, alphaT, anamorphic, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, attribute, backgroundBlurriness, backgroundIntensity, batch, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blur, bmat2, bmat3, bmat4, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToLinear, colorToDirection, compute, cond, context, convert, cos, createCanvasElement, createNodeFromType, createNodeMaterialFromType, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, densityFog, depth, depthPass, difference, diffuseColor, directionToColor, discard, distance, div, dodge, dof, dot, dotScreen, drawIndex, dynamicBufferAttribute, element, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, film, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, gaussianBlur, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, global, glsl, glslFn, greaterThan, greaterThanEqual, hash, hue, imat2, imat3, imat4, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightTargetDirection, lightingContext, lights, lightsNode, linearDepth, linearToColorSpace, linearTosRGB, log, log2, loop, lumaCoeffs, luminance, lut3D, mat2, mat3, mat4, matcapUV, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularStrength, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mod, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, 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, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, objectDirection, objectGroup, objectNormalMatrix, objectPosition, objectScale, objectViewMatrix, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, pcurve, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rgbShift, rotate, rotateUV, roughness, round, rtt, sRGBToLinear, sampler, saturate, saturation, screen, scriptable, scriptableValue, setCurrentStack, shaderStages, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, sobel, specularColor, split, spritesheetUV, sqrt, stack, step, storage, storageObject, storageTexture, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBicubic, textureCubeUV, textureLoad, texturePass, textureSize, textureStore, threshold, timerDelta, timerGlobal, timerLocal, toneMapping, transformDirection, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transpose, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, umat2, umat3, umat4, uniform, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportBottomRight, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSharedTexture, viewportTexture, viewportTopLeft, viewportTopRight, wgsl, wgslFn, xor };