three.webgpu.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933
  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 RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const DisplayP3ColorSpace = 'display-p3';
  168. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  169. const LinearTransfer = 'linear';
  170. const SRGBTransfer = 'srgb';
  171. const Rec709Primaries = 'rec709';
  172. const P3Primaries = 'p3';
  173. const ZeroStencilOp = 0;
  174. const KeepStencilOp = 7680;
  175. const ReplaceStencilOp = 7681;
  176. const IncrementStencilOp = 7682;
  177. const DecrementStencilOp = 7683;
  178. const IncrementWrapStencilOp = 34055;
  179. const DecrementWrapStencilOp = 34056;
  180. const InvertStencilOp = 5386;
  181. const NeverStencilFunc = 512;
  182. const LessStencilFunc = 513;
  183. const EqualStencilFunc = 514;
  184. const LessEqualStencilFunc = 515;
  185. const GreaterStencilFunc = 516;
  186. const NotEqualStencilFunc = 517;
  187. const GreaterEqualStencilFunc = 518;
  188. const AlwaysStencilFunc = 519;
  189. const NeverCompare = 512;
  190. const LessCompare = 513;
  191. const EqualCompare = 514;
  192. const LessEqualCompare = 515;
  193. const GreaterCompare = 516;
  194. const NotEqualCompare = 517;
  195. const GreaterEqualCompare = 518;
  196. const AlwaysCompare = 519;
  197. const StaticDrawUsage = 35044;
  198. const DynamicDrawUsage = 35048;
  199. const StreamDrawUsage = 35040;
  200. const StaticReadUsage = 35045;
  201. const DynamicReadUsage = 35049;
  202. const StreamReadUsage = 35041;
  203. const StaticCopyUsage = 35046;
  204. const DynamicCopyUsage = 35050;
  205. const StreamCopyUsage = 35042;
  206. const GLSL1 = '100';
  207. const GLSL3 = '300 es';
  208. const WebGLCoordinateSystem = 2000;
  209. const WebGPUCoordinateSystem = 2001;
  210. /**
  211. * https://github.com/mrdoob/eventdispatcher.js/
  212. */
  213. class EventDispatcher {
  214. addEventListener( type, listener ) {
  215. if ( this._listeners === undefined ) this._listeners = {};
  216. const listeners = this._listeners;
  217. if ( listeners[ type ] === undefined ) {
  218. listeners[ type ] = [];
  219. }
  220. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  221. listeners[ type ].push( listener );
  222. }
  223. }
  224. hasEventListener( type, listener ) {
  225. if ( this._listeners === undefined ) return false;
  226. const listeners = this._listeners;
  227. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  228. }
  229. removeEventListener( type, listener ) {
  230. if ( this._listeners === undefined ) return;
  231. const listeners = this._listeners;
  232. const listenerArray = listeners[ type ];
  233. if ( listenerArray !== undefined ) {
  234. const index = listenerArray.indexOf( listener );
  235. if ( index !== - 1 ) {
  236. listenerArray.splice( index, 1 );
  237. }
  238. }
  239. }
  240. dispatchEvent( event ) {
  241. if ( this._listeners === undefined ) return;
  242. const listeners = this._listeners;
  243. const listenerArray = listeners[ event.type ];
  244. if ( listenerArray !== undefined ) {
  245. event.target = this;
  246. // Make a copy, in case listeners are removed while iterating.
  247. const array = listenerArray.slice( 0 );
  248. for ( let i = 0, l = array.length; i < l; i ++ ) {
  249. array[ i ].call( this, event );
  250. }
  251. event.target = null;
  252. }
  253. }
  254. }
  255. 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' ];
  256. let _seed = 1234567;
  257. const DEG2RAD = Math.PI / 180;
  258. const RAD2DEG = 180 / Math.PI;
  259. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  260. function generateUUID() {
  261. const d0 = Math.random() * 0xffffffff | 0;
  262. const d1 = Math.random() * 0xffffffff | 0;
  263. const d2 = Math.random() * 0xffffffff | 0;
  264. const d3 = Math.random() * 0xffffffff | 0;
  265. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  266. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  267. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  268. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  269. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  270. return uuid.toLowerCase();
  271. }
  272. function clamp$1( value, min, max ) {
  273. return Math.max( min, Math.min( max, value ) );
  274. }
  275. // compute euclidean modulo of m % n
  276. // https://en.wikipedia.org/wiki/Modulo_operation
  277. function euclideanModulo( n, m ) {
  278. return ( ( n % m ) + m ) % m;
  279. }
  280. // Linear mapping from range <a1, a2> to range <b1, b2>
  281. function mapLinear( x, a1, a2, b1, b2 ) {
  282. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  283. }
  284. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  285. function inverseLerp( x, y, value ) {
  286. if ( x !== y ) {
  287. return ( value - x ) / ( y - x );
  288. } else {
  289. return 0;
  290. }
  291. }
  292. // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp( x, y, t ) {
  294. return ( 1 - t ) * x + t * y;
  295. }
  296. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  297. function damp( x, y, lambda, dt ) {
  298. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  299. }
  300. // https://www.desmos.com/calculator/vcsjnyz7x4
  301. function pingpong( x, length = 1 ) {
  302. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  303. }
  304. // http://en.wikipedia.org/wiki/Smoothstep
  305. function smoothstep$1( x, min, max ) {
  306. if ( x <= min ) return 0;
  307. if ( x >= max ) return 1;
  308. x = ( x - min ) / ( max - min );
  309. return x * x * ( 3 - 2 * x );
  310. }
  311. function smootherstep( x, min, max ) {
  312. if ( x <= min ) return 0;
  313. if ( x >= max ) return 1;
  314. x = ( x - min ) / ( max - min );
  315. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  316. }
  317. // Random integer from <low, high> interval
  318. function randInt( low, high ) {
  319. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  320. }
  321. // Random float from <low, high> interval
  322. function randFloat( low, high ) {
  323. return low + Math.random() * ( high - low );
  324. }
  325. // Random float from <-range/2, range/2> interval
  326. function randFloatSpread( range ) {
  327. return range * ( 0.5 - Math.random() );
  328. }
  329. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  330. function seededRandom( s ) {
  331. if ( s !== undefined ) _seed = s;
  332. // Mulberry32 generator
  333. let t = _seed += 0x6D2B79F5;
  334. t = Math.imul( t ^ t >>> 15, t | 1 );
  335. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  336. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  337. }
  338. function degToRad( degrees ) {
  339. return degrees * DEG2RAD;
  340. }
  341. function radToDeg( radians ) {
  342. return radians * RAD2DEG;
  343. }
  344. function isPowerOfTwo( value ) {
  345. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  346. }
  347. function ceilPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function floorPowerOfTwo( value ) {
  351. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  352. }
  353. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  354. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  355. // rotations are applied to the axes in the order specified by 'order'
  356. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  357. // angles are in radians
  358. const cos = Math.cos;
  359. const sin = Math.sin;
  360. const c2 = cos( b / 2 );
  361. const s2 = sin( b / 2 );
  362. const c13 = cos( ( a + c ) / 2 );
  363. const s13 = sin( ( a + c ) / 2 );
  364. const c1_3 = cos( ( a - c ) / 2 );
  365. const s1_3 = sin( ( a - c ) / 2 );
  366. const c3_1 = cos( ( c - a ) / 2 );
  367. const s3_1 = sin( ( c - a ) / 2 );
  368. switch ( order ) {
  369. case 'XYX':
  370. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  371. break;
  372. case 'YZY':
  373. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  374. break;
  375. case 'ZXZ':
  376. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  377. break;
  378. case 'XZX':
  379. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  380. break;
  381. case 'YXY':
  382. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  383. break;
  384. case 'ZYZ':
  385. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  386. break;
  387. default:
  388. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  389. }
  390. }
  391. function denormalize( value, array ) {
  392. switch ( array.constructor ) {
  393. case Float32Array:
  394. return value;
  395. case Uint32Array:
  396. return value / 4294967295.0;
  397. case Uint16Array:
  398. return value / 65535.0;
  399. case Uint8Array:
  400. return value / 255.0;
  401. case Int32Array:
  402. return Math.max( value / 2147483647.0, - 1.0 );
  403. case Int16Array:
  404. return Math.max( value / 32767.0, - 1.0 );
  405. case Int8Array:
  406. return Math.max( value / 127.0, - 1.0 );
  407. default:
  408. throw new Error( 'Invalid component type.' );
  409. }
  410. }
  411. function normalize$1( value, array ) {
  412. switch ( array.constructor ) {
  413. case Float32Array:
  414. return value;
  415. case Uint32Array:
  416. return Math.round( value * 4294967295.0 );
  417. case Uint16Array:
  418. return Math.round( value * 65535.0 );
  419. case Uint8Array:
  420. return Math.round( value * 255.0 );
  421. case Int32Array:
  422. return Math.round( value * 2147483647.0 );
  423. case Int16Array:
  424. return Math.round( value * 32767.0 );
  425. case Int8Array:
  426. return Math.round( value * 127.0 );
  427. default:
  428. throw new Error( 'Invalid component type.' );
  429. }
  430. }
  431. const MathUtils = {
  432. DEG2RAD: DEG2RAD,
  433. RAD2DEG: RAD2DEG,
  434. generateUUID: generateUUID,
  435. clamp: clamp$1,
  436. euclideanModulo: euclideanModulo,
  437. mapLinear: mapLinear,
  438. inverseLerp: inverseLerp,
  439. lerp: lerp,
  440. damp: damp,
  441. pingpong: pingpong,
  442. smoothstep: smoothstep$1,
  443. smootherstep: smootherstep,
  444. randInt: randInt,
  445. randFloat: randFloat,
  446. randFloatSpread: randFloatSpread,
  447. seededRandom: seededRandom,
  448. degToRad: degToRad,
  449. radToDeg: radToDeg,
  450. isPowerOfTwo: isPowerOfTwo,
  451. ceilPowerOfTwo: ceilPowerOfTwo,
  452. floorPowerOfTwo: floorPowerOfTwo,
  453. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  454. normalize: normalize$1,
  455. denormalize: denormalize
  456. };
  457. class Vector2 {
  458. constructor( x = 0, y = 0 ) {
  459. Vector2.prototype.isVector2 = true;
  460. this.x = x;
  461. this.y = y;
  462. }
  463. get width() {
  464. return this.x;
  465. }
  466. set width( value ) {
  467. this.x = value;
  468. }
  469. get height() {
  470. return this.y;
  471. }
  472. set height( value ) {
  473. this.y = value;
  474. }
  475. set( x, y ) {
  476. this.x = x;
  477. this.y = y;
  478. return this;
  479. }
  480. setScalar( scalar ) {
  481. this.x = scalar;
  482. this.y = scalar;
  483. return this;
  484. }
  485. setX( x ) {
  486. this.x = x;
  487. return this;
  488. }
  489. setY( y ) {
  490. this.y = y;
  491. return this;
  492. }
  493. setComponent( index, value ) {
  494. switch ( index ) {
  495. case 0: this.x = value; break;
  496. case 1: this.y = value; break;
  497. default: throw new Error( 'index is out of range: ' + index );
  498. }
  499. return this;
  500. }
  501. getComponent( index ) {
  502. switch ( index ) {
  503. case 0: return this.x;
  504. case 1: return this.y;
  505. default: throw new Error( 'index is out of range: ' + index );
  506. }
  507. }
  508. clone() {
  509. return new this.constructor( this.x, this.y );
  510. }
  511. copy( v ) {
  512. this.x = v.x;
  513. this.y = v.y;
  514. return this;
  515. }
  516. add( v ) {
  517. this.x += v.x;
  518. this.y += v.y;
  519. return this;
  520. }
  521. addScalar( s ) {
  522. this.x += s;
  523. this.y += s;
  524. return this;
  525. }
  526. addVectors( a, b ) {
  527. this.x = a.x + b.x;
  528. this.y = a.y + b.y;
  529. return this;
  530. }
  531. addScaledVector( v, s ) {
  532. this.x += v.x * s;
  533. this.y += v.y * s;
  534. return this;
  535. }
  536. sub( v ) {
  537. this.x -= v.x;
  538. this.y -= v.y;
  539. return this;
  540. }
  541. subScalar( s ) {
  542. this.x -= s;
  543. this.y -= s;
  544. return this;
  545. }
  546. subVectors( a, b ) {
  547. this.x = a.x - b.x;
  548. this.y = a.y - b.y;
  549. return this;
  550. }
  551. multiply( v ) {
  552. this.x *= v.x;
  553. this.y *= v.y;
  554. return this;
  555. }
  556. multiplyScalar( scalar ) {
  557. this.x *= scalar;
  558. this.y *= scalar;
  559. return this;
  560. }
  561. divide( v ) {
  562. this.x /= v.x;
  563. this.y /= v.y;
  564. return this;
  565. }
  566. divideScalar( scalar ) {
  567. return this.multiplyScalar( 1 / scalar );
  568. }
  569. applyMatrix3( m ) {
  570. const x = this.x, y = this.y;
  571. const e = m.elements;
  572. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  573. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  574. return this;
  575. }
  576. min( v ) {
  577. this.x = Math.min( this.x, v.x );
  578. this.y = Math.min( this.y, v.y );
  579. return this;
  580. }
  581. max( v ) {
  582. this.x = Math.max( this.x, v.x );
  583. this.y = Math.max( this.y, v.y );
  584. return this;
  585. }
  586. clamp( min, max ) {
  587. // assumes min < max, componentwise
  588. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  589. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  590. return this;
  591. }
  592. clampScalar( minVal, maxVal ) {
  593. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  594. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  595. return this;
  596. }
  597. clampLength( min, max ) {
  598. const length = this.length();
  599. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  600. }
  601. floor() {
  602. this.x = Math.floor( this.x );
  603. this.y = Math.floor( this.y );
  604. return this;
  605. }
  606. ceil() {
  607. this.x = Math.ceil( this.x );
  608. this.y = Math.ceil( this.y );
  609. return this;
  610. }
  611. round() {
  612. this.x = Math.round( this.x );
  613. this.y = Math.round( this.y );
  614. return this;
  615. }
  616. roundToZero() {
  617. this.x = Math.trunc( this.x );
  618. this.y = Math.trunc( this.y );
  619. return this;
  620. }
  621. negate() {
  622. this.x = - this.x;
  623. this.y = - this.y;
  624. return this;
  625. }
  626. dot( v ) {
  627. return this.x * v.x + this.y * v.y;
  628. }
  629. cross( v ) {
  630. return this.x * v.y - this.y * v.x;
  631. }
  632. lengthSq() {
  633. return this.x * this.x + this.y * this.y;
  634. }
  635. length() {
  636. return Math.sqrt( this.x * this.x + this.y * this.y );
  637. }
  638. manhattanLength() {
  639. return Math.abs( this.x ) + Math.abs( this.y );
  640. }
  641. normalize() {
  642. return this.divideScalar( this.length() || 1 );
  643. }
  644. angle() {
  645. // computes the angle in radians with respect to the positive x-axis
  646. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  647. return angle;
  648. }
  649. angleTo( v ) {
  650. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  651. if ( denominator === 0 ) return Math.PI / 2;
  652. const theta = this.dot( v ) / denominator;
  653. // clamp, to handle numerical problems
  654. return Math.acos( clamp$1( theta, - 1, 1 ) );
  655. }
  656. distanceTo( v ) {
  657. return Math.sqrt( this.distanceToSquared( v ) );
  658. }
  659. distanceToSquared( v ) {
  660. const dx = this.x - v.x, dy = this.y - v.y;
  661. return dx * dx + dy * dy;
  662. }
  663. manhattanDistanceTo( v ) {
  664. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  665. }
  666. setLength( length ) {
  667. return this.normalize().multiplyScalar( length );
  668. }
  669. lerp( v, alpha ) {
  670. this.x += ( v.x - this.x ) * alpha;
  671. this.y += ( v.y - this.y ) * alpha;
  672. return this;
  673. }
  674. lerpVectors( v1, v2, alpha ) {
  675. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  676. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  677. return this;
  678. }
  679. equals( v ) {
  680. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  681. }
  682. fromArray( array, offset = 0 ) {
  683. this.x = array[ offset ];
  684. this.y = array[ offset + 1 ];
  685. return this;
  686. }
  687. toArray( array = [], offset = 0 ) {
  688. array[ offset ] = this.x;
  689. array[ offset + 1 ] = this.y;
  690. return array;
  691. }
  692. fromBufferAttribute( attribute, index ) {
  693. this.x = attribute.getX( index );
  694. this.y = attribute.getY( index );
  695. return this;
  696. }
  697. rotateAround( center, angle ) {
  698. const c = Math.cos( angle ), s = Math.sin( angle );
  699. const x = this.x - center.x;
  700. const y = this.y - center.y;
  701. this.x = x * c - y * s + center.x;
  702. this.y = x * s + y * c + center.y;
  703. return this;
  704. }
  705. random() {
  706. this.x = Math.random();
  707. this.y = Math.random();
  708. return this;
  709. }
  710. *[ Symbol.iterator ]() {
  711. yield this.x;
  712. yield this.y;
  713. }
  714. }
  715. class Matrix3 {
  716. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  717. Matrix3.prototype.isMatrix3 = true;
  718. this.elements = [
  719. 1, 0, 0,
  720. 0, 1, 0,
  721. 0, 0, 1
  722. ];
  723. if ( n11 !== undefined ) {
  724. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  725. }
  726. }
  727. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  728. const te = this.elements;
  729. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  730. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  731. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  732. return this;
  733. }
  734. identity() {
  735. this.set(
  736. 1, 0, 0,
  737. 0, 1, 0,
  738. 0, 0, 1
  739. );
  740. return this;
  741. }
  742. copy( m ) {
  743. const te = this.elements;
  744. const me = m.elements;
  745. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  746. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  747. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  748. return this;
  749. }
  750. extractBasis( xAxis, yAxis, zAxis ) {
  751. xAxis.setFromMatrix3Column( this, 0 );
  752. yAxis.setFromMatrix3Column( this, 1 );
  753. zAxis.setFromMatrix3Column( this, 2 );
  754. return this;
  755. }
  756. setFromMatrix4( m ) {
  757. const me = m.elements;
  758. this.set(
  759. me[ 0 ], me[ 4 ], me[ 8 ],
  760. me[ 1 ], me[ 5 ], me[ 9 ],
  761. me[ 2 ], me[ 6 ], me[ 10 ]
  762. );
  763. return this;
  764. }
  765. multiply( m ) {
  766. return this.multiplyMatrices( this, m );
  767. }
  768. premultiply( m ) {
  769. return this.multiplyMatrices( m, this );
  770. }
  771. multiplyMatrices( a, b ) {
  772. const ae = a.elements;
  773. const be = b.elements;
  774. const te = this.elements;
  775. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  776. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  777. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  778. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  779. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  780. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  781. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  782. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  783. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  784. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  785. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  786. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  787. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  788. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  789. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  790. return this;
  791. }
  792. multiplyScalar( s ) {
  793. const te = this.elements;
  794. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  795. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  796. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  797. return this;
  798. }
  799. determinant() {
  800. const te = this.elements;
  801. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  802. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  803. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  804. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  805. }
  806. invert() {
  807. const te = this.elements,
  808. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  809. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  810. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  811. t11 = n33 * n22 - n32 * n23,
  812. t12 = n32 * n13 - n33 * n12,
  813. t13 = n23 * n12 - n22 * n13,
  814. det = n11 * t11 + n21 * t12 + n31 * t13;
  815. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  816. const detInv = 1 / det;
  817. te[ 0 ] = t11 * detInv;
  818. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  819. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  820. te[ 3 ] = t12 * detInv;
  821. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  822. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  823. te[ 6 ] = t13 * detInv;
  824. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  825. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  826. return this;
  827. }
  828. transpose() {
  829. let tmp;
  830. const m = this.elements;
  831. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  832. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  833. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  834. return this;
  835. }
  836. getNormalMatrix( matrix4 ) {
  837. return this.setFromMatrix4( matrix4 ).invert().transpose();
  838. }
  839. transposeIntoArray( r ) {
  840. const m = this.elements;
  841. r[ 0 ] = m[ 0 ];
  842. r[ 1 ] = m[ 3 ];
  843. r[ 2 ] = m[ 6 ];
  844. r[ 3 ] = m[ 1 ];
  845. r[ 4 ] = m[ 4 ];
  846. r[ 5 ] = m[ 7 ];
  847. r[ 6 ] = m[ 2 ];
  848. r[ 7 ] = m[ 5 ];
  849. r[ 8 ] = m[ 8 ];
  850. return this;
  851. }
  852. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  853. const c = Math.cos( rotation );
  854. const s = Math.sin( rotation );
  855. this.set(
  856. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  857. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  858. 0, 0, 1
  859. );
  860. return this;
  861. }
  862. //
  863. scale( sx, sy ) {
  864. this.premultiply( _m3.makeScale( sx, sy ) );
  865. return this;
  866. }
  867. rotate( theta ) {
  868. this.premultiply( _m3.makeRotation( - theta ) );
  869. return this;
  870. }
  871. translate( tx, ty ) {
  872. this.premultiply( _m3.makeTranslation( tx, ty ) );
  873. return this;
  874. }
  875. // for 2D Transforms
  876. makeTranslation( x, y ) {
  877. if ( x.isVector2 ) {
  878. this.set(
  879. 1, 0, x.x,
  880. 0, 1, x.y,
  881. 0, 0, 1
  882. );
  883. } else {
  884. this.set(
  885. 1, 0, x,
  886. 0, 1, y,
  887. 0, 0, 1
  888. );
  889. }
  890. return this;
  891. }
  892. makeRotation( theta ) {
  893. // counterclockwise
  894. const c = Math.cos( theta );
  895. const s = Math.sin( theta );
  896. this.set(
  897. c, - s, 0,
  898. s, c, 0,
  899. 0, 0, 1
  900. );
  901. return this;
  902. }
  903. makeScale( x, y ) {
  904. this.set(
  905. x, 0, 0,
  906. 0, y, 0,
  907. 0, 0, 1
  908. );
  909. return this;
  910. }
  911. //
  912. equals( matrix ) {
  913. const te = this.elements;
  914. const me = matrix.elements;
  915. for ( let i = 0; i < 9; i ++ ) {
  916. if ( te[ i ] !== me[ i ] ) return false;
  917. }
  918. return true;
  919. }
  920. fromArray( array, offset = 0 ) {
  921. for ( let i = 0; i < 9; i ++ ) {
  922. this.elements[ i ] = array[ i + offset ];
  923. }
  924. return this;
  925. }
  926. toArray( array = [], offset = 0 ) {
  927. const te = this.elements;
  928. array[ offset ] = te[ 0 ];
  929. array[ offset + 1 ] = te[ 1 ];
  930. array[ offset + 2 ] = te[ 2 ];
  931. array[ offset + 3 ] = te[ 3 ];
  932. array[ offset + 4 ] = te[ 4 ];
  933. array[ offset + 5 ] = te[ 5 ];
  934. array[ offset + 6 ] = te[ 6 ];
  935. array[ offset + 7 ] = te[ 7 ];
  936. array[ offset + 8 ] = te[ 8 ];
  937. return array;
  938. }
  939. clone() {
  940. return new this.constructor().fromArray( this.elements );
  941. }
  942. }
  943. const _m3 = /*@__PURE__*/ new Matrix3();
  944. function arrayNeedsUint32$1( array ) {
  945. // assumes larger values usually on last
  946. for ( let i = array.length - 1; i >= 0; -- i ) {
  947. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  948. }
  949. return false;
  950. }
  951. const TYPED_ARRAYS = {
  952. Int8Array: Int8Array,
  953. Uint8Array: Uint8Array,
  954. Uint8ClampedArray: Uint8ClampedArray,
  955. Int16Array: Int16Array,
  956. Uint16Array: Uint16Array,
  957. Int32Array: Int32Array,
  958. Uint32Array: Uint32Array,
  959. Float32Array: Float32Array,
  960. Float64Array: Float64Array
  961. };
  962. function getTypedArray( type, buffer ) {
  963. return new TYPED_ARRAYS[ type ]( buffer );
  964. }
  965. function createElementNS( name ) {
  966. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  967. }
  968. function createCanvasElement() {
  969. const canvas = createElementNS( 'canvas' );
  970. canvas.style.display = 'block';
  971. return canvas;
  972. }
  973. const _cache$1 = {};
  974. function warnOnce( message ) {
  975. if ( message in _cache$1 ) return;
  976. _cache$1[ message ] = true;
  977. console.warn( message );
  978. }
  979. /**
  980. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  981. * or clipping. Based on W3C specifications for sRGB and Display P3,
  982. * and ICC specifications for the D50 connection space. Values in/out
  983. * are _linear_ sRGB and _linear_ Display P3.
  984. *
  985. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  986. *
  987. * Reference:
  988. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  989. */
  990. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  991. 0.8224621, 0.177538, 0.0,
  992. 0.0331941, 0.9668058, 0.0,
  993. 0.0170827, 0.0723974, 0.9105199,
  994. );
  995. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  996. 1.2249401, - 0.2249404, 0.0,
  997. - 0.0420569, 1.0420571, 0.0,
  998. - 0.0196376, - 0.0786361, 1.0982735
  999. );
  1000. /**
  1001. * Defines supported color spaces by transfer function and primaries,
  1002. * and provides conversions to/from the Linear-sRGB reference space.
  1003. */
  1004. const COLOR_SPACES = {
  1005. [ LinearSRGBColorSpace ]: {
  1006. transfer: LinearTransfer,
  1007. primaries: Rec709Primaries,
  1008. toReference: ( color ) => color,
  1009. fromReference: ( color ) => color,
  1010. },
  1011. [ SRGBColorSpace ]: {
  1012. transfer: SRGBTransfer,
  1013. primaries: Rec709Primaries,
  1014. toReference: ( color ) => color.convertSRGBToLinear(),
  1015. fromReference: ( color ) => color.convertLinearToSRGB(),
  1016. },
  1017. [ LinearDisplayP3ColorSpace ]: {
  1018. transfer: LinearTransfer,
  1019. primaries: P3Primaries,
  1020. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1021. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1022. },
  1023. [ DisplayP3ColorSpace ]: {
  1024. transfer: SRGBTransfer,
  1025. primaries: P3Primaries,
  1026. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1027. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1028. },
  1029. };
  1030. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1031. const ColorManagement = {
  1032. enabled: true,
  1033. _workingColorSpace: LinearSRGBColorSpace,
  1034. get workingColorSpace() {
  1035. return this._workingColorSpace;
  1036. },
  1037. set workingColorSpace( colorSpace ) {
  1038. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1039. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1040. }
  1041. this._workingColorSpace = colorSpace;
  1042. },
  1043. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1044. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1045. return color;
  1046. }
  1047. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1048. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1049. return targetFromReference( sourceToReference( color ) );
  1050. },
  1051. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1052. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1053. },
  1054. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1055. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1056. },
  1057. getPrimaries: function ( colorSpace ) {
  1058. return COLOR_SPACES[ colorSpace ].primaries;
  1059. },
  1060. getTransfer: function ( colorSpace ) {
  1061. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1062. return COLOR_SPACES[ colorSpace ].transfer;
  1063. },
  1064. };
  1065. function SRGBToLinear( c ) {
  1066. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1067. }
  1068. function LinearToSRGB( c ) {
  1069. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1070. }
  1071. let _canvas;
  1072. class ImageUtils {
  1073. static getDataURL( image ) {
  1074. if ( /^data:/i.test( image.src ) ) {
  1075. return image.src;
  1076. }
  1077. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1078. return image.src;
  1079. }
  1080. let canvas;
  1081. if ( image instanceof HTMLCanvasElement ) {
  1082. canvas = image;
  1083. } else {
  1084. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1085. _canvas.width = image.width;
  1086. _canvas.height = image.height;
  1087. const context = _canvas.getContext( '2d' );
  1088. if ( image instanceof ImageData ) {
  1089. context.putImageData( image, 0, 0 );
  1090. } else {
  1091. context.drawImage( image, 0, 0, image.width, image.height );
  1092. }
  1093. canvas = _canvas;
  1094. }
  1095. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1096. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1097. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1098. } else {
  1099. return canvas.toDataURL( 'image/png' );
  1100. }
  1101. }
  1102. static sRGBToLinear( image ) {
  1103. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1104. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1105. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1106. const canvas = createElementNS( 'canvas' );
  1107. canvas.width = image.width;
  1108. canvas.height = image.height;
  1109. const context = canvas.getContext( '2d' );
  1110. context.drawImage( image, 0, 0, image.width, image.height );
  1111. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1112. const data = imageData.data;
  1113. for ( let i = 0; i < data.length; i ++ ) {
  1114. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1115. }
  1116. context.putImageData( imageData, 0, 0 );
  1117. return canvas;
  1118. } else if ( image.data ) {
  1119. const data = image.data.slice( 0 );
  1120. for ( let i = 0; i < data.length; i ++ ) {
  1121. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1122. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1123. } else {
  1124. // assuming float
  1125. data[ i ] = SRGBToLinear( data[ i ] );
  1126. }
  1127. }
  1128. return {
  1129. data: data,
  1130. width: image.width,
  1131. height: image.height
  1132. };
  1133. } else {
  1134. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1135. return image;
  1136. }
  1137. }
  1138. }
  1139. let _sourceId = 0;
  1140. class Source {
  1141. constructor( data = null ) {
  1142. this.isSource = true;
  1143. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1144. this.uuid = generateUUID();
  1145. this.data = data;
  1146. this.dataReady = true;
  1147. this.version = 0;
  1148. }
  1149. set needsUpdate( value ) {
  1150. if ( value === true ) this.version ++;
  1151. }
  1152. toJSON( meta ) {
  1153. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1154. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1155. return meta.images[ this.uuid ];
  1156. }
  1157. const output = {
  1158. uuid: this.uuid,
  1159. url: ''
  1160. };
  1161. const data = this.data;
  1162. if ( data !== null ) {
  1163. let url;
  1164. if ( Array.isArray( data ) ) {
  1165. // cube texture
  1166. url = [];
  1167. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1168. if ( data[ i ].isDataTexture ) {
  1169. url.push( serializeImage( data[ i ].image ) );
  1170. } else {
  1171. url.push( serializeImage( data[ i ] ) );
  1172. }
  1173. }
  1174. } else {
  1175. // texture
  1176. url = serializeImage( data );
  1177. }
  1178. output.url = url;
  1179. }
  1180. if ( ! isRootObject ) {
  1181. meta.images[ this.uuid ] = output;
  1182. }
  1183. return output;
  1184. }
  1185. }
  1186. function serializeImage( image ) {
  1187. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1188. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1189. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1190. // default images
  1191. return ImageUtils.getDataURL( image );
  1192. } else {
  1193. if ( image.data ) {
  1194. // images of DataTexture
  1195. return {
  1196. data: Array.from( image.data ),
  1197. width: image.width,
  1198. height: image.height,
  1199. type: image.data.constructor.name
  1200. };
  1201. } else {
  1202. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1203. return {};
  1204. }
  1205. }
  1206. }
  1207. let _textureId = 0;
  1208. class Texture extends EventDispatcher {
  1209. 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 ) {
  1210. super();
  1211. this.isTexture = true;
  1212. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1213. this.uuid = generateUUID();
  1214. this.name = '';
  1215. this.source = new Source( image );
  1216. this.mipmaps = [];
  1217. this.mapping = mapping;
  1218. this.channel = 0;
  1219. this.wrapS = wrapS;
  1220. this.wrapT = wrapT;
  1221. this.magFilter = magFilter;
  1222. this.minFilter = minFilter;
  1223. this.anisotropy = anisotropy;
  1224. this.format = format;
  1225. this.internalFormat = null;
  1226. this.type = type;
  1227. this.offset = new Vector2( 0, 0 );
  1228. this.repeat = new Vector2( 1, 1 );
  1229. this.center = new Vector2( 0, 0 );
  1230. this.rotation = 0;
  1231. this.matrixAutoUpdate = true;
  1232. this.matrix = new Matrix3();
  1233. this.generateMipmaps = true;
  1234. this.premultiplyAlpha = false;
  1235. this.flipY = true;
  1236. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1237. this.colorSpace = colorSpace;
  1238. this.userData = {};
  1239. this.version = 0;
  1240. this.onUpdate = null;
  1241. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1242. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1243. }
  1244. get image() {
  1245. return this.source.data;
  1246. }
  1247. set image( value = null ) {
  1248. this.source.data = value;
  1249. }
  1250. updateMatrix() {
  1251. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1252. }
  1253. clone() {
  1254. return new this.constructor().copy( this );
  1255. }
  1256. copy( source ) {
  1257. this.name = source.name;
  1258. this.source = source.source;
  1259. this.mipmaps = source.mipmaps.slice( 0 );
  1260. this.mapping = source.mapping;
  1261. this.channel = source.channel;
  1262. this.wrapS = source.wrapS;
  1263. this.wrapT = source.wrapT;
  1264. this.magFilter = source.magFilter;
  1265. this.minFilter = source.minFilter;
  1266. this.anisotropy = source.anisotropy;
  1267. this.format = source.format;
  1268. this.internalFormat = source.internalFormat;
  1269. this.type = source.type;
  1270. this.offset.copy( source.offset );
  1271. this.repeat.copy( source.repeat );
  1272. this.center.copy( source.center );
  1273. this.rotation = source.rotation;
  1274. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1275. this.matrix.copy( source.matrix );
  1276. this.generateMipmaps = source.generateMipmaps;
  1277. this.premultiplyAlpha = source.premultiplyAlpha;
  1278. this.flipY = source.flipY;
  1279. this.unpackAlignment = source.unpackAlignment;
  1280. this.colorSpace = source.colorSpace;
  1281. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1282. this.needsUpdate = true;
  1283. return this;
  1284. }
  1285. toJSON( meta ) {
  1286. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1287. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1288. return meta.textures[ this.uuid ];
  1289. }
  1290. const output = {
  1291. metadata: {
  1292. version: 4.6,
  1293. type: 'Texture',
  1294. generator: 'Texture.toJSON'
  1295. },
  1296. uuid: this.uuid,
  1297. name: this.name,
  1298. image: this.source.toJSON( meta ).uuid,
  1299. mapping: this.mapping,
  1300. channel: this.channel,
  1301. repeat: [ this.repeat.x, this.repeat.y ],
  1302. offset: [ this.offset.x, this.offset.y ],
  1303. center: [ this.center.x, this.center.y ],
  1304. rotation: this.rotation,
  1305. wrap: [ this.wrapS, this.wrapT ],
  1306. format: this.format,
  1307. internalFormat: this.internalFormat,
  1308. type: this.type,
  1309. colorSpace: this.colorSpace,
  1310. minFilter: this.minFilter,
  1311. magFilter: this.magFilter,
  1312. anisotropy: this.anisotropy,
  1313. flipY: this.flipY,
  1314. generateMipmaps: this.generateMipmaps,
  1315. premultiplyAlpha: this.premultiplyAlpha,
  1316. unpackAlignment: this.unpackAlignment
  1317. };
  1318. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1319. if ( ! isRootObject ) {
  1320. meta.textures[ this.uuid ] = output;
  1321. }
  1322. return output;
  1323. }
  1324. dispose() {
  1325. this.dispatchEvent( { type: 'dispose' } );
  1326. }
  1327. transformUv( uv ) {
  1328. if ( this.mapping !== UVMapping ) return uv;
  1329. uv.applyMatrix3( this.matrix );
  1330. if ( uv.x < 0 || uv.x > 1 ) {
  1331. switch ( this.wrapS ) {
  1332. case RepeatWrapping:
  1333. uv.x = uv.x - Math.floor( uv.x );
  1334. break;
  1335. case ClampToEdgeWrapping:
  1336. uv.x = uv.x < 0 ? 0 : 1;
  1337. break;
  1338. case MirroredRepeatWrapping:
  1339. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1340. uv.x = Math.ceil( uv.x ) - uv.x;
  1341. } else {
  1342. uv.x = uv.x - Math.floor( uv.x );
  1343. }
  1344. break;
  1345. }
  1346. }
  1347. if ( uv.y < 0 || uv.y > 1 ) {
  1348. switch ( this.wrapT ) {
  1349. case RepeatWrapping:
  1350. uv.y = uv.y - Math.floor( uv.y );
  1351. break;
  1352. case ClampToEdgeWrapping:
  1353. uv.y = uv.y < 0 ? 0 : 1;
  1354. break;
  1355. case MirroredRepeatWrapping:
  1356. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1357. uv.y = Math.ceil( uv.y ) - uv.y;
  1358. } else {
  1359. uv.y = uv.y - Math.floor( uv.y );
  1360. }
  1361. break;
  1362. }
  1363. }
  1364. if ( this.flipY ) {
  1365. uv.y = 1 - uv.y;
  1366. }
  1367. return uv;
  1368. }
  1369. set needsUpdate( value ) {
  1370. if ( value === true ) {
  1371. this.version ++;
  1372. this.source.needsUpdate = true;
  1373. }
  1374. }
  1375. set needsPMREMUpdate( value ) {
  1376. if ( value === true ) {
  1377. this.pmremVersion ++;
  1378. }
  1379. }
  1380. }
  1381. Texture.DEFAULT_IMAGE = null;
  1382. Texture.DEFAULT_MAPPING = UVMapping;
  1383. Texture.DEFAULT_ANISOTROPY = 1;
  1384. class Vector4 {
  1385. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1386. Vector4.prototype.isVector4 = true;
  1387. this.x = x;
  1388. this.y = y;
  1389. this.z = z;
  1390. this.w = w;
  1391. }
  1392. get width() {
  1393. return this.z;
  1394. }
  1395. set width( value ) {
  1396. this.z = value;
  1397. }
  1398. get height() {
  1399. return this.w;
  1400. }
  1401. set height( value ) {
  1402. this.w = value;
  1403. }
  1404. set( x, y, z, w ) {
  1405. this.x = x;
  1406. this.y = y;
  1407. this.z = z;
  1408. this.w = w;
  1409. return this;
  1410. }
  1411. setScalar( scalar ) {
  1412. this.x = scalar;
  1413. this.y = scalar;
  1414. this.z = scalar;
  1415. this.w = scalar;
  1416. return this;
  1417. }
  1418. setX( x ) {
  1419. this.x = x;
  1420. return this;
  1421. }
  1422. setY( y ) {
  1423. this.y = y;
  1424. return this;
  1425. }
  1426. setZ( z ) {
  1427. this.z = z;
  1428. return this;
  1429. }
  1430. setW( w ) {
  1431. this.w = w;
  1432. return this;
  1433. }
  1434. setComponent( index, value ) {
  1435. switch ( index ) {
  1436. case 0: this.x = value; break;
  1437. case 1: this.y = value; break;
  1438. case 2: this.z = value; break;
  1439. case 3: this.w = value; break;
  1440. default: throw new Error( 'index is out of range: ' + index );
  1441. }
  1442. return this;
  1443. }
  1444. getComponent( index ) {
  1445. switch ( index ) {
  1446. case 0: return this.x;
  1447. case 1: return this.y;
  1448. case 2: return this.z;
  1449. case 3: return this.w;
  1450. default: throw new Error( 'index is out of range: ' + index );
  1451. }
  1452. }
  1453. clone() {
  1454. return new this.constructor( this.x, this.y, this.z, this.w );
  1455. }
  1456. copy( v ) {
  1457. this.x = v.x;
  1458. this.y = v.y;
  1459. this.z = v.z;
  1460. this.w = ( v.w !== undefined ) ? v.w : 1;
  1461. return this;
  1462. }
  1463. add( v ) {
  1464. this.x += v.x;
  1465. this.y += v.y;
  1466. this.z += v.z;
  1467. this.w += v.w;
  1468. return this;
  1469. }
  1470. addScalar( s ) {
  1471. this.x += s;
  1472. this.y += s;
  1473. this.z += s;
  1474. this.w += s;
  1475. return this;
  1476. }
  1477. addVectors( a, b ) {
  1478. this.x = a.x + b.x;
  1479. this.y = a.y + b.y;
  1480. this.z = a.z + b.z;
  1481. this.w = a.w + b.w;
  1482. return this;
  1483. }
  1484. addScaledVector( v, s ) {
  1485. this.x += v.x * s;
  1486. this.y += v.y * s;
  1487. this.z += v.z * s;
  1488. this.w += v.w * s;
  1489. return this;
  1490. }
  1491. sub( v ) {
  1492. this.x -= v.x;
  1493. this.y -= v.y;
  1494. this.z -= v.z;
  1495. this.w -= v.w;
  1496. return this;
  1497. }
  1498. subScalar( s ) {
  1499. this.x -= s;
  1500. this.y -= s;
  1501. this.z -= s;
  1502. this.w -= s;
  1503. return this;
  1504. }
  1505. subVectors( a, b ) {
  1506. this.x = a.x - b.x;
  1507. this.y = a.y - b.y;
  1508. this.z = a.z - b.z;
  1509. this.w = a.w - b.w;
  1510. return this;
  1511. }
  1512. multiply( v ) {
  1513. this.x *= v.x;
  1514. this.y *= v.y;
  1515. this.z *= v.z;
  1516. this.w *= v.w;
  1517. return this;
  1518. }
  1519. multiplyScalar( scalar ) {
  1520. this.x *= scalar;
  1521. this.y *= scalar;
  1522. this.z *= scalar;
  1523. this.w *= scalar;
  1524. return this;
  1525. }
  1526. applyMatrix4( m ) {
  1527. const x = this.x, y = this.y, z = this.z, w = this.w;
  1528. const e = m.elements;
  1529. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1530. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1531. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1532. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1533. return this;
  1534. }
  1535. divideScalar( scalar ) {
  1536. return this.multiplyScalar( 1 / scalar );
  1537. }
  1538. setAxisAngleFromQuaternion( q ) {
  1539. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1540. // q is assumed to be normalized
  1541. this.w = 2 * Math.acos( q.w );
  1542. const s = Math.sqrt( 1 - q.w * q.w );
  1543. if ( s < 0.0001 ) {
  1544. this.x = 1;
  1545. this.y = 0;
  1546. this.z = 0;
  1547. } else {
  1548. this.x = q.x / s;
  1549. this.y = q.y / s;
  1550. this.z = q.z / s;
  1551. }
  1552. return this;
  1553. }
  1554. setAxisAngleFromRotationMatrix( m ) {
  1555. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1556. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1557. let angle, x, y, z; // variables for result
  1558. const epsilon = 0.01, // margin to allow for rounding errors
  1559. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1560. te = m.elements,
  1561. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1562. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1563. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1564. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1565. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1566. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1567. // singularity found
  1568. // first check for identity matrix which must have +1 for all terms
  1569. // in leading diagonal and zero in other terms
  1570. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1571. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1572. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1573. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1574. // this singularity is identity matrix so angle = 0
  1575. this.set( 1, 0, 0, 0 );
  1576. return this; // zero angle, arbitrary axis
  1577. }
  1578. // otherwise this singularity is angle = 180
  1579. angle = Math.PI;
  1580. const xx = ( m11 + 1 ) / 2;
  1581. const yy = ( m22 + 1 ) / 2;
  1582. const zz = ( m33 + 1 ) / 2;
  1583. const xy = ( m12 + m21 ) / 4;
  1584. const xz = ( m13 + m31 ) / 4;
  1585. const yz = ( m23 + m32 ) / 4;
  1586. if ( ( xx > yy ) && ( xx > zz ) ) {
  1587. // m11 is the largest diagonal term
  1588. if ( xx < epsilon ) {
  1589. x = 0;
  1590. y = 0.707106781;
  1591. z = 0.707106781;
  1592. } else {
  1593. x = Math.sqrt( xx );
  1594. y = xy / x;
  1595. z = xz / x;
  1596. }
  1597. } else if ( yy > zz ) {
  1598. // m22 is the largest diagonal term
  1599. if ( yy < epsilon ) {
  1600. x = 0.707106781;
  1601. y = 0;
  1602. z = 0.707106781;
  1603. } else {
  1604. y = Math.sqrt( yy );
  1605. x = xy / y;
  1606. z = yz / y;
  1607. }
  1608. } else {
  1609. // m33 is the largest diagonal term so base result on this
  1610. if ( zz < epsilon ) {
  1611. x = 0.707106781;
  1612. y = 0.707106781;
  1613. z = 0;
  1614. } else {
  1615. z = Math.sqrt( zz );
  1616. x = xz / z;
  1617. y = yz / z;
  1618. }
  1619. }
  1620. this.set( x, y, z, angle );
  1621. return this; // return 180 deg rotation
  1622. }
  1623. // as we have reached here there are no singularities so we can handle normally
  1624. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1625. ( m13 - m31 ) * ( m13 - m31 ) +
  1626. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1627. if ( Math.abs( s ) < 0.001 ) s = 1;
  1628. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1629. // caught by singularity test above, but I've left it in just in case
  1630. this.x = ( m32 - m23 ) / s;
  1631. this.y = ( m13 - m31 ) / s;
  1632. this.z = ( m21 - m12 ) / s;
  1633. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1634. return this;
  1635. }
  1636. setFromMatrixPosition( m ) {
  1637. const e = m.elements;
  1638. this.x = e[ 12 ];
  1639. this.y = e[ 13 ];
  1640. this.z = e[ 14 ];
  1641. this.w = e[ 15 ];
  1642. return this;
  1643. }
  1644. min( v ) {
  1645. this.x = Math.min( this.x, v.x );
  1646. this.y = Math.min( this.y, v.y );
  1647. this.z = Math.min( this.z, v.z );
  1648. this.w = Math.min( this.w, v.w );
  1649. return this;
  1650. }
  1651. max( v ) {
  1652. this.x = Math.max( this.x, v.x );
  1653. this.y = Math.max( this.y, v.y );
  1654. this.z = Math.max( this.z, v.z );
  1655. this.w = Math.max( this.w, v.w );
  1656. return this;
  1657. }
  1658. clamp( min, max ) {
  1659. // assumes min < max, componentwise
  1660. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1661. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1662. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1663. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1664. return this;
  1665. }
  1666. clampScalar( minVal, maxVal ) {
  1667. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1668. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1669. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1670. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1671. return this;
  1672. }
  1673. clampLength( min, max ) {
  1674. const length = this.length();
  1675. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1676. }
  1677. floor() {
  1678. this.x = Math.floor( this.x );
  1679. this.y = Math.floor( this.y );
  1680. this.z = Math.floor( this.z );
  1681. this.w = Math.floor( this.w );
  1682. return this;
  1683. }
  1684. ceil() {
  1685. this.x = Math.ceil( this.x );
  1686. this.y = Math.ceil( this.y );
  1687. this.z = Math.ceil( this.z );
  1688. this.w = Math.ceil( this.w );
  1689. return this;
  1690. }
  1691. round() {
  1692. this.x = Math.round( this.x );
  1693. this.y = Math.round( this.y );
  1694. this.z = Math.round( this.z );
  1695. this.w = Math.round( this.w );
  1696. return this;
  1697. }
  1698. roundToZero() {
  1699. this.x = Math.trunc( this.x );
  1700. this.y = Math.trunc( this.y );
  1701. this.z = Math.trunc( this.z );
  1702. this.w = Math.trunc( this.w );
  1703. return this;
  1704. }
  1705. negate() {
  1706. this.x = - this.x;
  1707. this.y = - this.y;
  1708. this.z = - this.z;
  1709. this.w = - this.w;
  1710. return this;
  1711. }
  1712. dot( v ) {
  1713. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1714. }
  1715. lengthSq() {
  1716. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1717. }
  1718. length() {
  1719. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1720. }
  1721. manhattanLength() {
  1722. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1723. }
  1724. normalize() {
  1725. return this.divideScalar( this.length() || 1 );
  1726. }
  1727. setLength( length ) {
  1728. return this.normalize().multiplyScalar( length );
  1729. }
  1730. lerp( v, alpha ) {
  1731. this.x += ( v.x - this.x ) * alpha;
  1732. this.y += ( v.y - this.y ) * alpha;
  1733. this.z += ( v.z - this.z ) * alpha;
  1734. this.w += ( v.w - this.w ) * alpha;
  1735. return this;
  1736. }
  1737. lerpVectors( v1, v2, alpha ) {
  1738. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1739. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1740. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1741. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1742. return this;
  1743. }
  1744. equals( v ) {
  1745. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1746. }
  1747. fromArray( array, offset = 0 ) {
  1748. this.x = array[ offset ];
  1749. this.y = array[ offset + 1 ];
  1750. this.z = array[ offset + 2 ];
  1751. this.w = array[ offset + 3 ];
  1752. return this;
  1753. }
  1754. toArray( array = [], offset = 0 ) {
  1755. array[ offset ] = this.x;
  1756. array[ offset + 1 ] = this.y;
  1757. array[ offset + 2 ] = this.z;
  1758. array[ offset + 3 ] = this.w;
  1759. return array;
  1760. }
  1761. fromBufferAttribute( attribute, index ) {
  1762. this.x = attribute.getX( index );
  1763. this.y = attribute.getY( index );
  1764. this.z = attribute.getZ( index );
  1765. this.w = attribute.getW( index );
  1766. return this;
  1767. }
  1768. random() {
  1769. this.x = Math.random();
  1770. this.y = Math.random();
  1771. this.z = Math.random();
  1772. this.w = Math.random();
  1773. return this;
  1774. }
  1775. *[ Symbol.iterator ]() {
  1776. yield this.x;
  1777. yield this.y;
  1778. yield this.z;
  1779. yield this.w;
  1780. }
  1781. }
  1782. /*
  1783. In options, we can specify:
  1784. * Texture parameters for an auto-generated target texture
  1785. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1786. */
  1787. class RenderTarget extends EventDispatcher {
  1788. constructor( width = 1, height = 1, options = {} ) {
  1789. super();
  1790. this.isRenderTarget = true;
  1791. this.width = width;
  1792. this.height = height;
  1793. this.depth = 1;
  1794. this.scissor = new Vector4( 0, 0, width, height );
  1795. this.scissorTest = false;
  1796. this.viewport = new Vector4( 0, 0, width, height );
  1797. const image = { width: width, height: height, depth: 1 };
  1798. options = Object.assign( {
  1799. generateMipmaps: false,
  1800. internalFormat: null,
  1801. minFilter: LinearFilter,
  1802. depthBuffer: true,
  1803. stencilBuffer: false,
  1804. resolveDepthBuffer: true,
  1805. resolveStencilBuffer: true,
  1806. depthTexture: null,
  1807. samples: 0,
  1808. count: 1
  1809. }, options );
  1810. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1811. texture.flipY = false;
  1812. texture.generateMipmaps = options.generateMipmaps;
  1813. texture.internalFormat = options.internalFormat;
  1814. this.textures = [];
  1815. const count = options.count;
  1816. for ( let i = 0; i < count; i ++ ) {
  1817. this.textures[ i ] = texture.clone();
  1818. this.textures[ i ].isRenderTargetTexture = true;
  1819. }
  1820. this.depthBuffer = options.depthBuffer;
  1821. this.stencilBuffer = options.stencilBuffer;
  1822. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1823. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1824. this.depthTexture = options.depthTexture;
  1825. this.samples = options.samples;
  1826. }
  1827. get texture() {
  1828. return this.textures[ 0 ];
  1829. }
  1830. set texture( value ) {
  1831. this.textures[ 0 ] = value;
  1832. }
  1833. setSize( width, height, depth = 1 ) {
  1834. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1835. this.width = width;
  1836. this.height = height;
  1837. this.depth = depth;
  1838. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1839. this.textures[ i ].image.width = width;
  1840. this.textures[ i ].image.height = height;
  1841. this.textures[ i ].image.depth = depth;
  1842. }
  1843. this.dispose();
  1844. }
  1845. this.viewport.set( 0, 0, width, height );
  1846. this.scissor.set( 0, 0, width, height );
  1847. }
  1848. clone() {
  1849. return new this.constructor().copy( this );
  1850. }
  1851. copy( source ) {
  1852. this.width = source.width;
  1853. this.height = source.height;
  1854. this.depth = source.depth;
  1855. this.scissor.copy( source.scissor );
  1856. this.scissorTest = source.scissorTest;
  1857. this.viewport.copy( source.viewport );
  1858. this.textures.length = 0;
  1859. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1860. this.textures[ i ] = source.textures[ i ].clone();
  1861. this.textures[ i ].isRenderTargetTexture = true;
  1862. }
  1863. // ensure image object is not shared, see #20328
  1864. const image = Object.assign( {}, source.texture.image );
  1865. this.texture.source = new Source( image );
  1866. this.depthBuffer = source.depthBuffer;
  1867. this.stencilBuffer = source.stencilBuffer;
  1868. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1869. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1870. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1871. this.samples = source.samples;
  1872. return this;
  1873. }
  1874. dispose() {
  1875. this.dispatchEvent( { type: 'dispose' } );
  1876. }
  1877. }
  1878. class WebGLRenderTarget extends RenderTarget {
  1879. constructor( width = 1, height = 1, options = {} ) {
  1880. super( width, height, options );
  1881. this.isWebGLRenderTarget = true;
  1882. }
  1883. }
  1884. class DataArrayTexture extends Texture {
  1885. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1886. super( null );
  1887. this.isDataArrayTexture = true;
  1888. this.image = { data, width, height, depth };
  1889. this.magFilter = NearestFilter;
  1890. this.minFilter = NearestFilter;
  1891. this.wrapR = ClampToEdgeWrapping;
  1892. this.generateMipmaps = false;
  1893. this.flipY = false;
  1894. this.unpackAlignment = 1;
  1895. this.layerUpdates = new Set();
  1896. }
  1897. addLayerUpdate( layerIndex ) {
  1898. this.layerUpdates.add( layerIndex );
  1899. }
  1900. clearLayerUpdates() {
  1901. this.layerUpdates.clear();
  1902. }
  1903. }
  1904. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1905. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1906. super( width, height, options );
  1907. this.isWebGLArrayRenderTarget = true;
  1908. this.depth = depth;
  1909. this.texture = new DataArrayTexture( null, width, height, depth );
  1910. this.texture.isRenderTargetTexture = true;
  1911. }
  1912. }
  1913. class Data3DTexture extends Texture {
  1914. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1915. // We're going to add .setXXX() methods for setting properties later.
  1916. // Users can still set in DataTexture3D directly.
  1917. //
  1918. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1919. // texture.anisotropy = 16;
  1920. //
  1921. // See #14839
  1922. super( null );
  1923. this.isData3DTexture = true;
  1924. this.image = { data, width, height, depth };
  1925. this.magFilter = NearestFilter;
  1926. this.minFilter = NearestFilter;
  1927. this.wrapR = ClampToEdgeWrapping;
  1928. this.generateMipmaps = false;
  1929. this.flipY = false;
  1930. this.unpackAlignment = 1;
  1931. }
  1932. }
  1933. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1934. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1935. super( width, height, options );
  1936. this.isWebGL3DRenderTarget = true;
  1937. this.depth = depth;
  1938. this.texture = new Data3DTexture( null, width, height, depth );
  1939. this.texture.isRenderTargetTexture = true;
  1940. }
  1941. }
  1942. class Quaternion {
  1943. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1944. this.isQuaternion = true;
  1945. this._x = x;
  1946. this._y = y;
  1947. this._z = z;
  1948. this._w = w;
  1949. }
  1950. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1951. // fuzz-free, array-based Quaternion SLERP operation
  1952. let x0 = src0[ srcOffset0 + 0 ],
  1953. y0 = src0[ srcOffset0 + 1 ],
  1954. z0 = src0[ srcOffset0 + 2 ],
  1955. w0 = src0[ srcOffset0 + 3 ];
  1956. const x1 = src1[ srcOffset1 + 0 ],
  1957. y1 = src1[ srcOffset1 + 1 ],
  1958. z1 = src1[ srcOffset1 + 2 ],
  1959. w1 = src1[ srcOffset1 + 3 ];
  1960. if ( t === 0 ) {
  1961. dst[ dstOffset + 0 ] = x0;
  1962. dst[ dstOffset + 1 ] = y0;
  1963. dst[ dstOffset + 2 ] = z0;
  1964. dst[ dstOffset + 3 ] = w0;
  1965. return;
  1966. }
  1967. if ( t === 1 ) {
  1968. dst[ dstOffset + 0 ] = x1;
  1969. dst[ dstOffset + 1 ] = y1;
  1970. dst[ dstOffset + 2 ] = z1;
  1971. dst[ dstOffset + 3 ] = w1;
  1972. return;
  1973. }
  1974. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1975. let s = 1 - t;
  1976. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1977. dir = ( cos >= 0 ? 1 : - 1 ),
  1978. sqrSin = 1 - cos * cos;
  1979. // Skip the Slerp for tiny steps to avoid numeric problems:
  1980. if ( sqrSin > Number.EPSILON ) {
  1981. const sin = Math.sqrt( sqrSin ),
  1982. len = Math.atan2( sin, cos * dir );
  1983. s = Math.sin( s * len ) / sin;
  1984. t = Math.sin( t * len ) / sin;
  1985. }
  1986. const tDir = t * dir;
  1987. x0 = x0 * s + x1 * tDir;
  1988. y0 = y0 * s + y1 * tDir;
  1989. z0 = z0 * s + z1 * tDir;
  1990. w0 = w0 * s + w1 * tDir;
  1991. // Normalize in case we just did a lerp:
  1992. if ( s === 1 - t ) {
  1993. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1994. x0 *= f;
  1995. y0 *= f;
  1996. z0 *= f;
  1997. w0 *= f;
  1998. }
  1999. }
  2000. dst[ dstOffset ] = x0;
  2001. dst[ dstOffset + 1 ] = y0;
  2002. dst[ dstOffset + 2 ] = z0;
  2003. dst[ dstOffset + 3 ] = w0;
  2004. }
  2005. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2006. const x0 = src0[ srcOffset0 ];
  2007. const y0 = src0[ srcOffset0 + 1 ];
  2008. const z0 = src0[ srcOffset0 + 2 ];
  2009. const w0 = src0[ srcOffset0 + 3 ];
  2010. const x1 = src1[ srcOffset1 ];
  2011. const y1 = src1[ srcOffset1 + 1 ];
  2012. const z1 = src1[ srcOffset1 + 2 ];
  2013. const w1 = src1[ srcOffset1 + 3 ];
  2014. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2015. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2016. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2017. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2018. return dst;
  2019. }
  2020. get x() {
  2021. return this._x;
  2022. }
  2023. set x( value ) {
  2024. this._x = value;
  2025. this._onChangeCallback();
  2026. }
  2027. get y() {
  2028. return this._y;
  2029. }
  2030. set y( value ) {
  2031. this._y = value;
  2032. this._onChangeCallback();
  2033. }
  2034. get z() {
  2035. return this._z;
  2036. }
  2037. set z( value ) {
  2038. this._z = value;
  2039. this._onChangeCallback();
  2040. }
  2041. get w() {
  2042. return this._w;
  2043. }
  2044. set w( value ) {
  2045. this._w = value;
  2046. this._onChangeCallback();
  2047. }
  2048. set( x, y, z, w ) {
  2049. this._x = x;
  2050. this._y = y;
  2051. this._z = z;
  2052. this._w = w;
  2053. this._onChangeCallback();
  2054. return this;
  2055. }
  2056. clone() {
  2057. return new this.constructor( this._x, this._y, this._z, this._w );
  2058. }
  2059. copy( quaternion ) {
  2060. this._x = quaternion.x;
  2061. this._y = quaternion.y;
  2062. this._z = quaternion.z;
  2063. this._w = quaternion.w;
  2064. this._onChangeCallback();
  2065. return this;
  2066. }
  2067. setFromEuler( euler, update = true ) {
  2068. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2069. // http://www.mathworks.com/matlabcentral/fileexchange/
  2070. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2071. // content/SpinCalc.m
  2072. const cos = Math.cos;
  2073. const sin = Math.sin;
  2074. const c1 = cos( x / 2 );
  2075. const c2 = cos( y / 2 );
  2076. const c3 = cos( z / 2 );
  2077. const s1 = sin( x / 2 );
  2078. const s2 = sin( y / 2 );
  2079. const s3 = sin( z / 2 );
  2080. switch ( order ) {
  2081. case 'XYZ':
  2082. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2083. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2084. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2085. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2086. break;
  2087. case 'YXZ':
  2088. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2089. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2090. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2091. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2092. break;
  2093. case 'ZXY':
  2094. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2095. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2096. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2097. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2098. break;
  2099. case 'ZYX':
  2100. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2101. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2102. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2103. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2104. break;
  2105. case 'YZX':
  2106. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2107. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2108. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2109. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2110. break;
  2111. case 'XZY':
  2112. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2113. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2114. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2115. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2116. break;
  2117. default:
  2118. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2119. }
  2120. if ( update === true ) this._onChangeCallback();
  2121. return this;
  2122. }
  2123. setFromAxisAngle( axis, angle ) {
  2124. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2125. // assumes axis is normalized
  2126. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2127. this._x = axis.x * s;
  2128. this._y = axis.y * s;
  2129. this._z = axis.z * s;
  2130. this._w = Math.cos( halfAngle );
  2131. this._onChangeCallback();
  2132. return this;
  2133. }
  2134. setFromRotationMatrix( m ) {
  2135. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2136. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2137. const te = m.elements,
  2138. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2139. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2140. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2141. trace = m11 + m22 + m33;
  2142. if ( trace > 0 ) {
  2143. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2144. this._w = 0.25 / s;
  2145. this._x = ( m32 - m23 ) * s;
  2146. this._y = ( m13 - m31 ) * s;
  2147. this._z = ( m21 - m12 ) * s;
  2148. } else if ( m11 > m22 && m11 > m33 ) {
  2149. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2150. this._w = ( m32 - m23 ) / s;
  2151. this._x = 0.25 * s;
  2152. this._y = ( m12 + m21 ) / s;
  2153. this._z = ( m13 + m31 ) / s;
  2154. } else if ( m22 > m33 ) {
  2155. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2156. this._w = ( m13 - m31 ) / s;
  2157. this._x = ( m12 + m21 ) / s;
  2158. this._y = 0.25 * s;
  2159. this._z = ( m23 + m32 ) / s;
  2160. } else {
  2161. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2162. this._w = ( m21 - m12 ) / s;
  2163. this._x = ( m13 + m31 ) / s;
  2164. this._y = ( m23 + m32 ) / s;
  2165. this._z = 0.25 * s;
  2166. }
  2167. this._onChangeCallback();
  2168. return this;
  2169. }
  2170. setFromUnitVectors( vFrom, vTo ) {
  2171. // assumes direction vectors vFrom and vTo are normalized
  2172. let r = vFrom.dot( vTo ) + 1;
  2173. if ( r < Number.EPSILON ) {
  2174. // vFrom and vTo point in opposite directions
  2175. r = 0;
  2176. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2177. this._x = - vFrom.y;
  2178. this._y = vFrom.x;
  2179. this._z = 0;
  2180. this._w = r;
  2181. } else {
  2182. this._x = 0;
  2183. this._y = - vFrom.z;
  2184. this._z = vFrom.y;
  2185. this._w = r;
  2186. }
  2187. } else {
  2188. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2189. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2190. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2191. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2192. this._w = r;
  2193. }
  2194. return this.normalize();
  2195. }
  2196. angleTo( q ) {
  2197. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2198. }
  2199. rotateTowards( q, step ) {
  2200. const angle = this.angleTo( q );
  2201. if ( angle === 0 ) return this;
  2202. const t = Math.min( 1, step / angle );
  2203. this.slerp( q, t );
  2204. return this;
  2205. }
  2206. identity() {
  2207. return this.set( 0, 0, 0, 1 );
  2208. }
  2209. invert() {
  2210. // quaternion is assumed to have unit length
  2211. return this.conjugate();
  2212. }
  2213. conjugate() {
  2214. this._x *= - 1;
  2215. this._y *= - 1;
  2216. this._z *= - 1;
  2217. this._onChangeCallback();
  2218. return this;
  2219. }
  2220. dot( v ) {
  2221. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2222. }
  2223. lengthSq() {
  2224. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2225. }
  2226. length() {
  2227. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2228. }
  2229. normalize() {
  2230. let l = this.length();
  2231. if ( l === 0 ) {
  2232. this._x = 0;
  2233. this._y = 0;
  2234. this._z = 0;
  2235. this._w = 1;
  2236. } else {
  2237. l = 1 / l;
  2238. this._x = this._x * l;
  2239. this._y = this._y * l;
  2240. this._z = this._z * l;
  2241. this._w = this._w * l;
  2242. }
  2243. this._onChangeCallback();
  2244. return this;
  2245. }
  2246. multiply( q ) {
  2247. return this.multiplyQuaternions( this, q );
  2248. }
  2249. premultiply( q ) {
  2250. return this.multiplyQuaternions( q, this );
  2251. }
  2252. multiplyQuaternions( a, b ) {
  2253. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2254. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2255. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2256. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2257. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2258. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2259. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2260. this._onChangeCallback();
  2261. return this;
  2262. }
  2263. slerp( qb, t ) {
  2264. if ( t === 0 ) return this;
  2265. if ( t === 1 ) return this.copy( qb );
  2266. const x = this._x, y = this._y, z = this._z, w = this._w;
  2267. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2268. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2269. if ( cosHalfTheta < 0 ) {
  2270. this._w = - qb._w;
  2271. this._x = - qb._x;
  2272. this._y = - qb._y;
  2273. this._z = - qb._z;
  2274. cosHalfTheta = - cosHalfTheta;
  2275. } else {
  2276. this.copy( qb );
  2277. }
  2278. if ( cosHalfTheta >= 1.0 ) {
  2279. this._w = w;
  2280. this._x = x;
  2281. this._y = y;
  2282. this._z = z;
  2283. return this;
  2284. }
  2285. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2286. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2287. const s = 1 - t;
  2288. this._w = s * w + t * this._w;
  2289. this._x = s * x + t * this._x;
  2290. this._y = s * y + t * this._y;
  2291. this._z = s * z + t * this._z;
  2292. this.normalize(); // normalize calls _onChangeCallback()
  2293. return this;
  2294. }
  2295. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2296. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2297. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2298. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2299. this._w = ( w * ratioA + this._w * ratioB );
  2300. this._x = ( x * ratioA + this._x * ratioB );
  2301. this._y = ( y * ratioA + this._y * ratioB );
  2302. this._z = ( z * ratioA + this._z * ratioB );
  2303. this._onChangeCallback();
  2304. return this;
  2305. }
  2306. slerpQuaternions( qa, qb, t ) {
  2307. return this.copy( qa ).slerp( qb, t );
  2308. }
  2309. random() {
  2310. // sets this quaternion to a uniform random unit quaternnion
  2311. // Ken Shoemake
  2312. // Uniform random rotations
  2313. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2314. const theta1 = 2 * Math.PI * Math.random();
  2315. const theta2 = 2 * Math.PI * Math.random();
  2316. const x0 = Math.random();
  2317. const r1 = Math.sqrt( 1 - x0 );
  2318. const r2 = Math.sqrt( x0 );
  2319. return this.set(
  2320. r1 * Math.sin( theta1 ),
  2321. r1 * Math.cos( theta1 ),
  2322. r2 * Math.sin( theta2 ),
  2323. r2 * Math.cos( theta2 ),
  2324. );
  2325. }
  2326. equals( quaternion ) {
  2327. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2328. }
  2329. fromArray( array, offset = 0 ) {
  2330. this._x = array[ offset ];
  2331. this._y = array[ offset + 1 ];
  2332. this._z = array[ offset + 2 ];
  2333. this._w = array[ offset + 3 ];
  2334. this._onChangeCallback();
  2335. return this;
  2336. }
  2337. toArray( array = [], offset = 0 ) {
  2338. array[ offset ] = this._x;
  2339. array[ offset + 1 ] = this._y;
  2340. array[ offset + 2 ] = this._z;
  2341. array[ offset + 3 ] = this._w;
  2342. return array;
  2343. }
  2344. fromBufferAttribute( attribute, index ) {
  2345. this._x = attribute.getX( index );
  2346. this._y = attribute.getY( index );
  2347. this._z = attribute.getZ( index );
  2348. this._w = attribute.getW( index );
  2349. this._onChangeCallback();
  2350. return this;
  2351. }
  2352. toJSON() {
  2353. return this.toArray();
  2354. }
  2355. _onChange( callback ) {
  2356. this._onChangeCallback = callback;
  2357. return this;
  2358. }
  2359. _onChangeCallback() {}
  2360. *[ Symbol.iterator ]() {
  2361. yield this._x;
  2362. yield this._y;
  2363. yield this._z;
  2364. yield this._w;
  2365. }
  2366. }
  2367. class Vector3 {
  2368. constructor( x = 0, y = 0, z = 0 ) {
  2369. Vector3.prototype.isVector3 = true;
  2370. this.x = x;
  2371. this.y = y;
  2372. this.z = z;
  2373. }
  2374. set( x, y, z ) {
  2375. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2376. this.x = x;
  2377. this.y = y;
  2378. this.z = z;
  2379. return this;
  2380. }
  2381. setScalar( scalar ) {
  2382. this.x = scalar;
  2383. this.y = scalar;
  2384. this.z = scalar;
  2385. return this;
  2386. }
  2387. setX( x ) {
  2388. this.x = x;
  2389. return this;
  2390. }
  2391. setY( y ) {
  2392. this.y = y;
  2393. return this;
  2394. }
  2395. setZ( z ) {
  2396. this.z = z;
  2397. return this;
  2398. }
  2399. setComponent( index, value ) {
  2400. switch ( index ) {
  2401. case 0: this.x = value; break;
  2402. case 1: this.y = value; break;
  2403. case 2: this.z = value; break;
  2404. default: throw new Error( 'index is out of range: ' + index );
  2405. }
  2406. return this;
  2407. }
  2408. getComponent( index ) {
  2409. switch ( index ) {
  2410. case 0: return this.x;
  2411. case 1: return this.y;
  2412. case 2: return this.z;
  2413. default: throw new Error( 'index is out of range: ' + index );
  2414. }
  2415. }
  2416. clone() {
  2417. return new this.constructor( this.x, this.y, this.z );
  2418. }
  2419. copy( v ) {
  2420. this.x = v.x;
  2421. this.y = v.y;
  2422. this.z = v.z;
  2423. return this;
  2424. }
  2425. add( v ) {
  2426. this.x += v.x;
  2427. this.y += v.y;
  2428. this.z += v.z;
  2429. return this;
  2430. }
  2431. addScalar( s ) {
  2432. this.x += s;
  2433. this.y += s;
  2434. this.z += s;
  2435. return this;
  2436. }
  2437. addVectors( a, b ) {
  2438. this.x = a.x + b.x;
  2439. this.y = a.y + b.y;
  2440. this.z = a.z + b.z;
  2441. return this;
  2442. }
  2443. addScaledVector( v, s ) {
  2444. this.x += v.x * s;
  2445. this.y += v.y * s;
  2446. this.z += v.z * s;
  2447. return this;
  2448. }
  2449. sub( v ) {
  2450. this.x -= v.x;
  2451. this.y -= v.y;
  2452. this.z -= v.z;
  2453. return this;
  2454. }
  2455. subScalar( s ) {
  2456. this.x -= s;
  2457. this.y -= s;
  2458. this.z -= s;
  2459. return this;
  2460. }
  2461. subVectors( a, b ) {
  2462. this.x = a.x - b.x;
  2463. this.y = a.y - b.y;
  2464. this.z = a.z - b.z;
  2465. return this;
  2466. }
  2467. multiply( v ) {
  2468. this.x *= v.x;
  2469. this.y *= v.y;
  2470. this.z *= v.z;
  2471. return this;
  2472. }
  2473. multiplyScalar( scalar ) {
  2474. this.x *= scalar;
  2475. this.y *= scalar;
  2476. this.z *= scalar;
  2477. return this;
  2478. }
  2479. multiplyVectors( a, b ) {
  2480. this.x = a.x * b.x;
  2481. this.y = a.y * b.y;
  2482. this.z = a.z * b.z;
  2483. return this;
  2484. }
  2485. applyEuler( euler ) {
  2486. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2487. }
  2488. applyAxisAngle( axis, angle ) {
  2489. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2490. }
  2491. applyMatrix3( m ) {
  2492. const x = this.x, y = this.y, z = this.z;
  2493. const e = m.elements;
  2494. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2495. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2496. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2497. return this;
  2498. }
  2499. applyNormalMatrix( m ) {
  2500. return this.applyMatrix3( m ).normalize();
  2501. }
  2502. applyMatrix4( m ) {
  2503. const x = this.x, y = this.y, z = this.z;
  2504. const e = m.elements;
  2505. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2506. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2507. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2508. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2509. return this;
  2510. }
  2511. applyQuaternion( q ) {
  2512. // quaternion q is assumed to have unit length
  2513. const vx = this.x, vy = this.y, vz = this.z;
  2514. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2515. // t = 2 * cross( q.xyz, v );
  2516. const tx = 2 * ( qy * vz - qz * vy );
  2517. const ty = 2 * ( qz * vx - qx * vz );
  2518. const tz = 2 * ( qx * vy - qy * vx );
  2519. // v + q.w * t + cross( q.xyz, t );
  2520. this.x = vx + qw * tx + qy * tz - qz * ty;
  2521. this.y = vy + qw * ty + qz * tx - qx * tz;
  2522. this.z = vz + qw * tz + qx * ty - qy * tx;
  2523. return this;
  2524. }
  2525. project( camera ) {
  2526. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2527. }
  2528. unproject( camera ) {
  2529. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2530. }
  2531. transformDirection( m ) {
  2532. // input: THREE.Matrix4 affine matrix
  2533. // vector interpreted as a direction
  2534. const x = this.x, y = this.y, z = this.z;
  2535. const e = m.elements;
  2536. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2537. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2538. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2539. return this.normalize();
  2540. }
  2541. divide( v ) {
  2542. this.x /= v.x;
  2543. this.y /= v.y;
  2544. this.z /= v.z;
  2545. return this;
  2546. }
  2547. divideScalar( scalar ) {
  2548. return this.multiplyScalar( 1 / scalar );
  2549. }
  2550. min( v ) {
  2551. this.x = Math.min( this.x, v.x );
  2552. this.y = Math.min( this.y, v.y );
  2553. this.z = Math.min( this.z, v.z );
  2554. return this;
  2555. }
  2556. max( v ) {
  2557. this.x = Math.max( this.x, v.x );
  2558. this.y = Math.max( this.y, v.y );
  2559. this.z = Math.max( this.z, v.z );
  2560. return this;
  2561. }
  2562. clamp( min, max ) {
  2563. // assumes min < max, componentwise
  2564. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2565. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2566. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2567. return this;
  2568. }
  2569. clampScalar( minVal, maxVal ) {
  2570. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2571. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2572. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2573. return this;
  2574. }
  2575. clampLength( min, max ) {
  2576. const length = this.length();
  2577. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2578. }
  2579. floor() {
  2580. this.x = Math.floor( this.x );
  2581. this.y = Math.floor( this.y );
  2582. this.z = Math.floor( this.z );
  2583. return this;
  2584. }
  2585. ceil() {
  2586. this.x = Math.ceil( this.x );
  2587. this.y = Math.ceil( this.y );
  2588. this.z = Math.ceil( this.z );
  2589. return this;
  2590. }
  2591. round() {
  2592. this.x = Math.round( this.x );
  2593. this.y = Math.round( this.y );
  2594. this.z = Math.round( this.z );
  2595. return this;
  2596. }
  2597. roundToZero() {
  2598. this.x = Math.trunc( this.x );
  2599. this.y = Math.trunc( this.y );
  2600. this.z = Math.trunc( this.z );
  2601. return this;
  2602. }
  2603. negate() {
  2604. this.x = - this.x;
  2605. this.y = - this.y;
  2606. this.z = - this.z;
  2607. return this;
  2608. }
  2609. dot( v ) {
  2610. return this.x * v.x + this.y * v.y + this.z * v.z;
  2611. }
  2612. // TODO lengthSquared?
  2613. lengthSq() {
  2614. return this.x * this.x + this.y * this.y + this.z * this.z;
  2615. }
  2616. length() {
  2617. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2618. }
  2619. manhattanLength() {
  2620. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2621. }
  2622. normalize() {
  2623. return this.divideScalar( this.length() || 1 );
  2624. }
  2625. setLength( length ) {
  2626. return this.normalize().multiplyScalar( length );
  2627. }
  2628. lerp( v, alpha ) {
  2629. this.x += ( v.x - this.x ) * alpha;
  2630. this.y += ( v.y - this.y ) * alpha;
  2631. this.z += ( v.z - this.z ) * alpha;
  2632. return this;
  2633. }
  2634. lerpVectors( v1, v2, alpha ) {
  2635. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2636. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2637. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2638. return this;
  2639. }
  2640. cross( v ) {
  2641. return this.crossVectors( this, v );
  2642. }
  2643. crossVectors( a, b ) {
  2644. const ax = a.x, ay = a.y, az = a.z;
  2645. const bx = b.x, by = b.y, bz = b.z;
  2646. this.x = ay * bz - az * by;
  2647. this.y = az * bx - ax * bz;
  2648. this.z = ax * by - ay * bx;
  2649. return this;
  2650. }
  2651. projectOnVector( v ) {
  2652. const denominator = v.lengthSq();
  2653. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2654. const scalar = v.dot( this ) / denominator;
  2655. return this.copy( v ).multiplyScalar( scalar );
  2656. }
  2657. projectOnPlane( planeNormal ) {
  2658. _vector$c.copy( this ).projectOnVector( planeNormal );
  2659. return this.sub( _vector$c );
  2660. }
  2661. reflect( normal ) {
  2662. // reflect incident vector off plane orthogonal to normal
  2663. // normal is assumed to have unit length
  2664. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2665. }
  2666. angleTo( v ) {
  2667. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2668. if ( denominator === 0 ) return Math.PI / 2;
  2669. const theta = this.dot( v ) / denominator;
  2670. // clamp, to handle numerical problems
  2671. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2672. }
  2673. distanceTo( v ) {
  2674. return Math.sqrt( this.distanceToSquared( v ) );
  2675. }
  2676. distanceToSquared( v ) {
  2677. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2678. return dx * dx + dy * dy + dz * dz;
  2679. }
  2680. manhattanDistanceTo( v ) {
  2681. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2682. }
  2683. setFromSpherical( s ) {
  2684. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2685. }
  2686. setFromSphericalCoords( radius, phi, theta ) {
  2687. const sinPhiRadius = Math.sin( phi ) * radius;
  2688. this.x = sinPhiRadius * Math.sin( theta );
  2689. this.y = Math.cos( phi ) * radius;
  2690. this.z = sinPhiRadius * Math.cos( theta );
  2691. return this;
  2692. }
  2693. setFromCylindrical( c ) {
  2694. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2695. }
  2696. setFromCylindricalCoords( radius, theta, y ) {
  2697. this.x = radius * Math.sin( theta );
  2698. this.y = y;
  2699. this.z = radius * Math.cos( theta );
  2700. return this;
  2701. }
  2702. setFromMatrixPosition( m ) {
  2703. const e = m.elements;
  2704. this.x = e[ 12 ];
  2705. this.y = e[ 13 ];
  2706. this.z = e[ 14 ];
  2707. return this;
  2708. }
  2709. setFromMatrixScale( m ) {
  2710. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2711. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2712. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2713. this.x = sx;
  2714. this.y = sy;
  2715. this.z = sz;
  2716. return this;
  2717. }
  2718. setFromMatrixColumn( m, index ) {
  2719. return this.fromArray( m.elements, index * 4 );
  2720. }
  2721. setFromMatrix3Column( m, index ) {
  2722. return this.fromArray( m.elements, index * 3 );
  2723. }
  2724. setFromEuler( e ) {
  2725. this.x = e._x;
  2726. this.y = e._y;
  2727. this.z = e._z;
  2728. return this;
  2729. }
  2730. setFromColor( c ) {
  2731. this.x = c.r;
  2732. this.y = c.g;
  2733. this.z = c.b;
  2734. return this;
  2735. }
  2736. equals( v ) {
  2737. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2738. }
  2739. fromArray( array, offset = 0 ) {
  2740. this.x = array[ offset ];
  2741. this.y = array[ offset + 1 ];
  2742. this.z = array[ offset + 2 ];
  2743. return this;
  2744. }
  2745. toArray( array = [], offset = 0 ) {
  2746. array[ offset ] = this.x;
  2747. array[ offset + 1 ] = this.y;
  2748. array[ offset + 2 ] = this.z;
  2749. return array;
  2750. }
  2751. fromBufferAttribute( attribute, index ) {
  2752. this.x = attribute.getX( index );
  2753. this.y = attribute.getY( index );
  2754. this.z = attribute.getZ( index );
  2755. return this;
  2756. }
  2757. random() {
  2758. this.x = Math.random();
  2759. this.y = Math.random();
  2760. this.z = Math.random();
  2761. return this;
  2762. }
  2763. randomDirection() {
  2764. // https://mathworld.wolfram.com/SpherePointPicking.html
  2765. const theta = Math.random() * Math.PI * 2;
  2766. const u = Math.random() * 2 - 1;
  2767. const c = Math.sqrt( 1 - u * u );
  2768. this.x = c * Math.cos( theta );
  2769. this.y = u;
  2770. this.z = c * Math.sin( theta );
  2771. return this;
  2772. }
  2773. *[ Symbol.iterator ]() {
  2774. yield this.x;
  2775. yield this.y;
  2776. yield this.z;
  2777. }
  2778. }
  2779. const _vector$c = /*@__PURE__*/ new Vector3();
  2780. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2781. class Box3 {
  2782. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2783. this.isBox3 = true;
  2784. this.min = min;
  2785. this.max = max;
  2786. }
  2787. set( min, max ) {
  2788. this.min.copy( min );
  2789. this.max.copy( max );
  2790. return this;
  2791. }
  2792. setFromArray( array ) {
  2793. this.makeEmpty();
  2794. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2795. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2796. }
  2797. return this;
  2798. }
  2799. setFromBufferAttribute( attribute ) {
  2800. this.makeEmpty();
  2801. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2802. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2803. }
  2804. return this;
  2805. }
  2806. setFromPoints( points ) {
  2807. this.makeEmpty();
  2808. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2809. this.expandByPoint( points[ i ] );
  2810. }
  2811. return this;
  2812. }
  2813. setFromCenterAndSize( center, size ) {
  2814. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2815. this.min.copy( center ).sub( halfSize );
  2816. this.max.copy( center ).add( halfSize );
  2817. return this;
  2818. }
  2819. setFromObject( object, precise = false ) {
  2820. this.makeEmpty();
  2821. return this.expandByObject( object, precise );
  2822. }
  2823. clone() {
  2824. return new this.constructor().copy( this );
  2825. }
  2826. copy( box ) {
  2827. this.min.copy( box.min );
  2828. this.max.copy( box.max );
  2829. return this;
  2830. }
  2831. makeEmpty() {
  2832. this.min.x = this.min.y = this.min.z = + Infinity;
  2833. this.max.x = this.max.y = this.max.z = - Infinity;
  2834. return this;
  2835. }
  2836. isEmpty() {
  2837. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2838. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2839. }
  2840. getCenter( target ) {
  2841. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2842. }
  2843. getSize( target ) {
  2844. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2845. }
  2846. expandByPoint( point ) {
  2847. this.min.min( point );
  2848. this.max.max( point );
  2849. return this;
  2850. }
  2851. expandByVector( vector ) {
  2852. this.min.sub( vector );
  2853. this.max.add( vector );
  2854. return this;
  2855. }
  2856. expandByScalar( scalar ) {
  2857. this.min.addScalar( - scalar );
  2858. this.max.addScalar( scalar );
  2859. return this;
  2860. }
  2861. expandByObject( object, precise = false ) {
  2862. // Computes the world-axis-aligned bounding box of an object (including its children),
  2863. // accounting for both the object's, and children's, world transforms
  2864. object.updateWorldMatrix( false, false );
  2865. const geometry = object.geometry;
  2866. if ( geometry !== undefined ) {
  2867. const positionAttribute = geometry.getAttribute( 'position' );
  2868. // precise AABB computation based on vertex data requires at least a position attribute.
  2869. // instancing isn't supported so far and uses the normal (conservative) code path.
  2870. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2871. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2872. if ( object.isMesh === true ) {
  2873. object.getVertexPosition( i, _vector$b );
  2874. } else {
  2875. _vector$b.fromBufferAttribute( positionAttribute, i );
  2876. }
  2877. _vector$b.applyMatrix4( object.matrixWorld );
  2878. this.expandByPoint( _vector$b );
  2879. }
  2880. } else {
  2881. if ( object.boundingBox !== undefined ) {
  2882. // object-level bounding box
  2883. if ( object.boundingBox === null ) {
  2884. object.computeBoundingBox();
  2885. }
  2886. _box$4.copy( object.boundingBox );
  2887. } else {
  2888. // geometry-level bounding box
  2889. if ( geometry.boundingBox === null ) {
  2890. geometry.computeBoundingBox();
  2891. }
  2892. _box$4.copy( geometry.boundingBox );
  2893. }
  2894. _box$4.applyMatrix4( object.matrixWorld );
  2895. this.union( _box$4 );
  2896. }
  2897. }
  2898. const children = object.children;
  2899. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2900. this.expandByObject( children[ i ], precise );
  2901. }
  2902. return this;
  2903. }
  2904. containsPoint( point ) {
  2905. return point.x < this.min.x || point.x > this.max.x ||
  2906. point.y < this.min.y || point.y > this.max.y ||
  2907. point.z < this.min.z || point.z > this.max.z ? false : true;
  2908. }
  2909. containsBox( box ) {
  2910. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2911. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2912. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2913. }
  2914. getParameter( point, target ) {
  2915. // This can potentially have a divide by zero if the box
  2916. // has a size dimension of 0.
  2917. return target.set(
  2918. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2919. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2920. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2921. );
  2922. }
  2923. intersectsBox( box ) {
  2924. // using 6 splitting planes to rule out intersections.
  2925. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2926. box.max.y < this.min.y || box.min.y > this.max.y ||
  2927. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2928. }
  2929. intersectsSphere( sphere ) {
  2930. // Find the point on the AABB closest to the sphere center.
  2931. this.clampPoint( sphere.center, _vector$b );
  2932. // If that point is inside the sphere, the AABB and sphere intersect.
  2933. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2934. }
  2935. intersectsPlane( plane ) {
  2936. // We compute the minimum and maximum dot product values. If those values
  2937. // are on the same side (back or front) of the plane, then there is no intersection.
  2938. let min, max;
  2939. if ( plane.normal.x > 0 ) {
  2940. min = plane.normal.x * this.min.x;
  2941. max = plane.normal.x * this.max.x;
  2942. } else {
  2943. min = plane.normal.x * this.max.x;
  2944. max = plane.normal.x * this.min.x;
  2945. }
  2946. if ( plane.normal.y > 0 ) {
  2947. min += plane.normal.y * this.min.y;
  2948. max += plane.normal.y * this.max.y;
  2949. } else {
  2950. min += plane.normal.y * this.max.y;
  2951. max += plane.normal.y * this.min.y;
  2952. }
  2953. if ( plane.normal.z > 0 ) {
  2954. min += plane.normal.z * this.min.z;
  2955. max += plane.normal.z * this.max.z;
  2956. } else {
  2957. min += plane.normal.z * this.max.z;
  2958. max += plane.normal.z * this.min.z;
  2959. }
  2960. return ( min <= - plane.constant && max >= - plane.constant );
  2961. }
  2962. intersectsTriangle( triangle ) {
  2963. if ( this.isEmpty() ) {
  2964. return false;
  2965. }
  2966. // compute box center and extents
  2967. this.getCenter( _center );
  2968. _extents.subVectors( this.max, _center );
  2969. // translate triangle to aabb origin
  2970. _v0$2.subVectors( triangle.a, _center );
  2971. _v1$7.subVectors( triangle.b, _center );
  2972. _v2$4.subVectors( triangle.c, _center );
  2973. // compute edge vectors for triangle
  2974. _f0.subVectors( _v1$7, _v0$2 );
  2975. _f1.subVectors( _v2$4, _v1$7 );
  2976. _f2.subVectors( _v0$2, _v2$4 );
  2977. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2978. // 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
  2979. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2980. let axes = [
  2981. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2982. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2983. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2984. ];
  2985. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2986. return false;
  2987. }
  2988. // test 3 face normals from the aabb
  2989. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2990. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2991. return false;
  2992. }
  2993. // finally testing the face normal of the triangle
  2994. // use already existing triangle edge vectors here
  2995. _triangleNormal.crossVectors( _f0, _f1 );
  2996. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2997. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2998. }
  2999. clampPoint( point, target ) {
  3000. return target.copy( point ).clamp( this.min, this.max );
  3001. }
  3002. distanceToPoint( point ) {
  3003. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3004. }
  3005. getBoundingSphere( target ) {
  3006. if ( this.isEmpty() ) {
  3007. target.makeEmpty();
  3008. } else {
  3009. this.getCenter( target.center );
  3010. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3011. }
  3012. return target;
  3013. }
  3014. intersect( box ) {
  3015. this.min.max( box.min );
  3016. this.max.min( box.max );
  3017. // 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.
  3018. if ( this.isEmpty() ) this.makeEmpty();
  3019. return this;
  3020. }
  3021. union( box ) {
  3022. this.min.min( box.min );
  3023. this.max.max( box.max );
  3024. return this;
  3025. }
  3026. applyMatrix4( matrix ) {
  3027. // transform of empty box is an empty box.
  3028. if ( this.isEmpty() ) return this;
  3029. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3030. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3031. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3032. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3033. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3034. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3035. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3036. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3037. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3038. this.setFromPoints( _points );
  3039. return this;
  3040. }
  3041. translate( offset ) {
  3042. this.min.add( offset );
  3043. this.max.add( offset );
  3044. return this;
  3045. }
  3046. equals( box ) {
  3047. return box.min.equals( this.min ) && box.max.equals( this.max );
  3048. }
  3049. }
  3050. const _points = [
  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. /*@__PURE__*/ new Vector3(),
  3058. /*@__PURE__*/ new Vector3()
  3059. ];
  3060. const _vector$b = /*@__PURE__*/ new Vector3();
  3061. const _box$4 = /*@__PURE__*/ new Box3();
  3062. // triangle centered vertices
  3063. const _v0$2 = /*@__PURE__*/ new Vector3();
  3064. const _v1$7 = /*@__PURE__*/ new Vector3();
  3065. const _v2$4 = /*@__PURE__*/ new Vector3();
  3066. // triangle edge vectors
  3067. const _f0 = /*@__PURE__*/ new Vector3();
  3068. const _f1 = /*@__PURE__*/ new Vector3();
  3069. const _f2 = /*@__PURE__*/ new Vector3();
  3070. const _center = /*@__PURE__*/ new Vector3();
  3071. const _extents = /*@__PURE__*/ new Vector3();
  3072. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3073. const _testAxis = /*@__PURE__*/ new Vector3();
  3074. function satForAxes( axes, v0, v1, v2, extents ) {
  3075. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3076. _testAxis.fromArray( axes, i );
  3077. // project the aabb onto the separating axis
  3078. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3079. // project all 3 vertices of the triangle onto the separating axis
  3080. const p0 = v0.dot( _testAxis );
  3081. const p1 = v1.dot( _testAxis );
  3082. const p2 = v2.dot( _testAxis );
  3083. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3084. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3085. // points of the projected triangle are outside the projected half-length of the aabb
  3086. // the axis is separating and we can exit
  3087. return false;
  3088. }
  3089. }
  3090. return true;
  3091. }
  3092. const _box$3 = /*@__PURE__*/ new Box3();
  3093. const _v1$6 = /*@__PURE__*/ new Vector3();
  3094. const _v2$3 = /*@__PURE__*/ new Vector3();
  3095. class Sphere {
  3096. constructor( center = new Vector3(), radius = - 1 ) {
  3097. this.isSphere = true;
  3098. this.center = center;
  3099. this.radius = radius;
  3100. }
  3101. set( center, radius ) {
  3102. this.center.copy( center );
  3103. this.radius = radius;
  3104. return this;
  3105. }
  3106. setFromPoints( points, optionalCenter ) {
  3107. const center = this.center;
  3108. if ( optionalCenter !== undefined ) {
  3109. center.copy( optionalCenter );
  3110. } else {
  3111. _box$3.setFromPoints( points ).getCenter( center );
  3112. }
  3113. let maxRadiusSq = 0;
  3114. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3115. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3116. }
  3117. this.radius = Math.sqrt( maxRadiusSq );
  3118. return this;
  3119. }
  3120. copy( sphere ) {
  3121. this.center.copy( sphere.center );
  3122. this.radius = sphere.radius;
  3123. return this;
  3124. }
  3125. isEmpty() {
  3126. return ( this.radius < 0 );
  3127. }
  3128. makeEmpty() {
  3129. this.center.set( 0, 0, 0 );
  3130. this.radius = - 1;
  3131. return this;
  3132. }
  3133. containsPoint( point ) {
  3134. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3135. }
  3136. distanceToPoint( point ) {
  3137. return ( point.distanceTo( this.center ) - this.radius );
  3138. }
  3139. intersectsSphere( sphere ) {
  3140. const radiusSum = this.radius + sphere.radius;
  3141. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3142. }
  3143. intersectsBox( box ) {
  3144. return box.intersectsSphere( this );
  3145. }
  3146. intersectsPlane( plane ) {
  3147. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3148. }
  3149. clampPoint( point, target ) {
  3150. const deltaLengthSq = this.center.distanceToSquared( point );
  3151. target.copy( point );
  3152. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3153. target.sub( this.center ).normalize();
  3154. target.multiplyScalar( this.radius ).add( this.center );
  3155. }
  3156. return target;
  3157. }
  3158. getBoundingBox( target ) {
  3159. if ( this.isEmpty() ) {
  3160. // Empty sphere produces empty bounding box
  3161. target.makeEmpty();
  3162. return target;
  3163. }
  3164. target.set( this.center, this.center );
  3165. target.expandByScalar( this.radius );
  3166. return target;
  3167. }
  3168. applyMatrix4( matrix ) {
  3169. this.center.applyMatrix4( matrix );
  3170. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3171. return this;
  3172. }
  3173. translate( offset ) {
  3174. this.center.add( offset );
  3175. return this;
  3176. }
  3177. expandByPoint( point ) {
  3178. if ( this.isEmpty() ) {
  3179. this.center.copy( point );
  3180. this.radius = 0;
  3181. return this;
  3182. }
  3183. _v1$6.subVectors( point, this.center );
  3184. const lengthSq = _v1$6.lengthSq();
  3185. if ( lengthSq > ( this.radius * this.radius ) ) {
  3186. // calculate the minimal sphere
  3187. const length = Math.sqrt( lengthSq );
  3188. const delta = ( length - this.radius ) * 0.5;
  3189. this.center.addScaledVector( _v1$6, delta / length );
  3190. this.radius += delta;
  3191. }
  3192. return this;
  3193. }
  3194. union( sphere ) {
  3195. if ( sphere.isEmpty() ) {
  3196. return this;
  3197. }
  3198. if ( this.isEmpty() ) {
  3199. this.copy( sphere );
  3200. return this;
  3201. }
  3202. if ( this.center.equals( sphere.center ) === true ) {
  3203. this.radius = Math.max( this.radius, sphere.radius );
  3204. } else {
  3205. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3206. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3207. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3208. }
  3209. return this;
  3210. }
  3211. equals( sphere ) {
  3212. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3213. }
  3214. clone() {
  3215. return new this.constructor().copy( this );
  3216. }
  3217. }
  3218. const _vector$a = /*@__PURE__*/ new Vector3();
  3219. const _segCenter = /*@__PURE__*/ new Vector3();
  3220. const _segDir = /*@__PURE__*/ new Vector3();
  3221. const _diff = /*@__PURE__*/ new Vector3();
  3222. const _edge1 = /*@__PURE__*/ new Vector3();
  3223. const _edge2 = /*@__PURE__*/ new Vector3();
  3224. const _normal$2 = /*@__PURE__*/ new Vector3();
  3225. class Ray {
  3226. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3227. this.origin = origin;
  3228. this.direction = direction;
  3229. }
  3230. set( origin, direction ) {
  3231. this.origin.copy( origin );
  3232. this.direction.copy( direction );
  3233. return this;
  3234. }
  3235. copy( ray ) {
  3236. this.origin.copy( ray.origin );
  3237. this.direction.copy( ray.direction );
  3238. return this;
  3239. }
  3240. at( t, target ) {
  3241. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3242. }
  3243. lookAt( v ) {
  3244. this.direction.copy( v ).sub( this.origin ).normalize();
  3245. return this;
  3246. }
  3247. recast( t ) {
  3248. this.origin.copy( this.at( t, _vector$a ) );
  3249. return this;
  3250. }
  3251. closestPointToPoint( point, target ) {
  3252. target.subVectors( point, this.origin );
  3253. const directionDistance = target.dot( this.direction );
  3254. if ( directionDistance < 0 ) {
  3255. return target.copy( this.origin );
  3256. }
  3257. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3258. }
  3259. distanceToPoint( point ) {
  3260. return Math.sqrt( this.distanceSqToPoint( point ) );
  3261. }
  3262. distanceSqToPoint( point ) {
  3263. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3264. // point behind the ray
  3265. if ( directionDistance < 0 ) {
  3266. return this.origin.distanceToSquared( point );
  3267. }
  3268. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3269. return _vector$a.distanceToSquared( point );
  3270. }
  3271. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3272. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3273. // It returns the min distance between the ray and the segment
  3274. // defined by v0 and v1
  3275. // It can also set two optional targets :
  3276. // - The closest point on the ray
  3277. // - The closest point on the segment
  3278. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3279. _segDir.copy( v1 ).sub( v0 ).normalize();
  3280. _diff.copy( this.origin ).sub( _segCenter );
  3281. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3282. const a01 = - this.direction.dot( _segDir );
  3283. const b0 = _diff.dot( this.direction );
  3284. const b1 = - _diff.dot( _segDir );
  3285. const c = _diff.lengthSq();
  3286. const det = Math.abs( 1 - a01 * a01 );
  3287. let s0, s1, sqrDist, extDet;
  3288. if ( det > 0 ) {
  3289. // The ray and segment are not parallel.
  3290. s0 = a01 * b1 - b0;
  3291. s1 = a01 * b0 - b1;
  3292. extDet = segExtent * det;
  3293. if ( s0 >= 0 ) {
  3294. if ( s1 >= - extDet ) {
  3295. if ( s1 <= extDet ) {
  3296. // region 0
  3297. // Minimum at interior points of ray and segment.
  3298. const invDet = 1 / det;
  3299. s0 *= invDet;
  3300. s1 *= invDet;
  3301. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3302. } else {
  3303. // region 1
  3304. s1 = segExtent;
  3305. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3306. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3307. }
  3308. } else {
  3309. // region 5
  3310. s1 = - segExtent;
  3311. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3312. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3313. }
  3314. } else {
  3315. if ( s1 <= - extDet ) {
  3316. // region 4
  3317. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3318. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3319. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3320. } else if ( s1 <= extDet ) {
  3321. // region 3
  3322. s0 = 0;
  3323. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3324. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3325. } else {
  3326. // region 2
  3327. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3328. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3329. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3330. }
  3331. }
  3332. } else {
  3333. // Ray and segment are parallel.
  3334. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3335. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3336. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3337. }
  3338. if ( optionalPointOnRay ) {
  3339. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3340. }
  3341. if ( optionalPointOnSegment ) {
  3342. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3343. }
  3344. return sqrDist;
  3345. }
  3346. intersectSphere( sphere, target ) {
  3347. _vector$a.subVectors( sphere.center, this.origin );
  3348. const tca = _vector$a.dot( this.direction );
  3349. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3350. const radius2 = sphere.radius * sphere.radius;
  3351. if ( d2 > radius2 ) return null;
  3352. const thc = Math.sqrt( radius2 - d2 );
  3353. // t0 = first intersect point - entrance on front of sphere
  3354. const t0 = tca - thc;
  3355. // t1 = second intersect point - exit point on back of sphere
  3356. const t1 = tca + thc;
  3357. // test to see if t1 is behind the ray - if so, return null
  3358. if ( t1 < 0 ) return null;
  3359. // test to see if t0 is behind the ray:
  3360. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3361. // in order to always return an intersect point that is in front of the ray.
  3362. if ( t0 < 0 ) return this.at( t1, target );
  3363. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3364. return this.at( t0, target );
  3365. }
  3366. intersectsSphere( sphere ) {
  3367. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3368. }
  3369. distanceToPlane( plane ) {
  3370. const denominator = plane.normal.dot( this.direction );
  3371. if ( denominator === 0 ) {
  3372. // line is coplanar, return origin
  3373. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3374. return 0;
  3375. }
  3376. // Null is preferable to undefined since undefined means.... it is undefined
  3377. return null;
  3378. }
  3379. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3380. // Return if the ray never intersects the plane
  3381. return t >= 0 ? t : null;
  3382. }
  3383. intersectPlane( plane, target ) {
  3384. const t = this.distanceToPlane( plane );
  3385. if ( t === null ) {
  3386. return null;
  3387. }
  3388. return this.at( t, target );
  3389. }
  3390. intersectsPlane( plane ) {
  3391. // check if the ray lies on the plane first
  3392. const distToPoint = plane.distanceToPoint( this.origin );
  3393. if ( distToPoint === 0 ) {
  3394. return true;
  3395. }
  3396. const denominator = plane.normal.dot( this.direction );
  3397. if ( denominator * distToPoint < 0 ) {
  3398. return true;
  3399. }
  3400. // ray origin is behind the plane (and is pointing behind it)
  3401. return false;
  3402. }
  3403. intersectBox( box, target ) {
  3404. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3405. const invdirx = 1 / this.direction.x,
  3406. invdiry = 1 / this.direction.y,
  3407. invdirz = 1 / this.direction.z;
  3408. const origin = this.origin;
  3409. if ( invdirx >= 0 ) {
  3410. tmin = ( box.min.x - origin.x ) * invdirx;
  3411. tmax = ( box.max.x - origin.x ) * invdirx;
  3412. } else {
  3413. tmin = ( box.max.x - origin.x ) * invdirx;
  3414. tmax = ( box.min.x - origin.x ) * invdirx;
  3415. }
  3416. if ( invdiry >= 0 ) {
  3417. tymin = ( box.min.y - origin.y ) * invdiry;
  3418. tymax = ( box.max.y - origin.y ) * invdiry;
  3419. } else {
  3420. tymin = ( box.max.y - origin.y ) * invdiry;
  3421. tymax = ( box.min.y - origin.y ) * invdiry;
  3422. }
  3423. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3424. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3425. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3426. if ( invdirz >= 0 ) {
  3427. tzmin = ( box.min.z - origin.z ) * invdirz;
  3428. tzmax = ( box.max.z - origin.z ) * invdirz;
  3429. } else {
  3430. tzmin = ( box.max.z - origin.z ) * invdirz;
  3431. tzmax = ( box.min.z - origin.z ) * invdirz;
  3432. }
  3433. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3434. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3435. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3436. //return point closest to the ray (positive side)
  3437. if ( tmax < 0 ) return null;
  3438. return this.at( tmin >= 0 ? tmin : tmax, target );
  3439. }
  3440. intersectsBox( box ) {
  3441. return this.intersectBox( box, _vector$a ) !== null;
  3442. }
  3443. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3444. // Compute the offset origin, edges, and normal.
  3445. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3446. _edge1.subVectors( b, a );
  3447. _edge2.subVectors( c, a );
  3448. _normal$2.crossVectors( _edge1, _edge2 );
  3449. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3450. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3451. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3452. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3453. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3454. let DdN = this.direction.dot( _normal$2 );
  3455. let sign;
  3456. if ( DdN > 0 ) {
  3457. if ( backfaceCulling ) return null;
  3458. sign = 1;
  3459. } else if ( DdN < 0 ) {
  3460. sign = - 1;
  3461. DdN = - DdN;
  3462. } else {
  3463. return null;
  3464. }
  3465. _diff.subVectors( this.origin, a );
  3466. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3467. // b1 < 0, no intersection
  3468. if ( DdQxE2 < 0 ) {
  3469. return null;
  3470. }
  3471. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3472. // b2 < 0, no intersection
  3473. if ( DdE1xQ < 0 ) {
  3474. return null;
  3475. }
  3476. // b1+b2 > 1, no intersection
  3477. if ( DdQxE2 + DdE1xQ > DdN ) {
  3478. return null;
  3479. }
  3480. // Line intersects triangle, check if ray does.
  3481. const QdN = - sign * _diff.dot( _normal$2 );
  3482. // t < 0, no intersection
  3483. if ( QdN < 0 ) {
  3484. return null;
  3485. }
  3486. // Ray intersects triangle.
  3487. return this.at( QdN / DdN, target );
  3488. }
  3489. applyMatrix4( matrix4 ) {
  3490. this.origin.applyMatrix4( matrix4 );
  3491. this.direction.transformDirection( matrix4 );
  3492. return this;
  3493. }
  3494. equals( ray ) {
  3495. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3496. }
  3497. clone() {
  3498. return new this.constructor().copy( this );
  3499. }
  3500. }
  3501. class Matrix4 {
  3502. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3503. Matrix4.prototype.isMatrix4 = true;
  3504. this.elements = [
  3505. 1, 0, 0, 0,
  3506. 0, 1, 0, 0,
  3507. 0, 0, 1, 0,
  3508. 0, 0, 0, 1
  3509. ];
  3510. if ( n11 !== undefined ) {
  3511. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3512. }
  3513. }
  3514. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3515. const te = this.elements;
  3516. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3517. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3518. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3519. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3520. return this;
  3521. }
  3522. identity() {
  3523. this.set(
  3524. 1, 0, 0, 0,
  3525. 0, 1, 0, 0,
  3526. 0, 0, 1, 0,
  3527. 0, 0, 0, 1
  3528. );
  3529. return this;
  3530. }
  3531. clone() {
  3532. return new Matrix4().fromArray( this.elements );
  3533. }
  3534. copy( m ) {
  3535. const te = this.elements;
  3536. const me = m.elements;
  3537. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3538. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3539. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3540. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3541. return this;
  3542. }
  3543. copyPosition( m ) {
  3544. const te = this.elements, me = m.elements;
  3545. te[ 12 ] = me[ 12 ];
  3546. te[ 13 ] = me[ 13 ];
  3547. te[ 14 ] = me[ 14 ];
  3548. return this;
  3549. }
  3550. setFromMatrix3( m ) {
  3551. const me = m.elements;
  3552. this.set(
  3553. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3554. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3555. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3556. 0, 0, 0, 1
  3557. );
  3558. return this;
  3559. }
  3560. extractBasis( xAxis, yAxis, zAxis ) {
  3561. xAxis.setFromMatrixColumn( this, 0 );
  3562. yAxis.setFromMatrixColumn( this, 1 );
  3563. zAxis.setFromMatrixColumn( this, 2 );
  3564. return this;
  3565. }
  3566. makeBasis( xAxis, yAxis, zAxis ) {
  3567. this.set(
  3568. xAxis.x, yAxis.x, zAxis.x, 0,
  3569. xAxis.y, yAxis.y, zAxis.y, 0,
  3570. xAxis.z, yAxis.z, zAxis.z, 0,
  3571. 0, 0, 0, 1
  3572. );
  3573. return this;
  3574. }
  3575. extractRotation( m ) {
  3576. // this method does not support reflection matrices
  3577. const te = this.elements;
  3578. const me = m.elements;
  3579. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3580. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3581. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3582. te[ 0 ] = me[ 0 ] * scaleX;
  3583. te[ 1 ] = me[ 1 ] * scaleX;
  3584. te[ 2 ] = me[ 2 ] * scaleX;
  3585. te[ 3 ] = 0;
  3586. te[ 4 ] = me[ 4 ] * scaleY;
  3587. te[ 5 ] = me[ 5 ] * scaleY;
  3588. te[ 6 ] = me[ 6 ] * scaleY;
  3589. te[ 7 ] = 0;
  3590. te[ 8 ] = me[ 8 ] * scaleZ;
  3591. te[ 9 ] = me[ 9 ] * scaleZ;
  3592. te[ 10 ] = me[ 10 ] * scaleZ;
  3593. te[ 11 ] = 0;
  3594. te[ 12 ] = 0;
  3595. te[ 13 ] = 0;
  3596. te[ 14 ] = 0;
  3597. te[ 15 ] = 1;
  3598. return this;
  3599. }
  3600. makeRotationFromEuler( euler ) {
  3601. const te = this.elements;
  3602. const x = euler.x, y = euler.y, z = euler.z;
  3603. const a = Math.cos( x ), b = Math.sin( x );
  3604. const c = Math.cos( y ), d = Math.sin( y );
  3605. const e = Math.cos( z ), f = Math.sin( z );
  3606. if ( euler.order === 'XYZ' ) {
  3607. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3608. te[ 0 ] = c * e;
  3609. te[ 4 ] = - c * f;
  3610. te[ 8 ] = d;
  3611. te[ 1 ] = af + be * d;
  3612. te[ 5 ] = ae - bf * d;
  3613. te[ 9 ] = - b * c;
  3614. te[ 2 ] = bf - ae * d;
  3615. te[ 6 ] = be + af * d;
  3616. te[ 10 ] = a * c;
  3617. } else if ( euler.order === 'YXZ' ) {
  3618. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3619. te[ 0 ] = ce + df * b;
  3620. te[ 4 ] = de * b - cf;
  3621. te[ 8 ] = a * d;
  3622. te[ 1 ] = a * f;
  3623. te[ 5 ] = a * e;
  3624. te[ 9 ] = - b;
  3625. te[ 2 ] = cf * b - de;
  3626. te[ 6 ] = df + ce * b;
  3627. te[ 10 ] = a * c;
  3628. } else if ( euler.order === 'ZXY' ) {
  3629. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3630. te[ 0 ] = ce - df * b;
  3631. te[ 4 ] = - a * f;
  3632. te[ 8 ] = de + cf * b;
  3633. te[ 1 ] = cf + de * b;
  3634. te[ 5 ] = a * e;
  3635. te[ 9 ] = df - ce * b;
  3636. te[ 2 ] = - a * d;
  3637. te[ 6 ] = b;
  3638. te[ 10 ] = a * c;
  3639. } else if ( euler.order === 'ZYX' ) {
  3640. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3641. te[ 0 ] = c * e;
  3642. te[ 4 ] = be * d - af;
  3643. te[ 8 ] = ae * d + bf;
  3644. te[ 1 ] = c * f;
  3645. te[ 5 ] = bf * d + ae;
  3646. te[ 9 ] = af * d - be;
  3647. te[ 2 ] = - d;
  3648. te[ 6 ] = b * c;
  3649. te[ 10 ] = a * c;
  3650. } else if ( euler.order === 'YZX' ) {
  3651. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3652. te[ 0 ] = c * e;
  3653. te[ 4 ] = bd - ac * f;
  3654. te[ 8 ] = bc * f + ad;
  3655. te[ 1 ] = f;
  3656. te[ 5 ] = a * e;
  3657. te[ 9 ] = - b * e;
  3658. te[ 2 ] = - d * e;
  3659. te[ 6 ] = ad * f + bc;
  3660. te[ 10 ] = ac - bd * f;
  3661. } else if ( euler.order === 'XZY' ) {
  3662. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3663. te[ 0 ] = c * e;
  3664. te[ 4 ] = - f;
  3665. te[ 8 ] = d * e;
  3666. te[ 1 ] = ac * f + bd;
  3667. te[ 5 ] = a * e;
  3668. te[ 9 ] = ad * f - bc;
  3669. te[ 2 ] = bc * f - ad;
  3670. te[ 6 ] = b * e;
  3671. te[ 10 ] = bd * f + ac;
  3672. }
  3673. // bottom row
  3674. te[ 3 ] = 0;
  3675. te[ 7 ] = 0;
  3676. te[ 11 ] = 0;
  3677. // last column
  3678. te[ 12 ] = 0;
  3679. te[ 13 ] = 0;
  3680. te[ 14 ] = 0;
  3681. te[ 15 ] = 1;
  3682. return this;
  3683. }
  3684. makeRotationFromQuaternion( q ) {
  3685. return this.compose( _zero, q, _one );
  3686. }
  3687. lookAt( eye, target, up ) {
  3688. const te = this.elements;
  3689. _z.subVectors( eye, target );
  3690. if ( _z.lengthSq() === 0 ) {
  3691. // eye and target are in the same position
  3692. _z.z = 1;
  3693. }
  3694. _z.normalize();
  3695. _x.crossVectors( up, _z );
  3696. if ( _x.lengthSq() === 0 ) {
  3697. // up and z are parallel
  3698. if ( Math.abs( up.z ) === 1 ) {
  3699. _z.x += 0.0001;
  3700. } else {
  3701. _z.z += 0.0001;
  3702. }
  3703. _z.normalize();
  3704. _x.crossVectors( up, _z );
  3705. }
  3706. _x.normalize();
  3707. _y.crossVectors( _z, _x );
  3708. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3709. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3710. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3711. return this;
  3712. }
  3713. multiply( m ) {
  3714. return this.multiplyMatrices( this, m );
  3715. }
  3716. premultiply( m ) {
  3717. return this.multiplyMatrices( m, this );
  3718. }
  3719. multiplyMatrices( a, b ) {
  3720. const ae = a.elements;
  3721. const be = b.elements;
  3722. const te = this.elements;
  3723. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3724. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3725. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3726. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3727. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3728. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3729. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3730. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3731. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3732. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3733. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3734. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3735. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3736. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3737. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3738. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3739. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3740. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3741. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3742. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3743. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3744. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3745. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3746. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3747. return this;
  3748. }
  3749. multiplyScalar( s ) {
  3750. const te = this.elements;
  3751. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3752. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3753. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3754. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3755. return this;
  3756. }
  3757. determinant() {
  3758. const te = this.elements;
  3759. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3760. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3761. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3762. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3763. //TODO: make this more efficient
  3764. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3765. return (
  3766. n41 * (
  3767. + n14 * n23 * n32
  3768. - n13 * n24 * n32
  3769. - n14 * n22 * n33
  3770. + n12 * n24 * n33
  3771. + n13 * n22 * n34
  3772. - n12 * n23 * n34
  3773. ) +
  3774. n42 * (
  3775. + n11 * n23 * n34
  3776. - n11 * n24 * n33
  3777. + n14 * n21 * n33
  3778. - n13 * n21 * n34
  3779. + n13 * n24 * n31
  3780. - n14 * n23 * n31
  3781. ) +
  3782. n43 * (
  3783. + n11 * n24 * n32
  3784. - n11 * n22 * n34
  3785. - n14 * n21 * n32
  3786. + n12 * n21 * n34
  3787. + n14 * n22 * n31
  3788. - n12 * n24 * n31
  3789. ) +
  3790. n44 * (
  3791. - n13 * n22 * n31
  3792. - n11 * n23 * n32
  3793. + n11 * n22 * n33
  3794. + n13 * n21 * n32
  3795. - n12 * n21 * n33
  3796. + n12 * n23 * n31
  3797. )
  3798. );
  3799. }
  3800. transpose() {
  3801. const te = this.elements;
  3802. let tmp;
  3803. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3804. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3805. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3806. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3807. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3808. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3809. return this;
  3810. }
  3811. setPosition( x, y, z ) {
  3812. const te = this.elements;
  3813. if ( x.isVector3 ) {
  3814. te[ 12 ] = x.x;
  3815. te[ 13 ] = x.y;
  3816. te[ 14 ] = x.z;
  3817. } else {
  3818. te[ 12 ] = x;
  3819. te[ 13 ] = y;
  3820. te[ 14 ] = z;
  3821. }
  3822. return this;
  3823. }
  3824. invert() {
  3825. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3826. const te = this.elements,
  3827. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3828. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3829. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3830. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3831. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3832. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3833. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3834. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3835. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3836. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3837. const detInv = 1 / det;
  3838. te[ 0 ] = t11 * detInv;
  3839. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3840. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3841. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3842. te[ 4 ] = t12 * detInv;
  3843. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3844. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3845. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3846. te[ 8 ] = t13 * detInv;
  3847. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3848. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3849. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3850. te[ 12 ] = t14 * detInv;
  3851. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3852. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3853. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3854. return this;
  3855. }
  3856. scale( v ) {
  3857. const te = this.elements;
  3858. const x = v.x, y = v.y, z = v.z;
  3859. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3860. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3861. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3862. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3863. return this;
  3864. }
  3865. getMaxScaleOnAxis() {
  3866. const te = this.elements;
  3867. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3868. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3869. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3870. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3871. }
  3872. makeTranslation( x, y, z ) {
  3873. if ( x.isVector3 ) {
  3874. this.set(
  3875. 1, 0, 0, x.x,
  3876. 0, 1, 0, x.y,
  3877. 0, 0, 1, x.z,
  3878. 0, 0, 0, 1
  3879. );
  3880. } else {
  3881. this.set(
  3882. 1, 0, 0, x,
  3883. 0, 1, 0, y,
  3884. 0, 0, 1, z,
  3885. 0, 0, 0, 1
  3886. );
  3887. }
  3888. return this;
  3889. }
  3890. makeRotationX( theta ) {
  3891. const c = Math.cos( theta ), s = Math.sin( theta );
  3892. this.set(
  3893. 1, 0, 0, 0,
  3894. 0, c, - s, 0,
  3895. 0, s, c, 0,
  3896. 0, 0, 0, 1
  3897. );
  3898. return this;
  3899. }
  3900. makeRotationY( theta ) {
  3901. const c = Math.cos( theta ), s = Math.sin( theta );
  3902. this.set(
  3903. c, 0, s, 0,
  3904. 0, 1, 0, 0,
  3905. - s, 0, c, 0,
  3906. 0, 0, 0, 1
  3907. );
  3908. return this;
  3909. }
  3910. makeRotationZ( theta ) {
  3911. const c = Math.cos( theta ), s = Math.sin( theta );
  3912. this.set(
  3913. c, - s, 0, 0,
  3914. s, c, 0, 0,
  3915. 0, 0, 1, 0,
  3916. 0, 0, 0, 1
  3917. );
  3918. return this;
  3919. }
  3920. makeRotationAxis( axis, angle ) {
  3921. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3922. const c = Math.cos( angle );
  3923. const s = Math.sin( angle );
  3924. const t = 1 - c;
  3925. const x = axis.x, y = axis.y, z = axis.z;
  3926. const tx = t * x, ty = t * y;
  3927. this.set(
  3928. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3929. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3930. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3931. 0, 0, 0, 1
  3932. );
  3933. return this;
  3934. }
  3935. makeScale( x, y, z ) {
  3936. this.set(
  3937. x, 0, 0, 0,
  3938. 0, y, 0, 0,
  3939. 0, 0, z, 0,
  3940. 0, 0, 0, 1
  3941. );
  3942. return this;
  3943. }
  3944. makeShear( xy, xz, yx, yz, zx, zy ) {
  3945. this.set(
  3946. 1, yx, zx, 0,
  3947. xy, 1, zy, 0,
  3948. xz, yz, 1, 0,
  3949. 0, 0, 0, 1
  3950. );
  3951. return this;
  3952. }
  3953. compose( position, quaternion, scale ) {
  3954. const te = this.elements;
  3955. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3956. const x2 = x + x, y2 = y + y, z2 = z + z;
  3957. const xx = x * x2, xy = x * y2, xz = x * z2;
  3958. const yy = y * y2, yz = y * z2, zz = z * z2;
  3959. const wx = w * x2, wy = w * y2, wz = w * z2;
  3960. const sx = scale.x, sy = scale.y, sz = scale.z;
  3961. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3962. te[ 1 ] = ( xy + wz ) * sx;
  3963. te[ 2 ] = ( xz - wy ) * sx;
  3964. te[ 3 ] = 0;
  3965. te[ 4 ] = ( xy - wz ) * sy;
  3966. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3967. te[ 6 ] = ( yz + wx ) * sy;
  3968. te[ 7 ] = 0;
  3969. te[ 8 ] = ( xz + wy ) * sz;
  3970. te[ 9 ] = ( yz - wx ) * sz;
  3971. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3972. te[ 11 ] = 0;
  3973. te[ 12 ] = position.x;
  3974. te[ 13 ] = position.y;
  3975. te[ 14 ] = position.z;
  3976. te[ 15 ] = 1;
  3977. return this;
  3978. }
  3979. decompose( position, quaternion, scale ) {
  3980. const te = this.elements;
  3981. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3982. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3983. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3984. // if determine is negative, we need to invert one scale
  3985. const det = this.determinant();
  3986. if ( det < 0 ) sx = - sx;
  3987. position.x = te[ 12 ];
  3988. position.y = te[ 13 ];
  3989. position.z = te[ 14 ];
  3990. // scale the rotation part
  3991. _m1$2.copy( this );
  3992. const invSX = 1 / sx;
  3993. const invSY = 1 / sy;
  3994. const invSZ = 1 / sz;
  3995. _m1$2.elements[ 0 ] *= invSX;
  3996. _m1$2.elements[ 1 ] *= invSX;
  3997. _m1$2.elements[ 2 ] *= invSX;
  3998. _m1$2.elements[ 4 ] *= invSY;
  3999. _m1$2.elements[ 5 ] *= invSY;
  4000. _m1$2.elements[ 6 ] *= invSY;
  4001. _m1$2.elements[ 8 ] *= invSZ;
  4002. _m1$2.elements[ 9 ] *= invSZ;
  4003. _m1$2.elements[ 10 ] *= invSZ;
  4004. quaternion.setFromRotationMatrix( _m1$2 );
  4005. scale.x = sx;
  4006. scale.y = sy;
  4007. scale.z = sz;
  4008. return this;
  4009. }
  4010. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4011. const te = this.elements;
  4012. const x = 2 * near / ( right - left );
  4013. const y = 2 * near / ( top - bottom );
  4014. const a = ( right + left ) / ( right - left );
  4015. const b = ( top + bottom ) / ( top - bottom );
  4016. let c, d;
  4017. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4018. c = - ( far + near ) / ( far - near );
  4019. d = ( - 2 * far * near ) / ( far - near );
  4020. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4021. c = - far / ( far - near );
  4022. d = ( - far * near ) / ( far - near );
  4023. } else {
  4024. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4025. }
  4026. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4027. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4028. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4029. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4030. return this;
  4031. }
  4032. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4033. const te = this.elements;
  4034. const w = 1.0 / ( right - left );
  4035. const h = 1.0 / ( top - bottom );
  4036. const p = 1.0 / ( far - near );
  4037. const x = ( right + left ) * w;
  4038. const y = ( top + bottom ) * h;
  4039. let z, zInv;
  4040. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4041. z = ( far + near ) * p;
  4042. zInv = - 2 * p;
  4043. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4044. z = near * p;
  4045. zInv = - 1 * p;
  4046. } else {
  4047. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4048. }
  4049. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4050. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4051. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4052. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4053. return this;
  4054. }
  4055. equals( matrix ) {
  4056. const te = this.elements;
  4057. const me = matrix.elements;
  4058. for ( let i = 0; i < 16; i ++ ) {
  4059. if ( te[ i ] !== me[ i ] ) return false;
  4060. }
  4061. return true;
  4062. }
  4063. fromArray( array, offset = 0 ) {
  4064. for ( let i = 0; i < 16; i ++ ) {
  4065. this.elements[ i ] = array[ i + offset ];
  4066. }
  4067. return this;
  4068. }
  4069. toArray( array = [], offset = 0 ) {
  4070. const te = this.elements;
  4071. array[ offset ] = te[ 0 ];
  4072. array[ offset + 1 ] = te[ 1 ];
  4073. array[ offset + 2 ] = te[ 2 ];
  4074. array[ offset + 3 ] = te[ 3 ];
  4075. array[ offset + 4 ] = te[ 4 ];
  4076. array[ offset + 5 ] = te[ 5 ];
  4077. array[ offset + 6 ] = te[ 6 ];
  4078. array[ offset + 7 ] = te[ 7 ];
  4079. array[ offset + 8 ] = te[ 8 ];
  4080. array[ offset + 9 ] = te[ 9 ];
  4081. array[ offset + 10 ] = te[ 10 ];
  4082. array[ offset + 11 ] = te[ 11 ];
  4083. array[ offset + 12 ] = te[ 12 ];
  4084. array[ offset + 13 ] = te[ 13 ];
  4085. array[ offset + 14 ] = te[ 14 ];
  4086. array[ offset + 15 ] = te[ 15 ];
  4087. return array;
  4088. }
  4089. }
  4090. const _v1$5 = /*@__PURE__*/ new Vector3();
  4091. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4092. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4093. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4094. const _x = /*@__PURE__*/ new Vector3();
  4095. const _y = /*@__PURE__*/ new Vector3();
  4096. const _z = /*@__PURE__*/ new Vector3();
  4097. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4098. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4099. class Euler {
  4100. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4101. this.isEuler = true;
  4102. this._x = x;
  4103. this._y = y;
  4104. this._z = z;
  4105. this._order = order;
  4106. }
  4107. get x() {
  4108. return this._x;
  4109. }
  4110. set x( value ) {
  4111. this._x = value;
  4112. this._onChangeCallback();
  4113. }
  4114. get y() {
  4115. return this._y;
  4116. }
  4117. set y( value ) {
  4118. this._y = value;
  4119. this._onChangeCallback();
  4120. }
  4121. get z() {
  4122. return this._z;
  4123. }
  4124. set z( value ) {
  4125. this._z = value;
  4126. this._onChangeCallback();
  4127. }
  4128. get order() {
  4129. return this._order;
  4130. }
  4131. set order( value ) {
  4132. this._order = value;
  4133. this._onChangeCallback();
  4134. }
  4135. set( x, y, z, order = this._order ) {
  4136. this._x = x;
  4137. this._y = y;
  4138. this._z = z;
  4139. this._order = order;
  4140. this._onChangeCallback();
  4141. return this;
  4142. }
  4143. clone() {
  4144. return new this.constructor( this._x, this._y, this._z, this._order );
  4145. }
  4146. copy( euler ) {
  4147. this._x = euler._x;
  4148. this._y = euler._y;
  4149. this._z = euler._z;
  4150. this._order = euler._order;
  4151. this._onChangeCallback();
  4152. return this;
  4153. }
  4154. setFromRotationMatrix( m, order = this._order, update = true ) {
  4155. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4156. const te = m.elements;
  4157. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4158. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4159. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4160. switch ( order ) {
  4161. case 'XYZ':
  4162. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4163. if ( Math.abs( m13 ) < 0.9999999 ) {
  4164. this._x = Math.atan2( - m23, m33 );
  4165. this._z = Math.atan2( - m12, m11 );
  4166. } else {
  4167. this._x = Math.atan2( m32, m22 );
  4168. this._z = 0;
  4169. }
  4170. break;
  4171. case 'YXZ':
  4172. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4173. if ( Math.abs( m23 ) < 0.9999999 ) {
  4174. this._y = Math.atan2( m13, m33 );
  4175. this._z = Math.atan2( m21, m22 );
  4176. } else {
  4177. this._y = Math.atan2( - m31, m11 );
  4178. this._z = 0;
  4179. }
  4180. break;
  4181. case 'ZXY':
  4182. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4183. if ( Math.abs( m32 ) < 0.9999999 ) {
  4184. this._y = Math.atan2( - m31, m33 );
  4185. this._z = Math.atan2( - m12, m22 );
  4186. } else {
  4187. this._y = 0;
  4188. this._z = Math.atan2( m21, m11 );
  4189. }
  4190. break;
  4191. case 'ZYX':
  4192. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4193. if ( Math.abs( m31 ) < 0.9999999 ) {
  4194. this._x = Math.atan2( m32, m33 );
  4195. this._z = Math.atan2( m21, m11 );
  4196. } else {
  4197. this._x = 0;
  4198. this._z = Math.atan2( - m12, m22 );
  4199. }
  4200. break;
  4201. case 'YZX':
  4202. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4203. if ( Math.abs( m21 ) < 0.9999999 ) {
  4204. this._x = Math.atan2( - m23, m22 );
  4205. this._y = Math.atan2( - m31, m11 );
  4206. } else {
  4207. this._x = 0;
  4208. this._y = Math.atan2( m13, m33 );
  4209. }
  4210. break;
  4211. case 'XZY':
  4212. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4213. if ( Math.abs( m12 ) < 0.9999999 ) {
  4214. this._x = Math.atan2( m32, m22 );
  4215. this._y = Math.atan2( m13, m11 );
  4216. } else {
  4217. this._x = Math.atan2( - m23, m33 );
  4218. this._y = 0;
  4219. }
  4220. break;
  4221. default:
  4222. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4223. }
  4224. this._order = order;
  4225. if ( update === true ) this._onChangeCallback();
  4226. return this;
  4227. }
  4228. setFromQuaternion( q, order, update ) {
  4229. _matrix$2.makeRotationFromQuaternion( q );
  4230. return this.setFromRotationMatrix( _matrix$2, order, update );
  4231. }
  4232. setFromVector3( v, order = this._order ) {
  4233. return this.set( v.x, v.y, v.z, order );
  4234. }
  4235. reorder( newOrder ) {
  4236. // WARNING: this discards revolution information -bhouston
  4237. _quaternion$3.setFromEuler( this );
  4238. return this.setFromQuaternion( _quaternion$3, newOrder );
  4239. }
  4240. equals( euler ) {
  4241. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4242. }
  4243. fromArray( array ) {
  4244. this._x = array[ 0 ];
  4245. this._y = array[ 1 ];
  4246. this._z = array[ 2 ];
  4247. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4248. this._onChangeCallback();
  4249. return this;
  4250. }
  4251. toArray( array = [], offset = 0 ) {
  4252. array[ offset ] = this._x;
  4253. array[ offset + 1 ] = this._y;
  4254. array[ offset + 2 ] = this._z;
  4255. array[ offset + 3 ] = this._order;
  4256. return array;
  4257. }
  4258. _onChange( callback ) {
  4259. this._onChangeCallback = callback;
  4260. return this;
  4261. }
  4262. _onChangeCallback() {}
  4263. *[ Symbol.iterator ]() {
  4264. yield this._x;
  4265. yield this._y;
  4266. yield this._z;
  4267. yield this._order;
  4268. }
  4269. }
  4270. Euler.DEFAULT_ORDER = 'XYZ';
  4271. class Layers {
  4272. constructor() {
  4273. this.mask = 1 | 0;
  4274. }
  4275. set( channel ) {
  4276. this.mask = ( 1 << channel | 0 ) >>> 0;
  4277. }
  4278. enable( channel ) {
  4279. this.mask |= 1 << channel | 0;
  4280. }
  4281. enableAll() {
  4282. this.mask = 0xffffffff | 0;
  4283. }
  4284. toggle( channel ) {
  4285. this.mask ^= 1 << channel | 0;
  4286. }
  4287. disable( channel ) {
  4288. this.mask &= ~ ( 1 << channel | 0 );
  4289. }
  4290. disableAll() {
  4291. this.mask = 0;
  4292. }
  4293. test( layers ) {
  4294. return ( this.mask & layers.mask ) !== 0;
  4295. }
  4296. isEnabled( channel ) {
  4297. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4298. }
  4299. }
  4300. let _object3DId = 0;
  4301. const _v1$4 = /*@__PURE__*/ new Vector3();
  4302. const _q1 = /*@__PURE__*/ new Quaternion();
  4303. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4304. const _target$1 = /*@__PURE__*/ new Vector3();
  4305. const _position$3 = /*@__PURE__*/ new Vector3();
  4306. const _scale$2 = /*@__PURE__*/ new Vector3();
  4307. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4308. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4309. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4310. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4311. const _addedEvent = { type: 'added' };
  4312. const _removedEvent = { type: 'removed' };
  4313. const _childaddedEvent = { type: 'childadded', child: null };
  4314. const _childremovedEvent = { type: 'childremoved', child: null };
  4315. class Object3D extends EventDispatcher {
  4316. constructor() {
  4317. super();
  4318. this.isObject3D = true;
  4319. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4320. this.uuid = generateUUID();
  4321. this.name = '';
  4322. this.type = 'Object3D';
  4323. this.parent = null;
  4324. this.children = [];
  4325. this.up = Object3D.DEFAULT_UP.clone();
  4326. const position = new Vector3();
  4327. const rotation = new Euler();
  4328. const quaternion = new Quaternion();
  4329. const scale = new Vector3( 1, 1, 1 );
  4330. function onRotationChange() {
  4331. quaternion.setFromEuler( rotation, false );
  4332. }
  4333. function onQuaternionChange() {
  4334. rotation.setFromQuaternion( quaternion, undefined, false );
  4335. }
  4336. rotation._onChange( onRotationChange );
  4337. quaternion._onChange( onQuaternionChange );
  4338. Object.defineProperties( this, {
  4339. position: {
  4340. configurable: true,
  4341. enumerable: true,
  4342. value: position
  4343. },
  4344. rotation: {
  4345. configurable: true,
  4346. enumerable: true,
  4347. value: rotation
  4348. },
  4349. quaternion: {
  4350. configurable: true,
  4351. enumerable: true,
  4352. value: quaternion
  4353. },
  4354. scale: {
  4355. configurable: true,
  4356. enumerable: true,
  4357. value: scale
  4358. },
  4359. modelViewMatrix: {
  4360. value: new Matrix4()
  4361. },
  4362. normalMatrix: {
  4363. value: new Matrix3()
  4364. }
  4365. } );
  4366. this.matrix = new Matrix4();
  4367. this.matrixWorld = new Matrix4();
  4368. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4369. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4370. this.matrixWorldNeedsUpdate = false;
  4371. this.layers = new Layers();
  4372. this.visible = true;
  4373. this.castShadow = false;
  4374. this.receiveShadow = false;
  4375. this.frustumCulled = true;
  4376. this.renderOrder = 0;
  4377. this.animations = [];
  4378. this.userData = {};
  4379. }
  4380. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4381. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4382. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4383. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4384. applyMatrix4( matrix ) {
  4385. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4386. this.matrix.premultiply( matrix );
  4387. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4388. }
  4389. applyQuaternion( q ) {
  4390. this.quaternion.premultiply( q );
  4391. return this;
  4392. }
  4393. setRotationFromAxisAngle( axis, angle ) {
  4394. // assumes axis is normalized
  4395. this.quaternion.setFromAxisAngle( axis, angle );
  4396. }
  4397. setRotationFromEuler( euler ) {
  4398. this.quaternion.setFromEuler( euler, true );
  4399. }
  4400. setRotationFromMatrix( m ) {
  4401. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4402. this.quaternion.setFromRotationMatrix( m );
  4403. }
  4404. setRotationFromQuaternion( q ) {
  4405. // assumes q is normalized
  4406. this.quaternion.copy( q );
  4407. }
  4408. rotateOnAxis( axis, angle ) {
  4409. // rotate object on axis in object space
  4410. // axis is assumed to be normalized
  4411. _q1.setFromAxisAngle( axis, angle );
  4412. this.quaternion.multiply( _q1 );
  4413. return this;
  4414. }
  4415. rotateOnWorldAxis( axis, angle ) {
  4416. // rotate object on axis in world space
  4417. // axis is assumed to be normalized
  4418. // method assumes no rotated parent
  4419. _q1.setFromAxisAngle( axis, angle );
  4420. this.quaternion.premultiply( _q1 );
  4421. return this;
  4422. }
  4423. rotateX( angle ) {
  4424. return this.rotateOnAxis( _xAxis, angle );
  4425. }
  4426. rotateY( angle ) {
  4427. return this.rotateOnAxis( _yAxis, angle );
  4428. }
  4429. rotateZ( angle ) {
  4430. return this.rotateOnAxis( _zAxis, angle );
  4431. }
  4432. translateOnAxis( axis, distance ) {
  4433. // translate object by distance along axis in object space
  4434. // axis is assumed to be normalized
  4435. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4436. this.position.add( _v1$4.multiplyScalar( distance ) );
  4437. return this;
  4438. }
  4439. translateX( distance ) {
  4440. return this.translateOnAxis( _xAxis, distance );
  4441. }
  4442. translateY( distance ) {
  4443. return this.translateOnAxis( _yAxis, distance );
  4444. }
  4445. translateZ( distance ) {
  4446. return this.translateOnAxis( _zAxis, distance );
  4447. }
  4448. localToWorld( vector ) {
  4449. this.updateWorldMatrix( true, false );
  4450. return vector.applyMatrix4( this.matrixWorld );
  4451. }
  4452. worldToLocal( vector ) {
  4453. this.updateWorldMatrix( true, false );
  4454. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4455. }
  4456. lookAt( x, y, z ) {
  4457. // This method does not support objects having non-uniformly-scaled parent(s)
  4458. if ( x.isVector3 ) {
  4459. _target$1.copy( x );
  4460. } else {
  4461. _target$1.set( x, y, z );
  4462. }
  4463. const parent = this.parent;
  4464. this.updateWorldMatrix( true, false );
  4465. _position$3.setFromMatrixPosition( this.matrixWorld );
  4466. if ( this.isCamera || this.isLight ) {
  4467. _m1$1.lookAt( _position$3, _target$1, this.up );
  4468. } else {
  4469. _m1$1.lookAt( _target$1, _position$3, this.up );
  4470. }
  4471. this.quaternion.setFromRotationMatrix( _m1$1 );
  4472. if ( parent ) {
  4473. _m1$1.extractRotation( parent.matrixWorld );
  4474. _q1.setFromRotationMatrix( _m1$1 );
  4475. this.quaternion.premultiply( _q1.invert() );
  4476. }
  4477. }
  4478. add( object ) {
  4479. if ( arguments.length > 1 ) {
  4480. for ( let i = 0; i < arguments.length; i ++ ) {
  4481. this.add( arguments[ i ] );
  4482. }
  4483. return this;
  4484. }
  4485. if ( object === this ) {
  4486. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4487. return this;
  4488. }
  4489. if ( object && object.isObject3D ) {
  4490. object.removeFromParent();
  4491. object.parent = this;
  4492. this.children.push( object );
  4493. object.dispatchEvent( _addedEvent );
  4494. _childaddedEvent.child = object;
  4495. this.dispatchEvent( _childaddedEvent );
  4496. _childaddedEvent.child = null;
  4497. } else {
  4498. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4499. }
  4500. return this;
  4501. }
  4502. remove( object ) {
  4503. if ( arguments.length > 1 ) {
  4504. for ( let i = 0; i < arguments.length; i ++ ) {
  4505. this.remove( arguments[ i ] );
  4506. }
  4507. return this;
  4508. }
  4509. const index = this.children.indexOf( object );
  4510. if ( index !== - 1 ) {
  4511. object.parent = null;
  4512. this.children.splice( index, 1 );
  4513. object.dispatchEvent( _removedEvent );
  4514. _childremovedEvent.child = object;
  4515. this.dispatchEvent( _childremovedEvent );
  4516. _childremovedEvent.child = null;
  4517. }
  4518. return this;
  4519. }
  4520. removeFromParent() {
  4521. const parent = this.parent;
  4522. if ( parent !== null ) {
  4523. parent.remove( this );
  4524. }
  4525. return this;
  4526. }
  4527. clear() {
  4528. return this.remove( ... this.children );
  4529. }
  4530. attach( object ) {
  4531. // adds object as a child of this, while maintaining the object's world transform
  4532. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4533. this.updateWorldMatrix( true, false );
  4534. _m1$1.copy( this.matrixWorld ).invert();
  4535. if ( object.parent !== null ) {
  4536. object.parent.updateWorldMatrix( true, false );
  4537. _m1$1.multiply( object.parent.matrixWorld );
  4538. }
  4539. object.applyMatrix4( _m1$1 );
  4540. object.removeFromParent();
  4541. object.parent = this;
  4542. this.children.push( object );
  4543. object.updateWorldMatrix( false, true );
  4544. object.dispatchEvent( _addedEvent );
  4545. _childaddedEvent.child = object;
  4546. this.dispatchEvent( _childaddedEvent );
  4547. _childaddedEvent.child = null;
  4548. return this;
  4549. }
  4550. getObjectById( id ) {
  4551. return this.getObjectByProperty( 'id', id );
  4552. }
  4553. getObjectByName( name ) {
  4554. return this.getObjectByProperty( 'name', name );
  4555. }
  4556. getObjectByProperty( name, value ) {
  4557. if ( this[ name ] === value ) return this;
  4558. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4559. const child = this.children[ i ];
  4560. const object = child.getObjectByProperty( name, value );
  4561. if ( object !== undefined ) {
  4562. return object;
  4563. }
  4564. }
  4565. return undefined;
  4566. }
  4567. getObjectsByProperty( name, value, result = [] ) {
  4568. if ( this[ name ] === value ) result.push( this );
  4569. const children = this.children;
  4570. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4571. children[ i ].getObjectsByProperty( name, value, result );
  4572. }
  4573. return result;
  4574. }
  4575. getWorldPosition( target ) {
  4576. this.updateWorldMatrix( true, false );
  4577. return target.setFromMatrixPosition( this.matrixWorld );
  4578. }
  4579. getWorldQuaternion( target ) {
  4580. this.updateWorldMatrix( true, false );
  4581. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4582. return target;
  4583. }
  4584. getWorldScale( target ) {
  4585. this.updateWorldMatrix( true, false );
  4586. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4587. return target;
  4588. }
  4589. getWorldDirection( target ) {
  4590. this.updateWorldMatrix( true, false );
  4591. const e = this.matrixWorld.elements;
  4592. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4593. }
  4594. raycast( /* raycaster, intersects */ ) {}
  4595. traverse( callback ) {
  4596. callback( this );
  4597. const children = this.children;
  4598. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4599. children[ i ].traverse( callback );
  4600. }
  4601. }
  4602. traverseVisible( callback ) {
  4603. if ( this.visible === false ) return;
  4604. callback( this );
  4605. const children = this.children;
  4606. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4607. children[ i ].traverseVisible( callback );
  4608. }
  4609. }
  4610. traverseAncestors( callback ) {
  4611. const parent = this.parent;
  4612. if ( parent !== null ) {
  4613. callback( parent );
  4614. parent.traverseAncestors( callback );
  4615. }
  4616. }
  4617. updateMatrix() {
  4618. this.matrix.compose( this.position, this.quaternion, this.scale );
  4619. this.matrixWorldNeedsUpdate = true;
  4620. }
  4621. updateMatrixWorld( force ) {
  4622. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4623. if ( this.matrixWorldNeedsUpdate || force ) {
  4624. if ( this.matrixWorldAutoUpdate === true ) {
  4625. if ( this.parent === null ) {
  4626. this.matrixWorld.copy( this.matrix );
  4627. } else {
  4628. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4629. }
  4630. }
  4631. this.matrixWorldNeedsUpdate = false;
  4632. force = true;
  4633. }
  4634. // make sure descendants are updated if required
  4635. const children = this.children;
  4636. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4637. const child = children[ i ];
  4638. child.updateMatrixWorld( force );
  4639. }
  4640. }
  4641. updateWorldMatrix( updateParents, updateChildren ) {
  4642. const parent = this.parent;
  4643. if ( updateParents === true && parent !== null ) {
  4644. parent.updateWorldMatrix( true, false );
  4645. }
  4646. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4647. if ( this.matrixWorldAutoUpdate === true ) {
  4648. if ( this.parent === null ) {
  4649. this.matrixWorld.copy( this.matrix );
  4650. } else {
  4651. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4652. }
  4653. }
  4654. // make sure descendants are updated
  4655. if ( updateChildren === true ) {
  4656. const children = this.children;
  4657. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4658. const child = children[ i ];
  4659. child.updateWorldMatrix( false, true );
  4660. }
  4661. }
  4662. }
  4663. toJSON( meta ) {
  4664. // meta is a string when called from JSON.stringify
  4665. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4666. const output = {};
  4667. // meta is a hash used to collect geometries, materials.
  4668. // not providing it implies that this is the root object
  4669. // being serialized.
  4670. if ( isRootObject ) {
  4671. // initialize meta obj
  4672. meta = {
  4673. geometries: {},
  4674. materials: {},
  4675. textures: {},
  4676. images: {},
  4677. shapes: {},
  4678. skeletons: {},
  4679. animations: {},
  4680. nodes: {}
  4681. };
  4682. output.metadata = {
  4683. version: 4.6,
  4684. type: 'Object',
  4685. generator: 'Object3D.toJSON'
  4686. };
  4687. }
  4688. // standard Object3D serialization
  4689. const object = {};
  4690. object.uuid = this.uuid;
  4691. object.type = this.type;
  4692. if ( this.name !== '' ) object.name = this.name;
  4693. if ( this.castShadow === true ) object.castShadow = true;
  4694. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4695. if ( this.visible === false ) object.visible = false;
  4696. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4697. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4698. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4699. object.layers = this.layers.mask;
  4700. object.matrix = this.matrix.toArray();
  4701. object.up = this.up.toArray();
  4702. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4703. // object specific properties
  4704. if ( this.isInstancedMesh ) {
  4705. object.type = 'InstancedMesh';
  4706. object.count = this.count;
  4707. object.instanceMatrix = this.instanceMatrix.toJSON();
  4708. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4709. }
  4710. if ( this.isBatchedMesh ) {
  4711. object.type = 'BatchedMesh';
  4712. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4713. object.sortObjects = this.sortObjects;
  4714. object.drawRanges = this._drawRanges;
  4715. object.reservedRanges = this._reservedRanges;
  4716. object.visibility = this._visibility;
  4717. object.active = this._active;
  4718. object.bounds = this._bounds.map( bound => ( {
  4719. boxInitialized: bound.boxInitialized,
  4720. boxMin: bound.box.min.toArray(),
  4721. boxMax: bound.box.max.toArray(),
  4722. sphereInitialized: bound.sphereInitialized,
  4723. sphereRadius: bound.sphere.radius,
  4724. sphereCenter: bound.sphere.center.toArray()
  4725. } ) );
  4726. object.maxInstanceCount = this._maxInstanceCount;
  4727. object.maxVertexCount = this._maxVertexCount;
  4728. object.maxIndexCount = this._maxIndexCount;
  4729. object.geometryInitialized = this._geometryInitialized;
  4730. object.geometryCount = this._geometryCount;
  4731. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4732. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4733. if ( this.boundingSphere !== null ) {
  4734. object.boundingSphere = {
  4735. center: object.boundingSphere.center.toArray(),
  4736. radius: object.boundingSphere.radius
  4737. };
  4738. }
  4739. if ( this.boundingBox !== null ) {
  4740. object.boundingBox = {
  4741. min: object.boundingBox.min.toArray(),
  4742. max: object.boundingBox.max.toArray()
  4743. };
  4744. }
  4745. }
  4746. //
  4747. function serialize( library, element ) {
  4748. if ( library[ element.uuid ] === undefined ) {
  4749. library[ element.uuid ] = element.toJSON( meta );
  4750. }
  4751. return element.uuid;
  4752. }
  4753. if ( this.isScene ) {
  4754. if ( this.background ) {
  4755. if ( this.background.isColor ) {
  4756. object.background = this.background.toJSON();
  4757. } else if ( this.background.isTexture ) {
  4758. object.background = this.background.toJSON( meta ).uuid;
  4759. }
  4760. }
  4761. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4762. object.environment = this.environment.toJSON( meta ).uuid;
  4763. }
  4764. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4765. object.geometry = serialize( meta.geometries, this.geometry );
  4766. const parameters = this.geometry.parameters;
  4767. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4768. const shapes = parameters.shapes;
  4769. if ( Array.isArray( shapes ) ) {
  4770. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4771. const shape = shapes[ i ];
  4772. serialize( meta.shapes, shape );
  4773. }
  4774. } else {
  4775. serialize( meta.shapes, shapes );
  4776. }
  4777. }
  4778. }
  4779. if ( this.isSkinnedMesh ) {
  4780. object.bindMode = this.bindMode;
  4781. object.bindMatrix = this.bindMatrix.toArray();
  4782. if ( this.skeleton !== undefined ) {
  4783. serialize( meta.skeletons, this.skeleton );
  4784. object.skeleton = this.skeleton.uuid;
  4785. }
  4786. }
  4787. if ( this.material !== undefined ) {
  4788. if ( Array.isArray( this.material ) ) {
  4789. const uuids = [];
  4790. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4791. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4792. }
  4793. object.material = uuids;
  4794. } else {
  4795. object.material = serialize( meta.materials, this.material );
  4796. }
  4797. }
  4798. //
  4799. if ( this.children.length > 0 ) {
  4800. object.children = [];
  4801. for ( let i = 0; i < this.children.length; i ++ ) {
  4802. object.children.push( this.children[ i ].toJSON( meta ).object );
  4803. }
  4804. }
  4805. //
  4806. if ( this.animations.length > 0 ) {
  4807. object.animations = [];
  4808. for ( let i = 0; i < this.animations.length; i ++ ) {
  4809. const animation = this.animations[ i ];
  4810. object.animations.push( serialize( meta.animations, animation ) );
  4811. }
  4812. }
  4813. if ( isRootObject ) {
  4814. const geometries = extractFromCache( meta.geometries );
  4815. const materials = extractFromCache( meta.materials );
  4816. const textures = extractFromCache( meta.textures );
  4817. const images = extractFromCache( meta.images );
  4818. const shapes = extractFromCache( meta.shapes );
  4819. const skeletons = extractFromCache( meta.skeletons );
  4820. const animations = extractFromCache( meta.animations );
  4821. const nodes = extractFromCache( meta.nodes );
  4822. if ( geometries.length > 0 ) output.geometries = geometries;
  4823. if ( materials.length > 0 ) output.materials = materials;
  4824. if ( textures.length > 0 ) output.textures = textures;
  4825. if ( images.length > 0 ) output.images = images;
  4826. if ( shapes.length > 0 ) output.shapes = shapes;
  4827. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4828. if ( animations.length > 0 ) output.animations = animations;
  4829. if ( nodes.length > 0 ) output.nodes = nodes;
  4830. }
  4831. output.object = object;
  4832. return output;
  4833. // extract data from the cache hash
  4834. // remove metadata on each item
  4835. // and return as array
  4836. function extractFromCache( cache ) {
  4837. const values = [];
  4838. for ( const key in cache ) {
  4839. const data = cache[ key ];
  4840. delete data.metadata;
  4841. values.push( data );
  4842. }
  4843. return values;
  4844. }
  4845. }
  4846. clone( recursive ) {
  4847. return new this.constructor().copy( this, recursive );
  4848. }
  4849. copy( source, recursive = true ) {
  4850. this.name = source.name;
  4851. this.up.copy( source.up );
  4852. this.position.copy( source.position );
  4853. this.rotation.order = source.rotation.order;
  4854. this.quaternion.copy( source.quaternion );
  4855. this.scale.copy( source.scale );
  4856. this.matrix.copy( source.matrix );
  4857. this.matrixWorld.copy( source.matrixWorld );
  4858. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4859. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4860. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4861. this.layers.mask = source.layers.mask;
  4862. this.visible = source.visible;
  4863. this.castShadow = source.castShadow;
  4864. this.receiveShadow = source.receiveShadow;
  4865. this.frustumCulled = source.frustumCulled;
  4866. this.renderOrder = source.renderOrder;
  4867. this.animations = source.animations.slice();
  4868. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4869. if ( recursive === true ) {
  4870. for ( let i = 0; i < source.children.length; i ++ ) {
  4871. const child = source.children[ i ];
  4872. this.add( child.clone() );
  4873. }
  4874. }
  4875. return this;
  4876. }
  4877. }
  4878. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4879. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4880. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4881. const _v0$1 = /*@__PURE__*/ new Vector3();
  4882. const _v1$3 = /*@__PURE__*/ new Vector3();
  4883. const _v2$2 = /*@__PURE__*/ new Vector3();
  4884. const _v3$2 = /*@__PURE__*/ new Vector3();
  4885. const _vab = /*@__PURE__*/ new Vector3();
  4886. const _vac = /*@__PURE__*/ new Vector3();
  4887. const _vbc = /*@__PURE__*/ new Vector3();
  4888. const _vap = /*@__PURE__*/ new Vector3();
  4889. const _vbp = /*@__PURE__*/ new Vector3();
  4890. const _vcp = /*@__PURE__*/ new Vector3();
  4891. class Triangle {
  4892. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4893. this.a = a;
  4894. this.b = b;
  4895. this.c = c;
  4896. }
  4897. static getNormal( a, b, c, target ) {
  4898. target.subVectors( c, b );
  4899. _v0$1.subVectors( a, b );
  4900. target.cross( _v0$1 );
  4901. const targetLengthSq = target.lengthSq();
  4902. if ( targetLengthSq > 0 ) {
  4903. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4904. }
  4905. return target.set( 0, 0, 0 );
  4906. }
  4907. // static/instance method to calculate barycentric coordinates
  4908. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4909. static getBarycoord( point, a, b, c, target ) {
  4910. _v0$1.subVectors( c, a );
  4911. _v1$3.subVectors( b, a );
  4912. _v2$2.subVectors( point, a );
  4913. const dot00 = _v0$1.dot( _v0$1 );
  4914. const dot01 = _v0$1.dot( _v1$3 );
  4915. const dot02 = _v0$1.dot( _v2$2 );
  4916. const dot11 = _v1$3.dot( _v1$3 );
  4917. const dot12 = _v1$3.dot( _v2$2 );
  4918. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4919. // collinear or singular triangle
  4920. if ( denom === 0 ) {
  4921. target.set( 0, 0, 0 );
  4922. return null;
  4923. }
  4924. const invDenom = 1 / denom;
  4925. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4926. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4927. // barycentric coordinates must always sum to 1
  4928. return target.set( 1 - u - v, v, u );
  4929. }
  4930. static containsPoint( point, a, b, c ) {
  4931. // if the triangle is degenerate then we can't contain a point
  4932. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4933. return false;
  4934. }
  4935. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4936. }
  4937. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4938. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4939. target.x = 0;
  4940. target.y = 0;
  4941. if ( 'z' in target ) target.z = 0;
  4942. if ( 'w' in target ) target.w = 0;
  4943. return null;
  4944. }
  4945. target.setScalar( 0 );
  4946. target.addScaledVector( v1, _v3$2.x );
  4947. target.addScaledVector( v2, _v3$2.y );
  4948. target.addScaledVector( v3, _v3$2.z );
  4949. return target;
  4950. }
  4951. static isFrontFacing( a, b, c, direction ) {
  4952. _v0$1.subVectors( c, b );
  4953. _v1$3.subVectors( a, b );
  4954. // strictly front facing
  4955. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4956. }
  4957. set( a, b, c ) {
  4958. this.a.copy( a );
  4959. this.b.copy( b );
  4960. this.c.copy( c );
  4961. return this;
  4962. }
  4963. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4964. this.a.copy( points[ i0 ] );
  4965. this.b.copy( points[ i1 ] );
  4966. this.c.copy( points[ i2 ] );
  4967. return this;
  4968. }
  4969. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4970. this.a.fromBufferAttribute( attribute, i0 );
  4971. this.b.fromBufferAttribute( attribute, i1 );
  4972. this.c.fromBufferAttribute( attribute, i2 );
  4973. return this;
  4974. }
  4975. clone() {
  4976. return new this.constructor().copy( this );
  4977. }
  4978. copy( triangle ) {
  4979. this.a.copy( triangle.a );
  4980. this.b.copy( triangle.b );
  4981. this.c.copy( triangle.c );
  4982. return this;
  4983. }
  4984. getArea() {
  4985. _v0$1.subVectors( this.c, this.b );
  4986. _v1$3.subVectors( this.a, this.b );
  4987. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4988. }
  4989. getMidpoint( target ) {
  4990. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4991. }
  4992. getNormal( target ) {
  4993. return Triangle.getNormal( this.a, this.b, this.c, target );
  4994. }
  4995. getPlane( target ) {
  4996. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4997. }
  4998. getBarycoord( point, target ) {
  4999. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5000. }
  5001. getInterpolation( point, v1, v2, v3, target ) {
  5002. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5003. }
  5004. containsPoint( point ) {
  5005. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5006. }
  5007. isFrontFacing( direction ) {
  5008. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5009. }
  5010. intersectsBox( box ) {
  5011. return box.intersectsTriangle( this );
  5012. }
  5013. closestPointToPoint( p, target ) {
  5014. const a = this.a, b = this.b, c = this.c;
  5015. let v, w;
  5016. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5017. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5018. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5019. // basically, we're distinguishing which of the voronoi regions of the triangle
  5020. // the point lies in with the minimum amount of redundant computation.
  5021. _vab.subVectors( b, a );
  5022. _vac.subVectors( c, a );
  5023. _vap.subVectors( p, a );
  5024. const d1 = _vab.dot( _vap );
  5025. const d2 = _vac.dot( _vap );
  5026. if ( d1 <= 0 && d2 <= 0 ) {
  5027. // vertex region of A; barycentric coords (1, 0, 0)
  5028. return target.copy( a );
  5029. }
  5030. _vbp.subVectors( p, b );
  5031. const d3 = _vab.dot( _vbp );
  5032. const d4 = _vac.dot( _vbp );
  5033. if ( d3 >= 0 && d4 <= d3 ) {
  5034. // vertex region of B; barycentric coords (0, 1, 0)
  5035. return target.copy( b );
  5036. }
  5037. const vc = d1 * d4 - d3 * d2;
  5038. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5039. v = d1 / ( d1 - d3 );
  5040. // edge region of AB; barycentric coords (1-v, v, 0)
  5041. return target.copy( a ).addScaledVector( _vab, v );
  5042. }
  5043. _vcp.subVectors( p, c );
  5044. const d5 = _vab.dot( _vcp );
  5045. const d6 = _vac.dot( _vcp );
  5046. if ( d6 >= 0 && d5 <= d6 ) {
  5047. // vertex region of C; barycentric coords (0, 0, 1)
  5048. return target.copy( c );
  5049. }
  5050. const vb = d5 * d2 - d1 * d6;
  5051. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5052. w = d2 / ( d2 - d6 );
  5053. // edge region of AC; barycentric coords (1-w, 0, w)
  5054. return target.copy( a ).addScaledVector( _vac, w );
  5055. }
  5056. const va = d3 * d6 - d5 * d4;
  5057. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5058. _vbc.subVectors( c, b );
  5059. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5060. // edge region of BC; barycentric coords (0, 1-w, w)
  5061. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5062. }
  5063. // face region
  5064. const denom = 1 / ( va + vb + vc );
  5065. // u = va * denom
  5066. v = vb * denom;
  5067. w = vc * denom;
  5068. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5069. }
  5070. equals( triangle ) {
  5071. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5072. }
  5073. }
  5074. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5075. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5076. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5077. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5078. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5079. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5080. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5081. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5082. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5083. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5084. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5085. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5086. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5087. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5088. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5089. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5090. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5091. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5092. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5093. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5094. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5095. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5096. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5097. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5098. const _hslA = { h: 0, s: 0, l: 0 };
  5099. const _hslB = { h: 0, s: 0, l: 0 };
  5100. function hue2rgb( p, q, t ) {
  5101. if ( t < 0 ) t += 1;
  5102. if ( t > 1 ) t -= 1;
  5103. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5104. if ( t < 1 / 2 ) return q;
  5105. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5106. return p;
  5107. }
  5108. class Color {
  5109. constructor( r, g, b ) {
  5110. this.isColor = true;
  5111. this.r = 1;
  5112. this.g = 1;
  5113. this.b = 1;
  5114. return this.set( r, g, b );
  5115. }
  5116. set( r, g, b ) {
  5117. if ( g === undefined && b === undefined ) {
  5118. // r is THREE.Color, hex or string
  5119. const value = r;
  5120. if ( value && value.isColor ) {
  5121. this.copy( value );
  5122. } else if ( typeof value === 'number' ) {
  5123. this.setHex( value );
  5124. } else if ( typeof value === 'string' ) {
  5125. this.setStyle( value );
  5126. }
  5127. } else {
  5128. this.setRGB( r, g, b );
  5129. }
  5130. return this;
  5131. }
  5132. setScalar( scalar ) {
  5133. this.r = scalar;
  5134. this.g = scalar;
  5135. this.b = scalar;
  5136. return this;
  5137. }
  5138. setHex( hex, colorSpace = SRGBColorSpace ) {
  5139. hex = Math.floor( hex );
  5140. this.r = ( hex >> 16 & 255 ) / 255;
  5141. this.g = ( hex >> 8 & 255 ) / 255;
  5142. this.b = ( hex & 255 ) / 255;
  5143. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5144. return this;
  5145. }
  5146. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5147. this.r = r;
  5148. this.g = g;
  5149. this.b = b;
  5150. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5151. return this;
  5152. }
  5153. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5154. // h,s,l ranges are in 0.0 - 1.0
  5155. h = euclideanModulo( h, 1 );
  5156. s = clamp$1( s, 0, 1 );
  5157. l = clamp$1( l, 0, 1 );
  5158. if ( s === 0 ) {
  5159. this.r = this.g = this.b = l;
  5160. } else {
  5161. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5162. const q = ( 2 * l ) - p;
  5163. this.r = hue2rgb( q, p, h + 1 / 3 );
  5164. this.g = hue2rgb( q, p, h );
  5165. this.b = hue2rgb( q, p, h - 1 / 3 );
  5166. }
  5167. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5168. return this;
  5169. }
  5170. setStyle( style, colorSpace = SRGBColorSpace ) {
  5171. function handleAlpha( string ) {
  5172. if ( string === undefined ) return;
  5173. if ( parseFloat( string ) < 1 ) {
  5174. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5175. }
  5176. }
  5177. let m;
  5178. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5179. // rgb / hsl
  5180. let color;
  5181. const name = m[ 1 ];
  5182. const components = m[ 2 ];
  5183. switch ( name ) {
  5184. case 'rgb':
  5185. case 'rgba':
  5186. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5187. // rgb(255,0,0) rgba(255,0,0,0.5)
  5188. handleAlpha( color[ 4 ] );
  5189. return this.setRGB(
  5190. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5191. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5192. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5193. colorSpace
  5194. );
  5195. }
  5196. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5197. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5198. handleAlpha( color[ 4 ] );
  5199. return this.setRGB(
  5200. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5201. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5202. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5203. colorSpace
  5204. );
  5205. }
  5206. break;
  5207. case 'hsl':
  5208. case 'hsla':
  5209. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5210. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5211. handleAlpha( color[ 4 ] );
  5212. return this.setHSL(
  5213. parseFloat( color[ 1 ] ) / 360,
  5214. parseFloat( color[ 2 ] ) / 100,
  5215. parseFloat( color[ 3 ] ) / 100,
  5216. colorSpace
  5217. );
  5218. }
  5219. break;
  5220. default:
  5221. console.warn( 'THREE.Color: Unknown color model ' + style );
  5222. }
  5223. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5224. // hex color
  5225. const hex = m[ 1 ];
  5226. const size = hex.length;
  5227. if ( size === 3 ) {
  5228. // #ff0
  5229. return this.setRGB(
  5230. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5231. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5232. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5233. colorSpace
  5234. );
  5235. } else if ( size === 6 ) {
  5236. // #ff0000
  5237. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5238. } else {
  5239. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5240. }
  5241. } else if ( style && style.length > 0 ) {
  5242. return this.setColorName( style, colorSpace );
  5243. }
  5244. return this;
  5245. }
  5246. setColorName( style, colorSpace = SRGBColorSpace ) {
  5247. // color keywords
  5248. const hex = _colorKeywords[ style.toLowerCase() ];
  5249. if ( hex !== undefined ) {
  5250. // red
  5251. this.setHex( hex, colorSpace );
  5252. } else {
  5253. // unknown color
  5254. console.warn( 'THREE.Color: Unknown color ' + style );
  5255. }
  5256. return this;
  5257. }
  5258. clone() {
  5259. return new this.constructor( this.r, this.g, this.b );
  5260. }
  5261. copy( color ) {
  5262. this.r = color.r;
  5263. this.g = color.g;
  5264. this.b = color.b;
  5265. return this;
  5266. }
  5267. copySRGBToLinear( color ) {
  5268. this.r = SRGBToLinear( color.r );
  5269. this.g = SRGBToLinear( color.g );
  5270. this.b = SRGBToLinear( color.b );
  5271. return this;
  5272. }
  5273. copyLinearToSRGB( color ) {
  5274. this.r = LinearToSRGB( color.r );
  5275. this.g = LinearToSRGB( color.g );
  5276. this.b = LinearToSRGB( color.b );
  5277. return this;
  5278. }
  5279. convertSRGBToLinear() {
  5280. this.copySRGBToLinear( this );
  5281. return this;
  5282. }
  5283. convertLinearToSRGB() {
  5284. this.copyLinearToSRGB( this );
  5285. return this;
  5286. }
  5287. getHex( colorSpace = SRGBColorSpace ) {
  5288. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5289. 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 ) );
  5290. }
  5291. getHexString( colorSpace = SRGBColorSpace ) {
  5292. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5293. }
  5294. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5295. // h,s,l ranges are in 0.0 - 1.0
  5296. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5297. const r = _color.r, g = _color.g, b = _color.b;
  5298. const max = Math.max( r, g, b );
  5299. const min = Math.min( r, g, b );
  5300. let hue, saturation;
  5301. const lightness = ( min + max ) / 2.0;
  5302. if ( min === max ) {
  5303. hue = 0;
  5304. saturation = 0;
  5305. } else {
  5306. const delta = max - min;
  5307. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5308. switch ( max ) {
  5309. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5310. case g: hue = ( b - r ) / delta + 2; break;
  5311. case b: hue = ( r - g ) / delta + 4; break;
  5312. }
  5313. hue /= 6;
  5314. }
  5315. target.h = hue;
  5316. target.s = saturation;
  5317. target.l = lightness;
  5318. return target;
  5319. }
  5320. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5321. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5322. target.r = _color.r;
  5323. target.g = _color.g;
  5324. target.b = _color.b;
  5325. return target;
  5326. }
  5327. getStyle( colorSpace = SRGBColorSpace ) {
  5328. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5329. const r = _color.r, g = _color.g, b = _color.b;
  5330. if ( colorSpace !== SRGBColorSpace ) {
  5331. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5332. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5333. }
  5334. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5335. }
  5336. offsetHSL( h, s, l ) {
  5337. this.getHSL( _hslA );
  5338. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5339. }
  5340. add( color ) {
  5341. this.r += color.r;
  5342. this.g += color.g;
  5343. this.b += color.b;
  5344. return this;
  5345. }
  5346. addColors( color1, color2 ) {
  5347. this.r = color1.r + color2.r;
  5348. this.g = color1.g + color2.g;
  5349. this.b = color1.b + color2.b;
  5350. return this;
  5351. }
  5352. addScalar( s ) {
  5353. this.r += s;
  5354. this.g += s;
  5355. this.b += s;
  5356. return this;
  5357. }
  5358. sub( color ) {
  5359. this.r = Math.max( 0, this.r - color.r );
  5360. this.g = Math.max( 0, this.g - color.g );
  5361. this.b = Math.max( 0, this.b - color.b );
  5362. return this;
  5363. }
  5364. multiply( color ) {
  5365. this.r *= color.r;
  5366. this.g *= color.g;
  5367. this.b *= color.b;
  5368. return this;
  5369. }
  5370. multiplyScalar( s ) {
  5371. this.r *= s;
  5372. this.g *= s;
  5373. this.b *= s;
  5374. return this;
  5375. }
  5376. lerp( color, alpha ) {
  5377. this.r += ( color.r - this.r ) * alpha;
  5378. this.g += ( color.g - this.g ) * alpha;
  5379. this.b += ( color.b - this.b ) * alpha;
  5380. return this;
  5381. }
  5382. lerpColors( color1, color2, alpha ) {
  5383. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5384. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5385. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5386. return this;
  5387. }
  5388. lerpHSL( color, alpha ) {
  5389. this.getHSL( _hslA );
  5390. color.getHSL( _hslB );
  5391. const h = lerp( _hslA.h, _hslB.h, alpha );
  5392. const s = lerp( _hslA.s, _hslB.s, alpha );
  5393. const l = lerp( _hslA.l, _hslB.l, alpha );
  5394. this.setHSL( h, s, l );
  5395. return this;
  5396. }
  5397. setFromVector3( v ) {
  5398. this.r = v.x;
  5399. this.g = v.y;
  5400. this.b = v.z;
  5401. return this;
  5402. }
  5403. applyMatrix3( m ) {
  5404. const r = this.r, g = this.g, b = this.b;
  5405. const e = m.elements;
  5406. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5407. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5408. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5409. return this;
  5410. }
  5411. equals( c ) {
  5412. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5413. }
  5414. fromArray( array, offset = 0 ) {
  5415. this.r = array[ offset ];
  5416. this.g = array[ offset + 1 ];
  5417. this.b = array[ offset + 2 ];
  5418. return this;
  5419. }
  5420. toArray( array = [], offset = 0 ) {
  5421. array[ offset ] = this.r;
  5422. array[ offset + 1 ] = this.g;
  5423. array[ offset + 2 ] = this.b;
  5424. return array;
  5425. }
  5426. fromBufferAttribute( attribute, index ) {
  5427. this.r = attribute.getX( index );
  5428. this.g = attribute.getY( index );
  5429. this.b = attribute.getZ( index );
  5430. return this;
  5431. }
  5432. toJSON() {
  5433. return this.getHex();
  5434. }
  5435. *[ Symbol.iterator ]() {
  5436. yield this.r;
  5437. yield this.g;
  5438. yield this.b;
  5439. }
  5440. }
  5441. const _color = /*@__PURE__*/ new Color();
  5442. Color.NAMES = _colorKeywords;
  5443. let _materialId = 0;
  5444. class Material extends EventDispatcher {
  5445. constructor() {
  5446. super();
  5447. this.isMaterial = true;
  5448. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5449. this.uuid = generateUUID();
  5450. this.name = '';
  5451. this.type = 'Material';
  5452. this.blending = NormalBlending;
  5453. this.side = FrontSide;
  5454. this.vertexColors = false;
  5455. this.opacity = 1;
  5456. this.transparent = false;
  5457. this.alphaHash = false;
  5458. this.blendSrc = SrcAlphaFactor;
  5459. this.blendDst = OneMinusSrcAlphaFactor;
  5460. this.blendEquation = AddEquation;
  5461. this.blendSrcAlpha = null;
  5462. this.blendDstAlpha = null;
  5463. this.blendEquationAlpha = null;
  5464. this.blendColor = new Color( 0, 0, 0 );
  5465. this.blendAlpha = 0;
  5466. this.depthFunc = LessEqualDepth;
  5467. this.depthTest = true;
  5468. this.depthWrite = true;
  5469. this.stencilWriteMask = 0xff;
  5470. this.stencilFunc = AlwaysStencilFunc;
  5471. this.stencilRef = 0;
  5472. this.stencilFuncMask = 0xff;
  5473. this.stencilFail = KeepStencilOp;
  5474. this.stencilZFail = KeepStencilOp;
  5475. this.stencilZPass = KeepStencilOp;
  5476. this.stencilWrite = false;
  5477. this.clippingPlanes = null;
  5478. this.clipIntersection = false;
  5479. this.clipShadows = false;
  5480. this.shadowSide = null;
  5481. this.colorWrite = true;
  5482. this.precision = null; // override the renderer's default precision for this material
  5483. this.polygonOffset = false;
  5484. this.polygonOffsetFactor = 0;
  5485. this.polygonOffsetUnits = 0;
  5486. this.dithering = false;
  5487. this.alphaToCoverage = false;
  5488. this.premultipliedAlpha = false;
  5489. this.forceSinglePass = false;
  5490. this.visible = true;
  5491. this.toneMapped = true;
  5492. this.userData = {};
  5493. this.version = 0;
  5494. this._alphaTest = 0;
  5495. }
  5496. get alphaTest() {
  5497. return this._alphaTest;
  5498. }
  5499. set alphaTest( value ) {
  5500. if ( this._alphaTest > 0 !== value > 0 ) {
  5501. this.version ++;
  5502. }
  5503. this._alphaTest = value;
  5504. }
  5505. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5506. customProgramCacheKey() {
  5507. return this.onBeforeCompile.toString();
  5508. }
  5509. setValues( values ) {
  5510. if ( values === undefined ) return;
  5511. for ( const key in values ) {
  5512. const newValue = values[ key ];
  5513. if ( newValue === undefined ) {
  5514. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5515. continue;
  5516. }
  5517. const currentValue = this[ key ];
  5518. if ( currentValue === undefined ) {
  5519. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5520. continue;
  5521. }
  5522. if ( currentValue && currentValue.isColor ) {
  5523. currentValue.set( newValue );
  5524. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5525. currentValue.copy( newValue );
  5526. } else {
  5527. this[ key ] = newValue;
  5528. }
  5529. }
  5530. }
  5531. toJSON( meta ) {
  5532. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5533. if ( isRootObject ) {
  5534. meta = {
  5535. textures: {},
  5536. images: {}
  5537. };
  5538. }
  5539. const data = {
  5540. metadata: {
  5541. version: 4.6,
  5542. type: 'Material',
  5543. generator: 'Material.toJSON'
  5544. }
  5545. };
  5546. // standard Material serialization
  5547. data.uuid = this.uuid;
  5548. data.type = this.type;
  5549. if ( this.name !== '' ) data.name = this.name;
  5550. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5551. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5552. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5553. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5554. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5555. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5556. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5557. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5558. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5559. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5560. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5561. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5562. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5563. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5564. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5565. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5566. }
  5567. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5568. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5569. }
  5570. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5571. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5572. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5573. }
  5574. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5575. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5576. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5577. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5578. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5579. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5580. }
  5581. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5582. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5583. }
  5584. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5585. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5586. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5587. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5588. }
  5589. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5590. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5591. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5592. if ( this.lightMap && this.lightMap.isTexture ) {
  5593. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5594. data.lightMapIntensity = this.lightMapIntensity;
  5595. }
  5596. if ( this.aoMap && this.aoMap.isTexture ) {
  5597. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5598. data.aoMapIntensity = this.aoMapIntensity;
  5599. }
  5600. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5601. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5602. data.bumpScale = this.bumpScale;
  5603. }
  5604. if ( this.normalMap && this.normalMap.isTexture ) {
  5605. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5606. data.normalMapType = this.normalMapType;
  5607. data.normalScale = this.normalScale.toArray();
  5608. }
  5609. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5610. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5611. data.displacementScale = this.displacementScale;
  5612. data.displacementBias = this.displacementBias;
  5613. }
  5614. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5615. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5616. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5617. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5618. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5619. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5620. if ( this.envMap && this.envMap.isTexture ) {
  5621. data.envMap = this.envMap.toJSON( meta ).uuid;
  5622. if ( this.combine !== undefined ) data.combine = this.combine;
  5623. }
  5624. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5625. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5626. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5627. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5628. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5629. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5630. }
  5631. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5632. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5633. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5634. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5635. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5636. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5637. if ( this.size !== undefined ) data.size = this.size;
  5638. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5639. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5640. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5641. if ( this.side !== FrontSide ) data.side = this.side;
  5642. if ( this.vertexColors === true ) data.vertexColors = true;
  5643. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5644. if ( this.transparent === true ) data.transparent = true;
  5645. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5646. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5647. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5648. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5649. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5650. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5651. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5652. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5653. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5654. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5655. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5656. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5657. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5658. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5659. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5660. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5661. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5662. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5663. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5664. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5665. // rotation (SpriteMaterial)
  5666. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5667. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5668. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5669. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5670. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5671. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5672. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5673. if ( this.scale !== undefined ) data.scale = this.scale;
  5674. if ( this.dithering === true ) data.dithering = true;
  5675. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5676. if ( this.alphaHash === true ) data.alphaHash = true;
  5677. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5678. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5679. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5680. if ( this.wireframe === true ) data.wireframe = true;
  5681. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5682. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5683. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5684. if ( this.flatShading === true ) data.flatShading = true;
  5685. if ( this.visible === false ) data.visible = false;
  5686. if ( this.toneMapped === false ) data.toneMapped = false;
  5687. if ( this.fog === false ) data.fog = false;
  5688. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5689. // TODO: Copied from Object3D.toJSON
  5690. function extractFromCache( cache ) {
  5691. const values = [];
  5692. for ( const key in cache ) {
  5693. const data = cache[ key ];
  5694. delete data.metadata;
  5695. values.push( data );
  5696. }
  5697. return values;
  5698. }
  5699. if ( isRootObject ) {
  5700. const textures = extractFromCache( meta.textures );
  5701. const images = extractFromCache( meta.images );
  5702. if ( textures.length > 0 ) data.textures = textures;
  5703. if ( images.length > 0 ) data.images = images;
  5704. }
  5705. return data;
  5706. }
  5707. clone() {
  5708. return new this.constructor().copy( this );
  5709. }
  5710. copy( source ) {
  5711. this.name = source.name;
  5712. this.blending = source.blending;
  5713. this.side = source.side;
  5714. this.vertexColors = source.vertexColors;
  5715. this.opacity = source.opacity;
  5716. this.transparent = source.transparent;
  5717. this.blendSrc = source.blendSrc;
  5718. this.blendDst = source.blendDst;
  5719. this.blendEquation = source.blendEquation;
  5720. this.blendSrcAlpha = source.blendSrcAlpha;
  5721. this.blendDstAlpha = source.blendDstAlpha;
  5722. this.blendEquationAlpha = source.blendEquationAlpha;
  5723. this.blendColor.copy( source.blendColor );
  5724. this.blendAlpha = source.blendAlpha;
  5725. this.depthFunc = source.depthFunc;
  5726. this.depthTest = source.depthTest;
  5727. this.depthWrite = source.depthWrite;
  5728. this.stencilWriteMask = source.stencilWriteMask;
  5729. this.stencilFunc = source.stencilFunc;
  5730. this.stencilRef = source.stencilRef;
  5731. this.stencilFuncMask = source.stencilFuncMask;
  5732. this.stencilFail = source.stencilFail;
  5733. this.stencilZFail = source.stencilZFail;
  5734. this.stencilZPass = source.stencilZPass;
  5735. this.stencilWrite = source.stencilWrite;
  5736. const srcPlanes = source.clippingPlanes;
  5737. let dstPlanes = null;
  5738. if ( srcPlanes !== null ) {
  5739. const n = srcPlanes.length;
  5740. dstPlanes = new Array( n );
  5741. for ( let i = 0; i !== n; ++ i ) {
  5742. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5743. }
  5744. }
  5745. this.clippingPlanes = dstPlanes;
  5746. this.clipIntersection = source.clipIntersection;
  5747. this.clipShadows = source.clipShadows;
  5748. this.shadowSide = source.shadowSide;
  5749. this.colorWrite = source.colorWrite;
  5750. this.precision = source.precision;
  5751. this.polygonOffset = source.polygonOffset;
  5752. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5753. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5754. this.dithering = source.dithering;
  5755. this.alphaTest = source.alphaTest;
  5756. this.alphaHash = source.alphaHash;
  5757. this.alphaToCoverage = source.alphaToCoverage;
  5758. this.premultipliedAlpha = source.premultipliedAlpha;
  5759. this.forceSinglePass = source.forceSinglePass;
  5760. this.visible = source.visible;
  5761. this.toneMapped = source.toneMapped;
  5762. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5763. return this;
  5764. }
  5765. dispose() {
  5766. this.dispatchEvent( { type: 'dispose' } );
  5767. }
  5768. set needsUpdate( value ) {
  5769. if ( value === true ) this.version ++;
  5770. }
  5771. onBuild( /* shaderobject, renderer */ ) {
  5772. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5773. }
  5774. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {
  5775. console.warn( 'Material: onBeforeRender() has been removed.' ); // @deprecated, r166
  5776. }
  5777. }
  5778. class MeshBasicMaterial extends Material {
  5779. constructor( parameters ) {
  5780. super();
  5781. this.isMeshBasicMaterial = true;
  5782. this.type = 'MeshBasicMaterial';
  5783. this.color = new Color( 0xffffff ); // emissive
  5784. this.map = null;
  5785. this.lightMap = null;
  5786. this.lightMapIntensity = 1.0;
  5787. this.aoMap = null;
  5788. this.aoMapIntensity = 1.0;
  5789. this.specularMap = null;
  5790. this.alphaMap = null;
  5791. this.envMap = null;
  5792. this.envMapRotation = new Euler();
  5793. this.combine = MultiplyOperation;
  5794. this.reflectivity = 1;
  5795. this.refractionRatio = 0.98;
  5796. this.wireframe = false;
  5797. this.wireframeLinewidth = 1;
  5798. this.wireframeLinecap = 'round';
  5799. this.wireframeLinejoin = 'round';
  5800. this.fog = true;
  5801. this.setValues( parameters );
  5802. }
  5803. copy( source ) {
  5804. super.copy( source );
  5805. this.color.copy( source.color );
  5806. this.map = source.map;
  5807. this.lightMap = source.lightMap;
  5808. this.lightMapIntensity = source.lightMapIntensity;
  5809. this.aoMap = source.aoMap;
  5810. this.aoMapIntensity = source.aoMapIntensity;
  5811. this.specularMap = source.specularMap;
  5812. this.alphaMap = source.alphaMap;
  5813. this.envMap = source.envMap;
  5814. this.envMapRotation.copy( source.envMapRotation );
  5815. this.combine = source.combine;
  5816. this.reflectivity = source.reflectivity;
  5817. this.refractionRatio = source.refractionRatio;
  5818. this.wireframe = source.wireframe;
  5819. this.wireframeLinewidth = source.wireframeLinewidth;
  5820. this.wireframeLinecap = source.wireframeLinecap;
  5821. this.wireframeLinejoin = source.wireframeLinejoin;
  5822. this.fog = source.fog;
  5823. return this;
  5824. }
  5825. }
  5826. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5827. const _tables = /*@__PURE__*/ _generateTables();
  5828. function _generateTables() {
  5829. // float32 to float16 helpers
  5830. const buffer = new ArrayBuffer( 4 );
  5831. const floatView = new Float32Array( buffer );
  5832. const uint32View = new Uint32Array( buffer );
  5833. const baseTable = new Uint32Array( 512 );
  5834. const shiftTable = new Uint32Array( 512 );
  5835. for ( let i = 0; i < 256; ++ i ) {
  5836. const e = i - 127;
  5837. // very small number (0, -0)
  5838. if ( e < - 27 ) {
  5839. baseTable[ i ] = 0x0000;
  5840. baseTable[ i | 0x100 ] = 0x8000;
  5841. shiftTable[ i ] = 24;
  5842. shiftTable[ i | 0x100 ] = 24;
  5843. // small number (denorm)
  5844. } else if ( e < - 14 ) {
  5845. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5846. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5847. shiftTable[ i ] = - e - 1;
  5848. shiftTable[ i | 0x100 ] = - e - 1;
  5849. // normal number
  5850. } else if ( e <= 15 ) {
  5851. baseTable[ i ] = ( e + 15 ) << 10;
  5852. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5853. shiftTable[ i ] = 13;
  5854. shiftTable[ i | 0x100 ] = 13;
  5855. // large number (Infinity, -Infinity)
  5856. } else if ( e < 128 ) {
  5857. baseTable[ i ] = 0x7c00;
  5858. baseTable[ i | 0x100 ] = 0xfc00;
  5859. shiftTable[ i ] = 24;
  5860. shiftTable[ i | 0x100 ] = 24;
  5861. // stay (NaN, Infinity, -Infinity)
  5862. } else {
  5863. baseTable[ i ] = 0x7c00;
  5864. baseTable[ i | 0x100 ] = 0xfc00;
  5865. shiftTable[ i ] = 13;
  5866. shiftTable[ i | 0x100 ] = 13;
  5867. }
  5868. }
  5869. // float16 to float32 helpers
  5870. const mantissaTable = new Uint32Array( 2048 );
  5871. const exponentTable = new Uint32Array( 64 );
  5872. const offsetTable = new Uint32Array( 64 );
  5873. for ( let i = 1; i < 1024; ++ i ) {
  5874. let m = i << 13; // zero pad mantissa bits
  5875. let e = 0; // zero exponent
  5876. // normalized
  5877. while ( ( m & 0x00800000 ) === 0 ) {
  5878. m <<= 1;
  5879. e -= 0x00800000; // decrement exponent
  5880. }
  5881. m &= ~ 0x00800000; // clear leading 1 bit
  5882. e += 0x38800000; // adjust bias
  5883. mantissaTable[ i ] = m | e;
  5884. }
  5885. for ( let i = 1024; i < 2048; ++ i ) {
  5886. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5887. }
  5888. for ( let i = 1; i < 31; ++ i ) {
  5889. exponentTable[ i ] = i << 23;
  5890. }
  5891. exponentTable[ 31 ] = 0x47800000;
  5892. exponentTable[ 32 ] = 0x80000000;
  5893. for ( let i = 33; i < 63; ++ i ) {
  5894. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5895. }
  5896. exponentTable[ 63 ] = 0xc7800000;
  5897. for ( let i = 1; i < 64; ++ i ) {
  5898. if ( i !== 32 ) {
  5899. offsetTable[ i ] = 1024;
  5900. }
  5901. }
  5902. return {
  5903. floatView: floatView,
  5904. uint32View: uint32View,
  5905. baseTable: baseTable,
  5906. shiftTable: shiftTable,
  5907. mantissaTable: mantissaTable,
  5908. exponentTable: exponentTable,
  5909. offsetTable: offsetTable
  5910. };
  5911. }
  5912. // float32 to float16
  5913. function toHalfFloat( val ) {
  5914. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5915. val = clamp$1( val, - 65504, 65504 );
  5916. _tables.floatView[ 0 ] = val;
  5917. const f = _tables.uint32View[ 0 ];
  5918. const e = ( f >> 23 ) & 0x1ff;
  5919. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5920. }
  5921. // float16 to float32
  5922. function fromHalfFloat( val ) {
  5923. const m = val >> 10;
  5924. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5925. return _tables.floatView[ 0 ];
  5926. }
  5927. const DataUtils = {
  5928. toHalfFloat: toHalfFloat,
  5929. fromHalfFloat: fromHalfFloat,
  5930. };
  5931. const _vector$9 = /*@__PURE__*/ new Vector3();
  5932. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5933. class BufferAttribute {
  5934. constructor( array, itemSize, normalized = false ) {
  5935. if ( Array.isArray( array ) ) {
  5936. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5937. }
  5938. this.isBufferAttribute = true;
  5939. this.name = '';
  5940. this.array = array;
  5941. this.itemSize = itemSize;
  5942. this.count = array !== undefined ? array.length / itemSize : 0;
  5943. this.normalized = normalized;
  5944. this.usage = StaticDrawUsage;
  5945. this._updateRange = { offset: 0, count: - 1 };
  5946. this.updateRanges = [];
  5947. this.gpuType = FloatType;
  5948. this.version = 0;
  5949. }
  5950. onUploadCallback() {}
  5951. set needsUpdate( value ) {
  5952. if ( value === true ) this.version ++;
  5953. }
  5954. get updateRange() {
  5955. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5956. return this._updateRange;
  5957. }
  5958. setUsage( value ) {
  5959. this.usage = value;
  5960. return this;
  5961. }
  5962. addUpdateRange( start, count ) {
  5963. this.updateRanges.push( { start, count } );
  5964. }
  5965. clearUpdateRanges() {
  5966. this.updateRanges.length = 0;
  5967. }
  5968. copy( source ) {
  5969. this.name = source.name;
  5970. this.array = new source.array.constructor( source.array );
  5971. this.itemSize = source.itemSize;
  5972. this.count = source.count;
  5973. this.normalized = source.normalized;
  5974. this.usage = source.usage;
  5975. this.gpuType = source.gpuType;
  5976. return this;
  5977. }
  5978. copyAt( index1, attribute, index2 ) {
  5979. index1 *= this.itemSize;
  5980. index2 *= attribute.itemSize;
  5981. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5982. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5983. }
  5984. return this;
  5985. }
  5986. copyArray( array ) {
  5987. this.array.set( array );
  5988. return this;
  5989. }
  5990. applyMatrix3( m ) {
  5991. if ( this.itemSize === 2 ) {
  5992. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5993. _vector2$1.fromBufferAttribute( this, i );
  5994. _vector2$1.applyMatrix3( m );
  5995. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5996. }
  5997. } else if ( this.itemSize === 3 ) {
  5998. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5999. _vector$9.fromBufferAttribute( this, i );
  6000. _vector$9.applyMatrix3( m );
  6001. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6002. }
  6003. }
  6004. return this;
  6005. }
  6006. applyMatrix4( m ) {
  6007. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6008. _vector$9.fromBufferAttribute( this, i );
  6009. _vector$9.applyMatrix4( m );
  6010. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6011. }
  6012. return this;
  6013. }
  6014. applyNormalMatrix( m ) {
  6015. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6016. _vector$9.fromBufferAttribute( this, i );
  6017. _vector$9.applyNormalMatrix( m );
  6018. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6019. }
  6020. return this;
  6021. }
  6022. transformDirection( m ) {
  6023. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6024. _vector$9.fromBufferAttribute( this, i );
  6025. _vector$9.transformDirection( m );
  6026. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6027. }
  6028. return this;
  6029. }
  6030. set( value, offset = 0 ) {
  6031. // Matching BufferAttribute constructor, do not normalize the array.
  6032. this.array.set( value, offset );
  6033. return this;
  6034. }
  6035. getComponent( index, component ) {
  6036. let value = this.array[ index * this.itemSize + component ];
  6037. if ( this.normalized ) value = denormalize( value, this.array );
  6038. return value;
  6039. }
  6040. setComponent( index, component, value ) {
  6041. if ( this.normalized ) value = normalize$1( value, this.array );
  6042. this.array[ index * this.itemSize + component ] = value;
  6043. return this;
  6044. }
  6045. getX( index ) {
  6046. let x = this.array[ index * this.itemSize ];
  6047. if ( this.normalized ) x = denormalize( x, this.array );
  6048. return x;
  6049. }
  6050. setX( index, x ) {
  6051. if ( this.normalized ) x = normalize$1( x, this.array );
  6052. this.array[ index * this.itemSize ] = x;
  6053. return this;
  6054. }
  6055. getY( index ) {
  6056. let y = this.array[ index * this.itemSize + 1 ];
  6057. if ( this.normalized ) y = denormalize( y, this.array );
  6058. return y;
  6059. }
  6060. setY( index, y ) {
  6061. if ( this.normalized ) y = normalize$1( y, this.array );
  6062. this.array[ index * this.itemSize + 1 ] = y;
  6063. return this;
  6064. }
  6065. getZ( index ) {
  6066. let z = this.array[ index * this.itemSize + 2 ];
  6067. if ( this.normalized ) z = denormalize( z, this.array );
  6068. return z;
  6069. }
  6070. setZ( index, z ) {
  6071. if ( this.normalized ) z = normalize$1( z, this.array );
  6072. this.array[ index * this.itemSize + 2 ] = z;
  6073. return this;
  6074. }
  6075. getW( index ) {
  6076. let w = this.array[ index * this.itemSize + 3 ];
  6077. if ( this.normalized ) w = denormalize( w, this.array );
  6078. return w;
  6079. }
  6080. setW( index, w ) {
  6081. if ( this.normalized ) w = normalize$1( w, this.array );
  6082. this.array[ index * this.itemSize + 3 ] = w;
  6083. return this;
  6084. }
  6085. setXY( index, x, y ) {
  6086. index *= this.itemSize;
  6087. if ( this.normalized ) {
  6088. x = normalize$1( x, this.array );
  6089. y = normalize$1( y, this.array );
  6090. }
  6091. this.array[ index + 0 ] = x;
  6092. this.array[ index + 1 ] = y;
  6093. return this;
  6094. }
  6095. setXYZ( index, x, y, z ) {
  6096. index *= this.itemSize;
  6097. if ( this.normalized ) {
  6098. x = normalize$1( x, this.array );
  6099. y = normalize$1( y, this.array );
  6100. z = normalize$1( z, this.array );
  6101. }
  6102. this.array[ index + 0 ] = x;
  6103. this.array[ index + 1 ] = y;
  6104. this.array[ index + 2 ] = z;
  6105. return this;
  6106. }
  6107. setXYZW( index, x, y, z, w ) {
  6108. index *= this.itemSize;
  6109. if ( this.normalized ) {
  6110. x = normalize$1( x, this.array );
  6111. y = normalize$1( y, this.array );
  6112. z = normalize$1( z, this.array );
  6113. w = normalize$1( w, this.array );
  6114. }
  6115. this.array[ index + 0 ] = x;
  6116. this.array[ index + 1 ] = y;
  6117. this.array[ index + 2 ] = z;
  6118. this.array[ index + 3 ] = w;
  6119. return this;
  6120. }
  6121. onUpload( callback ) {
  6122. this.onUploadCallback = callback;
  6123. return this;
  6124. }
  6125. clone() {
  6126. return new this.constructor( this.array, this.itemSize ).copy( this );
  6127. }
  6128. toJSON() {
  6129. const data = {
  6130. itemSize: this.itemSize,
  6131. type: this.array.constructor.name,
  6132. array: Array.from( this.array ),
  6133. normalized: this.normalized
  6134. };
  6135. if ( this.name !== '' ) data.name = this.name;
  6136. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6137. return data;
  6138. }
  6139. }
  6140. //
  6141. class Int8BufferAttribute extends BufferAttribute {
  6142. constructor( array, itemSize, normalized ) {
  6143. super( new Int8Array( array ), itemSize, normalized );
  6144. }
  6145. }
  6146. class Uint8BufferAttribute extends BufferAttribute {
  6147. constructor( array, itemSize, normalized ) {
  6148. super( new Uint8Array( array ), itemSize, normalized );
  6149. }
  6150. }
  6151. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6152. constructor( array, itemSize, normalized ) {
  6153. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6154. }
  6155. }
  6156. class Int16BufferAttribute extends BufferAttribute {
  6157. constructor( array, itemSize, normalized ) {
  6158. super( new Int16Array( array ), itemSize, normalized );
  6159. }
  6160. }
  6161. class Uint16BufferAttribute extends BufferAttribute {
  6162. constructor( array, itemSize, normalized ) {
  6163. super( new Uint16Array( array ), itemSize, normalized );
  6164. }
  6165. }
  6166. class Int32BufferAttribute extends BufferAttribute {
  6167. constructor( array, itemSize, normalized ) {
  6168. super( new Int32Array( array ), itemSize, normalized );
  6169. }
  6170. }
  6171. class Uint32BufferAttribute extends BufferAttribute {
  6172. constructor( array, itemSize, normalized ) {
  6173. super( new Uint32Array( array ), itemSize, normalized );
  6174. }
  6175. }
  6176. class Float16BufferAttribute extends BufferAttribute {
  6177. constructor( array, itemSize, normalized ) {
  6178. super( new Uint16Array( array ), itemSize, normalized );
  6179. this.isFloat16BufferAttribute = true;
  6180. }
  6181. getX( index ) {
  6182. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6183. if ( this.normalized ) x = denormalize( x, this.array );
  6184. return x;
  6185. }
  6186. setX( index, x ) {
  6187. if ( this.normalized ) x = normalize$1( x, this.array );
  6188. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6189. return this;
  6190. }
  6191. getY( index ) {
  6192. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6193. if ( this.normalized ) y = denormalize( y, this.array );
  6194. return y;
  6195. }
  6196. setY( index, y ) {
  6197. if ( this.normalized ) y = normalize$1( y, this.array );
  6198. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6199. return this;
  6200. }
  6201. getZ( index ) {
  6202. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6203. if ( this.normalized ) z = denormalize( z, this.array );
  6204. return z;
  6205. }
  6206. setZ( index, z ) {
  6207. if ( this.normalized ) z = normalize$1( z, this.array );
  6208. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6209. return this;
  6210. }
  6211. getW( index ) {
  6212. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6213. if ( this.normalized ) w = denormalize( w, this.array );
  6214. return w;
  6215. }
  6216. setW( index, w ) {
  6217. if ( this.normalized ) w = normalize$1( w, this.array );
  6218. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6219. return this;
  6220. }
  6221. setXY( index, x, y ) {
  6222. index *= this.itemSize;
  6223. if ( this.normalized ) {
  6224. x = normalize$1( x, this.array );
  6225. y = normalize$1( y, this.array );
  6226. }
  6227. this.array[ index + 0 ] = toHalfFloat( x );
  6228. this.array[ index + 1 ] = toHalfFloat( y );
  6229. return this;
  6230. }
  6231. setXYZ( index, x, y, z ) {
  6232. index *= this.itemSize;
  6233. if ( this.normalized ) {
  6234. x = normalize$1( x, this.array );
  6235. y = normalize$1( y, this.array );
  6236. z = normalize$1( z, this.array );
  6237. }
  6238. this.array[ index + 0 ] = toHalfFloat( x );
  6239. this.array[ index + 1 ] = toHalfFloat( y );
  6240. this.array[ index + 2 ] = toHalfFloat( z );
  6241. return this;
  6242. }
  6243. setXYZW( index, x, y, z, w ) {
  6244. index *= this.itemSize;
  6245. if ( this.normalized ) {
  6246. x = normalize$1( x, this.array );
  6247. y = normalize$1( y, this.array );
  6248. z = normalize$1( z, this.array );
  6249. w = normalize$1( w, this.array );
  6250. }
  6251. this.array[ index + 0 ] = toHalfFloat( x );
  6252. this.array[ index + 1 ] = toHalfFloat( y );
  6253. this.array[ index + 2 ] = toHalfFloat( z );
  6254. this.array[ index + 3 ] = toHalfFloat( w );
  6255. return this;
  6256. }
  6257. }
  6258. class Float32BufferAttribute extends BufferAttribute {
  6259. constructor( array, itemSize, normalized ) {
  6260. super( new Float32Array( array ), itemSize, normalized );
  6261. }
  6262. }
  6263. let _id$6 = 0;
  6264. const _m1 = /*@__PURE__*/ new Matrix4();
  6265. const _obj = /*@__PURE__*/ new Object3D();
  6266. const _offset = /*@__PURE__*/ new Vector3();
  6267. const _box$2 = /*@__PURE__*/ new Box3();
  6268. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6269. const _vector$8 = /*@__PURE__*/ new Vector3();
  6270. class BufferGeometry extends EventDispatcher {
  6271. constructor() {
  6272. super();
  6273. this.isBufferGeometry = true;
  6274. Object.defineProperty( this, 'id', { value: _id$6 ++ } );
  6275. this.uuid = generateUUID();
  6276. this.name = '';
  6277. this.type = 'BufferGeometry';
  6278. this.index = null;
  6279. this.attributes = {};
  6280. this.morphAttributes = {};
  6281. this.morphTargetsRelative = false;
  6282. this.groups = [];
  6283. this.boundingBox = null;
  6284. this.boundingSphere = null;
  6285. this.drawRange = { start: 0, count: Infinity };
  6286. this.userData = {};
  6287. }
  6288. getIndex() {
  6289. return this.index;
  6290. }
  6291. setIndex( index ) {
  6292. if ( Array.isArray( index ) ) {
  6293. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6294. } else {
  6295. this.index = index;
  6296. }
  6297. return this;
  6298. }
  6299. getAttribute( name ) {
  6300. return this.attributes[ name ];
  6301. }
  6302. setAttribute( name, attribute ) {
  6303. this.attributes[ name ] = attribute;
  6304. return this;
  6305. }
  6306. deleteAttribute( name ) {
  6307. delete this.attributes[ name ];
  6308. return this;
  6309. }
  6310. hasAttribute( name ) {
  6311. return this.attributes[ name ] !== undefined;
  6312. }
  6313. addGroup( start, count, materialIndex = 0 ) {
  6314. this.groups.push( {
  6315. start: start,
  6316. count: count,
  6317. materialIndex: materialIndex
  6318. } );
  6319. }
  6320. clearGroups() {
  6321. this.groups = [];
  6322. }
  6323. setDrawRange( start, count ) {
  6324. this.drawRange.start = start;
  6325. this.drawRange.count = count;
  6326. }
  6327. applyMatrix4( matrix ) {
  6328. const position = this.attributes.position;
  6329. if ( position !== undefined ) {
  6330. position.applyMatrix4( matrix );
  6331. position.needsUpdate = true;
  6332. }
  6333. const normal = this.attributes.normal;
  6334. if ( normal !== undefined ) {
  6335. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6336. normal.applyNormalMatrix( normalMatrix );
  6337. normal.needsUpdate = true;
  6338. }
  6339. const tangent = this.attributes.tangent;
  6340. if ( tangent !== undefined ) {
  6341. tangent.transformDirection( matrix );
  6342. tangent.needsUpdate = true;
  6343. }
  6344. if ( this.boundingBox !== null ) {
  6345. this.computeBoundingBox();
  6346. }
  6347. if ( this.boundingSphere !== null ) {
  6348. this.computeBoundingSphere();
  6349. }
  6350. return this;
  6351. }
  6352. applyQuaternion( q ) {
  6353. _m1.makeRotationFromQuaternion( q );
  6354. this.applyMatrix4( _m1 );
  6355. return this;
  6356. }
  6357. rotateX( angle ) {
  6358. // rotate geometry around world x-axis
  6359. _m1.makeRotationX( angle );
  6360. this.applyMatrix4( _m1 );
  6361. return this;
  6362. }
  6363. rotateY( angle ) {
  6364. // rotate geometry around world y-axis
  6365. _m1.makeRotationY( angle );
  6366. this.applyMatrix4( _m1 );
  6367. return this;
  6368. }
  6369. rotateZ( angle ) {
  6370. // rotate geometry around world z-axis
  6371. _m1.makeRotationZ( angle );
  6372. this.applyMatrix4( _m1 );
  6373. return this;
  6374. }
  6375. translate( x, y, z ) {
  6376. // translate geometry
  6377. _m1.makeTranslation( x, y, z );
  6378. this.applyMatrix4( _m1 );
  6379. return this;
  6380. }
  6381. scale( x, y, z ) {
  6382. // scale geometry
  6383. _m1.makeScale( x, y, z );
  6384. this.applyMatrix4( _m1 );
  6385. return this;
  6386. }
  6387. lookAt( vector ) {
  6388. _obj.lookAt( vector );
  6389. _obj.updateMatrix();
  6390. this.applyMatrix4( _obj.matrix );
  6391. return this;
  6392. }
  6393. center() {
  6394. this.computeBoundingBox();
  6395. this.boundingBox.getCenter( _offset ).negate();
  6396. this.translate( _offset.x, _offset.y, _offset.z );
  6397. return this;
  6398. }
  6399. setFromPoints( points ) {
  6400. const position = [];
  6401. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6402. const point = points[ i ];
  6403. position.push( point.x, point.y, point.z || 0 );
  6404. }
  6405. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6406. return this;
  6407. }
  6408. computeBoundingBox() {
  6409. if ( this.boundingBox === null ) {
  6410. this.boundingBox = new Box3();
  6411. }
  6412. const position = this.attributes.position;
  6413. const morphAttributesPosition = this.morphAttributes.position;
  6414. if ( position && position.isGLBufferAttribute ) {
  6415. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6416. this.boundingBox.set(
  6417. new Vector3( - Infinity, - Infinity, - Infinity ),
  6418. new Vector3( + Infinity, + Infinity, + Infinity )
  6419. );
  6420. return;
  6421. }
  6422. if ( position !== undefined ) {
  6423. this.boundingBox.setFromBufferAttribute( position );
  6424. // process morph attributes if present
  6425. if ( morphAttributesPosition ) {
  6426. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6427. const morphAttribute = morphAttributesPosition[ i ];
  6428. _box$2.setFromBufferAttribute( morphAttribute );
  6429. if ( this.morphTargetsRelative ) {
  6430. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6431. this.boundingBox.expandByPoint( _vector$8 );
  6432. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6433. this.boundingBox.expandByPoint( _vector$8 );
  6434. } else {
  6435. this.boundingBox.expandByPoint( _box$2.min );
  6436. this.boundingBox.expandByPoint( _box$2.max );
  6437. }
  6438. }
  6439. }
  6440. } else {
  6441. this.boundingBox.makeEmpty();
  6442. }
  6443. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6444. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6445. }
  6446. }
  6447. computeBoundingSphere() {
  6448. if ( this.boundingSphere === null ) {
  6449. this.boundingSphere = new Sphere();
  6450. }
  6451. const position = this.attributes.position;
  6452. const morphAttributesPosition = this.morphAttributes.position;
  6453. if ( position && position.isGLBufferAttribute ) {
  6454. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6455. this.boundingSphere.set( new Vector3(), Infinity );
  6456. return;
  6457. }
  6458. if ( position ) {
  6459. // first, find the center of the bounding sphere
  6460. const center = this.boundingSphere.center;
  6461. _box$2.setFromBufferAttribute( position );
  6462. // process morph attributes if present
  6463. if ( morphAttributesPosition ) {
  6464. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6465. const morphAttribute = morphAttributesPosition[ i ];
  6466. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6467. if ( this.morphTargetsRelative ) {
  6468. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6469. _box$2.expandByPoint( _vector$8 );
  6470. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6471. _box$2.expandByPoint( _vector$8 );
  6472. } else {
  6473. _box$2.expandByPoint( _boxMorphTargets.min );
  6474. _box$2.expandByPoint( _boxMorphTargets.max );
  6475. }
  6476. }
  6477. }
  6478. _box$2.getCenter( center );
  6479. // second, try to find a boundingSphere with a radius smaller than the
  6480. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6481. let maxRadiusSq = 0;
  6482. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6483. _vector$8.fromBufferAttribute( position, i );
  6484. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6485. }
  6486. // process morph attributes if present
  6487. if ( morphAttributesPosition ) {
  6488. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6489. const morphAttribute = morphAttributesPosition[ i ];
  6490. const morphTargetsRelative = this.morphTargetsRelative;
  6491. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6492. _vector$8.fromBufferAttribute( morphAttribute, j );
  6493. if ( morphTargetsRelative ) {
  6494. _offset.fromBufferAttribute( position, j );
  6495. _vector$8.add( _offset );
  6496. }
  6497. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6498. }
  6499. }
  6500. }
  6501. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6502. if ( isNaN( this.boundingSphere.radius ) ) {
  6503. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6504. }
  6505. }
  6506. }
  6507. computeTangents() {
  6508. const index = this.index;
  6509. const attributes = this.attributes;
  6510. // based on http://www.terathon.com/code/tangent.html
  6511. // (per vertex tangents)
  6512. if ( index === null ||
  6513. attributes.position === undefined ||
  6514. attributes.normal === undefined ||
  6515. attributes.uv === undefined ) {
  6516. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6517. return;
  6518. }
  6519. const positionAttribute = attributes.position;
  6520. const normalAttribute = attributes.normal;
  6521. const uvAttribute = attributes.uv;
  6522. if ( this.hasAttribute( 'tangent' ) === false ) {
  6523. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6524. }
  6525. const tangentAttribute = this.getAttribute( 'tangent' );
  6526. const tan1 = [], tan2 = [];
  6527. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6528. tan1[ i ] = new Vector3();
  6529. tan2[ i ] = new Vector3();
  6530. }
  6531. const vA = new Vector3(),
  6532. vB = new Vector3(),
  6533. vC = new Vector3(),
  6534. uvA = new Vector2(),
  6535. uvB = new Vector2(),
  6536. uvC = new Vector2(),
  6537. sdir = new Vector3(),
  6538. tdir = new Vector3();
  6539. function handleTriangle( a, b, c ) {
  6540. vA.fromBufferAttribute( positionAttribute, a );
  6541. vB.fromBufferAttribute( positionAttribute, b );
  6542. vC.fromBufferAttribute( positionAttribute, c );
  6543. uvA.fromBufferAttribute( uvAttribute, a );
  6544. uvB.fromBufferAttribute( uvAttribute, b );
  6545. uvC.fromBufferAttribute( uvAttribute, c );
  6546. vB.sub( vA );
  6547. vC.sub( vA );
  6548. uvB.sub( uvA );
  6549. uvC.sub( uvA );
  6550. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6551. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6552. if ( ! isFinite( r ) ) return;
  6553. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6554. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6555. tan1[ a ].add( sdir );
  6556. tan1[ b ].add( sdir );
  6557. tan1[ c ].add( sdir );
  6558. tan2[ a ].add( tdir );
  6559. tan2[ b ].add( tdir );
  6560. tan2[ c ].add( tdir );
  6561. }
  6562. let groups = this.groups;
  6563. if ( groups.length === 0 ) {
  6564. groups = [ {
  6565. start: 0,
  6566. count: index.count
  6567. } ];
  6568. }
  6569. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6570. const group = groups[ i ];
  6571. const start = group.start;
  6572. const count = group.count;
  6573. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6574. handleTriangle(
  6575. index.getX( j + 0 ),
  6576. index.getX( j + 1 ),
  6577. index.getX( j + 2 )
  6578. );
  6579. }
  6580. }
  6581. const tmp = new Vector3(), tmp2 = new Vector3();
  6582. const n = new Vector3(), n2 = new Vector3();
  6583. function handleVertex( v ) {
  6584. n.fromBufferAttribute( normalAttribute, v );
  6585. n2.copy( n );
  6586. const t = tan1[ v ];
  6587. // Gram-Schmidt orthogonalize
  6588. tmp.copy( t );
  6589. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6590. // Calculate handedness
  6591. tmp2.crossVectors( n2, t );
  6592. const test = tmp2.dot( tan2[ v ] );
  6593. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6594. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6595. }
  6596. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6597. const group = groups[ i ];
  6598. const start = group.start;
  6599. const count = group.count;
  6600. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6601. handleVertex( index.getX( j + 0 ) );
  6602. handleVertex( index.getX( j + 1 ) );
  6603. handleVertex( index.getX( j + 2 ) );
  6604. }
  6605. }
  6606. }
  6607. computeVertexNormals() {
  6608. const index = this.index;
  6609. const positionAttribute = this.getAttribute( 'position' );
  6610. if ( positionAttribute !== undefined ) {
  6611. let normalAttribute = this.getAttribute( 'normal' );
  6612. if ( normalAttribute === undefined ) {
  6613. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6614. this.setAttribute( 'normal', normalAttribute );
  6615. } else {
  6616. // reset existing normals to zero
  6617. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6618. normalAttribute.setXYZ( i, 0, 0, 0 );
  6619. }
  6620. }
  6621. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6622. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6623. const cb = new Vector3(), ab = new Vector3();
  6624. // indexed elements
  6625. if ( index ) {
  6626. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6627. const vA = index.getX( i + 0 );
  6628. const vB = index.getX( i + 1 );
  6629. const vC = index.getX( i + 2 );
  6630. pA.fromBufferAttribute( positionAttribute, vA );
  6631. pB.fromBufferAttribute( positionAttribute, vB );
  6632. pC.fromBufferAttribute( positionAttribute, vC );
  6633. cb.subVectors( pC, pB );
  6634. ab.subVectors( pA, pB );
  6635. cb.cross( ab );
  6636. nA.fromBufferAttribute( normalAttribute, vA );
  6637. nB.fromBufferAttribute( normalAttribute, vB );
  6638. nC.fromBufferAttribute( normalAttribute, vC );
  6639. nA.add( cb );
  6640. nB.add( cb );
  6641. nC.add( cb );
  6642. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6643. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6644. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6645. }
  6646. } else {
  6647. // non-indexed elements (unconnected triangle soup)
  6648. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6649. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6650. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6651. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6652. cb.subVectors( pC, pB );
  6653. ab.subVectors( pA, pB );
  6654. cb.cross( ab );
  6655. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6656. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6657. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6658. }
  6659. }
  6660. this.normalizeNormals();
  6661. normalAttribute.needsUpdate = true;
  6662. }
  6663. }
  6664. normalizeNormals() {
  6665. const normals = this.attributes.normal;
  6666. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6667. _vector$8.fromBufferAttribute( normals, i );
  6668. _vector$8.normalize();
  6669. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6670. }
  6671. }
  6672. toNonIndexed() {
  6673. function convertBufferAttribute( attribute, indices ) {
  6674. const array = attribute.array;
  6675. const itemSize = attribute.itemSize;
  6676. const normalized = attribute.normalized;
  6677. const array2 = new array.constructor( indices.length * itemSize );
  6678. let index = 0, index2 = 0;
  6679. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6680. if ( attribute.isInterleavedBufferAttribute ) {
  6681. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6682. } else {
  6683. index = indices[ i ] * itemSize;
  6684. }
  6685. for ( let j = 0; j < itemSize; j ++ ) {
  6686. array2[ index2 ++ ] = array[ index ++ ];
  6687. }
  6688. }
  6689. return new BufferAttribute( array2, itemSize, normalized );
  6690. }
  6691. //
  6692. if ( this.index === null ) {
  6693. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6694. return this;
  6695. }
  6696. const geometry2 = new BufferGeometry();
  6697. const indices = this.index.array;
  6698. const attributes = this.attributes;
  6699. // attributes
  6700. for ( const name in attributes ) {
  6701. const attribute = attributes[ name ];
  6702. const newAttribute = convertBufferAttribute( attribute, indices );
  6703. geometry2.setAttribute( name, newAttribute );
  6704. }
  6705. // morph attributes
  6706. const morphAttributes = this.morphAttributes;
  6707. for ( const name in morphAttributes ) {
  6708. const morphArray = [];
  6709. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6710. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6711. const attribute = morphAttribute[ i ];
  6712. const newAttribute = convertBufferAttribute( attribute, indices );
  6713. morphArray.push( newAttribute );
  6714. }
  6715. geometry2.morphAttributes[ name ] = morphArray;
  6716. }
  6717. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6718. // groups
  6719. const groups = this.groups;
  6720. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6721. const group = groups[ i ];
  6722. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6723. }
  6724. return geometry2;
  6725. }
  6726. toJSON() {
  6727. const data = {
  6728. metadata: {
  6729. version: 4.6,
  6730. type: 'BufferGeometry',
  6731. generator: 'BufferGeometry.toJSON'
  6732. }
  6733. };
  6734. // standard BufferGeometry serialization
  6735. data.uuid = this.uuid;
  6736. data.type = this.type;
  6737. if ( this.name !== '' ) data.name = this.name;
  6738. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6739. if ( this.parameters !== undefined ) {
  6740. const parameters = this.parameters;
  6741. for ( const key in parameters ) {
  6742. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6743. }
  6744. return data;
  6745. }
  6746. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6747. data.data = { attributes: {} };
  6748. const index = this.index;
  6749. if ( index !== null ) {
  6750. data.data.index = {
  6751. type: index.array.constructor.name,
  6752. array: Array.prototype.slice.call( index.array )
  6753. };
  6754. }
  6755. const attributes = this.attributes;
  6756. for ( const key in attributes ) {
  6757. const attribute = attributes[ key ];
  6758. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6759. }
  6760. const morphAttributes = {};
  6761. let hasMorphAttributes = false;
  6762. for ( const key in this.morphAttributes ) {
  6763. const attributeArray = this.morphAttributes[ key ];
  6764. const array = [];
  6765. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6766. const attribute = attributeArray[ i ];
  6767. array.push( attribute.toJSON( data.data ) );
  6768. }
  6769. if ( array.length > 0 ) {
  6770. morphAttributes[ key ] = array;
  6771. hasMorphAttributes = true;
  6772. }
  6773. }
  6774. if ( hasMorphAttributes ) {
  6775. data.data.morphAttributes = morphAttributes;
  6776. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6777. }
  6778. const groups = this.groups;
  6779. if ( groups.length > 0 ) {
  6780. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6781. }
  6782. const boundingSphere = this.boundingSphere;
  6783. if ( boundingSphere !== null ) {
  6784. data.data.boundingSphere = {
  6785. center: boundingSphere.center.toArray(),
  6786. radius: boundingSphere.radius
  6787. };
  6788. }
  6789. return data;
  6790. }
  6791. clone() {
  6792. return new this.constructor().copy( this );
  6793. }
  6794. copy( source ) {
  6795. // reset
  6796. this.index = null;
  6797. this.attributes = {};
  6798. this.morphAttributes = {};
  6799. this.groups = [];
  6800. this.boundingBox = null;
  6801. this.boundingSphere = null;
  6802. // used for storing cloned, shared data
  6803. const data = {};
  6804. // name
  6805. this.name = source.name;
  6806. // index
  6807. const index = source.index;
  6808. if ( index !== null ) {
  6809. this.setIndex( index.clone( data ) );
  6810. }
  6811. // attributes
  6812. const attributes = source.attributes;
  6813. for ( const name in attributes ) {
  6814. const attribute = attributes[ name ];
  6815. this.setAttribute( name, attribute.clone( data ) );
  6816. }
  6817. // morph attributes
  6818. const morphAttributes = source.morphAttributes;
  6819. for ( const name in morphAttributes ) {
  6820. const array = [];
  6821. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6822. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6823. array.push( morphAttribute[ i ].clone( data ) );
  6824. }
  6825. this.morphAttributes[ name ] = array;
  6826. }
  6827. this.morphTargetsRelative = source.morphTargetsRelative;
  6828. // groups
  6829. const groups = source.groups;
  6830. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6831. const group = groups[ i ];
  6832. this.addGroup( group.start, group.count, group.materialIndex );
  6833. }
  6834. // bounding box
  6835. const boundingBox = source.boundingBox;
  6836. if ( boundingBox !== null ) {
  6837. this.boundingBox = boundingBox.clone();
  6838. }
  6839. // bounding sphere
  6840. const boundingSphere = source.boundingSphere;
  6841. if ( boundingSphere !== null ) {
  6842. this.boundingSphere = boundingSphere.clone();
  6843. }
  6844. // draw range
  6845. this.drawRange.start = source.drawRange.start;
  6846. this.drawRange.count = source.drawRange.count;
  6847. // user data
  6848. this.userData = source.userData;
  6849. return this;
  6850. }
  6851. dispose() {
  6852. this.dispatchEvent( { type: 'dispose' } );
  6853. }
  6854. }
  6855. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6856. const _ray$3 = /*@__PURE__*/ new Ray();
  6857. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6858. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6859. const _vA$1 = /*@__PURE__*/ new Vector3();
  6860. const _vB$1 = /*@__PURE__*/ new Vector3();
  6861. const _vC$1 = /*@__PURE__*/ new Vector3();
  6862. const _tempA = /*@__PURE__*/ new Vector3();
  6863. const _morphA = /*@__PURE__*/ new Vector3();
  6864. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6865. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6866. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6867. const _normalA = /*@__PURE__*/ new Vector3();
  6868. const _normalB = /*@__PURE__*/ new Vector3();
  6869. const _normalC = /*@__PURE__*/ new Vector3();
  6870. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6871. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6872. class Mesh extends Object3D {
  6873. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6874. super();
  6875. this.isMesh = true;
  6876. this.type = 'Mesh';
  6877. this.geometry = geometry;
  6878. this.material = material;
  6879. this.updateMorphTargets();
  6880. }
  6881. copy( source, recursive ) {
  6882. super.copy( source, recursive );
  6883. if ( source.morphTargetInfluences !== undefined ) {
  6884. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6885. }
  6886. if ( source.morphTargetDictionary !== undefined ) {
  6887. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6888. }
  6889. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6890. this.geometry = source.geometry;
  6891. return this;
  6892. }
  6893. updateMorphTargets() {
  6894. const geometry = this.geometry;
  6895. const morphAttributes = geometry.morphAttributes;
  6896. const keys = Object.keys( morphAttributes );
  6897. if ( keys.length > 0 ) {
  6898. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6899. if ( morphAttribute !== undefined ) {
  6900. this.morphTargetInfluences = [];
  6901. this.morphTargetDictionary = {};
  6902. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6903. const name = morphAttribute[ m ].name || String( m );
  6904. this.morphTargetInfluences.push( 0 );
  6905. this.morphTargetDictionary[ name ] = m;
  6906. }
  6907. }
  6908. }
  6909. }
  6910. getVertexPosition( index, target ) {
  6911. const geometry = this.geometry;
  6912. const position = geometry.attributes.position;
  6913. const morphPosition = geometry.morphAttributes.position;
  6914. const morphTargetsRelative = geometry.morphTargetsRelative;
  6915. target.fromBufferAttribute( position, index );
  6916. const morphInfluences = this.morphTargetInfluences;
  6917. if ( morphPosition && morphInfluences ) {
  6918. _morphA.set( 0, 0, 0 );
  6919. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6920. const influence = morphInfluences[ i ];
  6921. const morphAttribute = morphPosition[ i ];
  6922. if ( influence === 0 ) continue;
  6923. _tempA.fromBufferAttribute( morphAttribute, index );
  6924. if ( morphTargetsRelative ) {
  6925. _morphA.addScaledVector( _tempA, influence );
  6926. } else {
  6927. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6928. }
  6929. }
  6930. target.add( _morphA );
  6931. }
  6932. return target;
  6933. }
  6934. raycast( raycaster, intersects ) {
  6935. const geometry = this.geometry;
  6936. const material = this.material;
  6937. const matrixWorld = this.matrixWorld;
  6938. if ( material === undefined ) return;
  6939. // test with bounding sphere in world space
  6940. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6941. _sphere$6.copy( geometry.boundingSphere );
  6942. _sphere$6.applyMatrix4( matrixWorld );
  6943. // check distance from ray origin to bounding sphere
  6944. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6945. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6946. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6947. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6948. }
  6949. // convert ray to local space of mesh
  6950. _inverseMatrix$3.copy( matrixWorld ).invert();
  6951. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6952. // test with bounding box in local space
  6953. if ( geometry.boundingBox !== null ) {
  6954. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6955. }
  6956. // test for intersections with geometry
  6957. this._computeIntersections( raycaster, intersects, _ray$3 );
  6958. }
  6959. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6960. let intersection;
  6961. const geometry = this.geometry;
  6962. const material = this.material;
  6963. const index = geometry.index;
  6964. const position = geometry.attributes.position;
  6965. const uv = geometry.attributes.uv;
  6966. const uv1 = geometry.attributes.uv1;
  6967. const normal = geometry.attributes.normal;
  6968. const groups = geometry.groups;
  6969. const drawRange = geometry.drawRange;
  6970. if ( index !== null ) {
  6971. // indexed buffer geometry
  6972. if ( Array.isArray( material ) ) {
  6973. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6974. const group = groups[ i ];
  6975. const groupMaterial = material[ group.materialIndex ];
  6976. const start = Math.max( group.start, drawRange.start );
  6977. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6978. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6979. const a = index.getX( j );
  6980. const b = index.getX( j + 1 );
  6981. const c = index.getX( j + 2 );
  6982. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6983. if ( intersection ) {
  6984. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6985. intersection.face.materialIndex = group.materialIndex;
  6986. intersects.push( intersection );
  6987. }
  6988. }
  6989. }
  6990. } else {
  6991. const start = Math.max( 0, drawRange.start );
  6992. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6993. for ( let i = start, il = end; i < il; i += 3 ) {
  6994. const a = index.getX( i );
  6995. const b = index.getX( i + 1 );
  6996. const c = index.getX( i + 2 );
  6997. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6998. if ( intersection ) {
  6999. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7000. intersects.push( intersection );
  7001. }
  7002. }
  7003. }
  7004. } else if ( position !== undefined ) {
  7005. // non-indexed buffer geometry
  7006. if ( Array.isArray( material ) ) {
  7007. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7008. const group = groups[ i ];
  7009. const groupMaterial = material[ group.materialIndex ];
  7010. const start = Math.max( group.start, drawRange.start );
  7011. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7012. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7013. const a = j;
  7014. const b = j + 1;
  7015. const c = j + 2;
  7016. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7017. if ( intersection ) {
  7018. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7019. intersection.face.materialIndex = group.materialIndex;
  7020. intersects.push( intersection );
  7021. }
  7022. }
  7023. }
  7024. } else {
  7025. const start = Math.max( 0, drawRange.start );
  7026. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7027. for ( let i = start, il = end; i < il; i += 3 ) {
  7028. const a = i;
  7029. const b = i + 1;
  7030. const c = i + 2;
  7031. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7032. if ( intersection ) {
  7033. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7034. intersects.push( intersection );
  7035. }
  7036. }
  7037. }
  7038. }
  7039. }
  7040. }
  7041. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7042. let intersect;
  7043. if ( material.side === BackSide ) {
  7044. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7045. } else {
  7046. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7047. }
  7048. if ( intersect === null ) return null;
  7049. _intersectionPointWorld.copy( point );
  7050. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7051. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7052. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7053. return {
  7054. distance: distance,
  7055. point: _intersectionPointWorld.clone(),
  7056. object: object
  7057. };
  7058. }
  7059. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7060. object.getVertexPosition( a, _vA$1 );
  7061. object.getVertexPosition( b, _vB$1 );
  7062. object.getVertexPosition( c, _vC$1 );
  7063. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7064. if ( intersection ) {
  7065. if ( uv ) {
  7066. _uvA$1.fromBufferAttribute( uv, a );
  7067. _uvB$1.fromBufferAttribute( uv, b );
  7068. _uvC$1.fromBufferAttribute( uv, c );
  7069. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7070. }
  7071. if ( uv1 ) {
  7072. _uvA$1.fromBufferAttribute( uv1, a );
  7073. _uvB$1.fromBufferAttribute( uv1, b );
  7074. _uvC$1.fromBufferAttribute( uv1, c );
  7075. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7076. }
  7077. if ( normal ) {
  7078. _normalA.fromBufferAttribute( normal, a );
  7079. _normalB.fromBufferAttribute( normal, b );
  7080. _normalC.fromBufferAttribute( normal, c );
  7081. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7082. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7083. intersection.normal.multiplyScalar( - 1 );
  7084. }
  7085. }
  7086. const face = {
  7087. a: a,
  7088. b: b,
  7089. c: c,
  7090. normal: new Vector3(),
  7091. materialIndex: 0
  7092. };
  7093. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7094. intersection.face = face;
  7095. }
  7096. return intersection;
  7097. }
  7098. class BoxGeometry extends BufferGeometry {
  7099. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7100. super();
  7101. this.type = 'BoxGeometry';
  7102. this.parameters = {
  7103. width: width,
  7104. height: height,
  7105. depth: depth,
  7106. widthSegments: widthSegments,
  7107. heightSegments: heightSegments,
  7108. depthSegments: depthSegments
  7109. };
  7110. const scope = this;
  7111. // segments
  7112. widthSegments = Math.floor( widthSegments );
  7113. heightSegments = Math.floor( heightSegments );
  7114. depthSegments = Math.floor( depthSegments );
  7115. // buffers
  7116. const indices = [];
  7117. const vertices = [];
  7118. const normals = [];
  7119. const uvs = [];
  7120. // helper variables
  7121. let numberOfVertices = 0;
  7122. let groupStart = 0;
  7123. // build each side of the box geometry
  7124. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7125. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7126. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7127. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7128. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7129. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7130. // build geometry
  7131. this.setIndex( indices );
  7132. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7133. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7134. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7135. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7136. const segmentWidth = width / gridX;
  7137. const segmentHeight = height / gridY;
  7138. const widthHalf = width / 2;
  7139. const heightHalf = height / 2;
  7140. const depthHalf = depth / 2;
  7141. const gridX1 = gridX + 1;
  7142. const gridY1 = gridY + 1;
  7143. let vertexCounter = 0;
  7144. let groupCount = 0;
  7145. const vector = new Vector3();
  7146. // generate vertices, normals and uvs
  7147. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7148. const y = iy * segmentHeight - heightHalf;
  7149. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7150. const x = ix * segmentWidth - widthHalf;
  7151. // set values to correct vector component
  7152. vector[ u ] = x * udir;
  7153. vector[ v ] = y * vdir;
  7154. vector[ w ] = depthHalf;
  7155. // now apply vector to vertex buffer
  7156. vertices.push( vector.x, vector.y, vector.z );
  7157. // set values to correct vector component
  7158. vector[ u ] = 0;
  7159. vector[ v ] = 0;
  7160. vector[ w ] = depth > 0 ? 1 : - 1;
  7161. // now apply vector to normal buffer
  7162. normals.push( vector.x, vector.y, vector.z );
  7163. // uvs
  7164. uvs.push( ix / gridX );
  7165. uvs.push( 1 - ( iy / gridY ) );
  7166. // counters
  7167. vertexCounter += 1;
  7168. }
  7169. }
  7170. // indices
  7171. // 1. you need three indices to draw a single face
  7172. // 2. a single segment consists of two faces
  7173. // 3. so we need to generate six (2*3) indices per segment
  7174. for ( let iy = 0; iy < gridY; iy ++ ) {
  7175. for ( let ix = 0; ix < gridX; ix ++ ) {
  7176. const a = numberOfVertices + ix + gridX1 * iy;
  7177. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7178. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7179. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7180. // faces
  7181. indices.push( a, b, d );
  7182. indices.push( b, c, d );
  7183. // increase counter
  7184. groupCount += 6;
  7185. }
  7186. }
  7187. // add a group to the geometry. this will ensure multi material support
  7188. scope.addGroup( groupStart, groupCount, materialIndex );
  7189. // calculate new start value for groups
  7190. groupStart += groupCount;
  7191. // update total number of vertices
  7192. numberOfVertices += vertexCounter;
  7193. }
  7194. }
  7195. copy( source ) {
  7196. super.copy( source );
  7197. this.parameters = Object.assign( {}, source.parameters );
  7198. return this;
  7199. }
  7200. static fromJSON( data ) {
  7201. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7202. }
  7203. }
  7204. /**
  7205. * Uniform Utilities
  7206. */
  7207. function cloneUniforms( src ) {
  7208. const dst = {};
  7209. for ( const u in src ) {
  7210. dst[ u ] = {};
  7211. for ( const p in src[ u ] ) {
  7212. const property = src[ u ][ p ];
  7213. if ( property && ( property.isColor ||
  7214. property.isMatrix3 || property.isMatrix4 ||
  7215. property.isVector2 || property.isVector3 || property.isVector4 ||
  7216. property.isTexture || property.isQuaternion ) ) {
  7217. if ( property.isRenderTargetTexture ) {
  7218. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7219. dst[ u ][ p ] = null;
  7220. } else {
  7221. dst[ u ][ p ] = property.clone();
  7222. }
  7223. } else if ( Array.isArray( property ) ) {
  7224. dst[ u ][ p ] = property.slice();
  7225. } else {
  7226. dst[ u ][ p ] = property;
  7227. }
  7228. }
  7229. }
  7230. return dst;
  7231. }
  7232. function cloneUniformsGroups( src ) {
  7233. const dst = [];
  7234. for ( let u = 0; u < src.length; u ++ ) {
  7235. dst.push( src[ u ].clone() );
  7236. }
  7237. return dst;
  7238. }
  7239. var default_vertex = /* glsl */`
  7240. void main() {
  7241. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7242. }
  7243. `;
  7244. var default_fragment = /* glsl */`
  7245. void main() {
  7246. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7247. }
  7248. `;
  7249. class ShaderMaterial extends Material {
  7250. constructor( parameters ) {
  7251. super();
  7252. this.isShaderMaterial = true;
  7253. this.type = 'ShaderMaterial';
  7254. this.defines = {};
  7255. this.uniforms = {};
  7256. this.uniformsGroups = [];
  7257. this.vertexShader = default_vertex;
  7258. this.fragmentShader = default_fragment;
  7259. this.linewidth = 1;
  7260. this.wireframe = false;
  7261. this.wireframeLinewidth = 1;
  7262. this.fog = false; // set to use scene fog
  7263. this.lights = false; // set to use scene lights
  7264. this.clipping = false; // set to use user-defined clipping planes
  7265. this.forceSinglePass = true;
  7266. this.extensions = {
  7267. clipCullDistance: false, // set to use vertex shader clipping
  7268. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7269. };
  7270. // When rendered geometry doesn't include these attributes but the material does,
  7271. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7272. this.defaultAttributeValues = {
  7273. 'color': [ 1, 1, 1 ],
  7274. 'uv': [ 0, 0 ],
  7275. 'uv1': [ 0, 0 ]
  7276. };
  7277. this.index0AttributeName = undefined;
  7278. this.uniformsNeedUpdate = false;
  7279. this.glslVersion = null;
  7280. if ( parameters !== undefined ) {
  7281. this.setValues( parameters );
  7282. }
  7283. }
  7284. copy( source ) {
  7285. super.copy( source );
  7286. this.fragmentShader = source.fragmentShader;
  7287. this.vertexShader = source.vertexShader;
  7288. this.uniforms = cloneUniforms( source.uniforms );
  7289. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7290. this.defines = Object.assign( {}, source.defines );
  7291. this.wireframe = source.wireframe;
  7292. this.wireframeLinewidth = source.wireframeLinewidth;
  7293. this.fog = source.fog;
  7294. this.lights = source.lights;
  7295. this.clipping = source.clipping;
  7296. this.extensions = Object.assign( {}, source.extensions );
  7297. this.glslVersion = source.glslVersion;
  7298. return this;
  7299. }
  7300. toJSON( meta ) {
  7301. const data = super.toJSON( meta );
  7302. data.glslVersion = this.glslVersion;
  7303. data.uniforms = {};
  7304. for ( const name in this.uniforms ) {
  7305. const uniform = this.uniforms[ name ];
  7306. const value = uniform.value;
  7307. if ( value && value.isTexture ) {
  7308. data.uniforms[ name ] = {
  7309. type: 't',
  7310. value: value.toJSON( meta ).uuid
  7311. };
  7312. } else if ( value && value.isColor ) {
  7313. data.uniforms[ name ] = {
  7314. type: 'c',
  7315. value: value.getHex()
  7316. };
  7317. } else if ( value && value.isVector2 ) {
  7318. data.uniforms[ name ] = {
  7319. type: 'v2',
  7320. value: value.toArray()
  7321. };
  7322. } else if ( value && value.isVector3 ) {
  7323. data.uniforms[ name ] = {
  7324. type: 'v3',
  7325. value: value.toArray()
  7326. };
  7327. } else if ( value && value.isVector4 ) {
  7328. data.uniforms[ name ] = {
  7329. type: 'v4',
  7330. value: value.toArray()
  7331. };
  7332. } else if ( value && value.isMatrix3 ) {
  7333. data.uniforms[ name ] = {
  7334. type: 'm3',
  7335. value: value.toArray()
  7336. };
  7337. } else if ( value && value.isMatrix4 ) {
  7338. data.uniforms[ name ] = {
  7339. type: 'm4',
  7340. value: value.toArray()
  7341. };
  7342. } else {
  7343. data.uniforms[ name ] = {
  7344. value: value
  7345. };
  7346. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7347. }
  7348. }
  7349. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7350. data.vertexShader = this.vertexShader;
  7351. data.fragmentShader = this.fragmentShader;
  7352. data.lights = this.lights;
  7353. data.clipping = this.clipping;
  7354. const extensions = {};
  7355. for ( const key in this.extensions ) {
  7356. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7357. }
  7358. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7359. return data;
  7360. }
  7361. }
  7362. class Camera extends Object3D {
  7363. constructor() {
  7364. super();
  7365. this.isCamera = true;
  7366. this.type = 'Camera';
  7367. this.matrixWorldInverse = new Matrix4();
  7368. this.projectionMatrix = new Matrix4();
  7369. this.projectionMatrixInverse = new Matrix4();
  7370. this.coordinateSystem = WebGLCoordinateSystem;
  7371. }
  7372. copy( source, recursive ) {
  7373. super.copy( source, recursive );
  7374. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7375. this.projectionMatrix.copy( source.projectionMatrix );
  7376. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7377. this.coordinateSystem = source.coordinateSystem;
  7378. return this;
  7379. }
  7380. getWorldDirection( target ) {
  7381. return super.getWorldDirection( target ).negate();
  7382. }
  7383. updateMatrixWorld( force ) {
  7384. super.updateMatrixWorld( force );
  7385. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7386. }
  7387. updateWorldMatrix( updateParents, updateChildren ) {
  7388. super.updateWorldMatrix( updateParents, updateChildren );
  7389. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7390. }
  7391. clone() {
  7392. return new this.constructor().copy( this );
  7393. }
  7394. }
  7395. const _v3$1 = /*@__PURE__*/ new Vector3();
  7396. const _minTarget = /*@__PURE__*/ new Vector2();
  7397. const _maxTarget = /*@__PURE__*/ new Vector2();
  7398. class PerspectiveCamera extends Camera {
  7399. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7400. super();
  7401. this.isPerspectiveCamera = true;
  7402. this.type = 'PerspectiveCamera';
  7403. this.fov = fov;
  7404. this.zoom = 1;
  7405. this.near = near;
  7406. this.far = far;
  7407. this.focus = 10;
  7408. this.aspect = aspect;
  7409. this.view = null;
  7410. this.filmGauge = 35; // width of the film (default in millimeters)
  7411. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7412. this.updateProjectionMatrix();
  7413. }
  7414. copy( source, recursive ) {
  7415. super.copy( source, recursive );
  7416. this.fov = source.fov;
  7417. this.zoom = source.zoom;
  7418. this.near = source.near;
  7419. this.far = source.far;
  7420. this.focus = source.focus;
  7421. this.aspect = source.aspect;
  7422. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7423. this.filmGauge = source.filmGauge;
  7424. this.filmOffset = source.filmOffset;
  7425. return this;
  7426. }
  7427. /**
  7428. * Sets the FOV by focal length in respect to the current .filmGauge.
  7429. *
  7430. * The default film gauge is 35, so that the focal length can be specified for
  7431. * a 35mm (full frame) camera.
  7432. *
  7433. * Values for focal length and film gauge must have the same unit.
  7434. */
  7435. setFocalLength( focalLength ) {
  7436. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7437. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7438. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7439. this.updateProjectionMatrix();
  7440. }
  7441. /**
  7442. * Calculates the focal length from the current .fov and .filmGauge.
  7443. */
  7444. getFocalLength() {
  7445. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7446. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7447. }
  7448. getEffectiveFOV() {
  7449. return RAD2DEG * 2 * Math.atan(
  7450. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7451. }
  7452. getFilmWidth() {
  7453. // film not completely covered in portrait format (aspect < 1)
  7454. return this.filmGauge * Math.min( this.aspect, 1 );
  7455. }
  7456. getFilmHeight() {
  7457. // film not completely covered in landscape format (aspect > 1)
  7458. return this.filmGauge / Math.max( this.aspect, 1 );
  7459. }
  7460. /**
  7461. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7462. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7463. */
  7464. getViewBounds( distance, minTarget, maxTarget ) {
  7465. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7466. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7467. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7468. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7469. }
  7470. /**
  7471. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7472. * Copies the result into the target Vector2, where x is width and y is height.
  7473. */
  7474. getViewSize( distance, target ) {
  7475. this.getViewBounds( distance, _minTarget, _maxTarget );
  7476. return target.subVectors( _maxTarget, _minTarget );
  7477. }
  7478. /**
  7479. * Sets an offset in a larger frustum. This is useful for multi-window or
  7480. * multi-monitor/multi-machine setups.
  7481. *
  7482. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7483. * the monitors are in grid like this
  7484. *
  7485. * +---+---+---+
  7486. * | A | B | C |
  7487. * +---+---+---+
  7488. * | D | E | F |
  7489. * +---+---+---+
  7490. *
  7491. * then for each monitor you would call it like this
  7492. *
  7493. * const w = 1920;
  7494. * const h = 1080;
  7495. * const fullWidth = w * 3;
  7496. * const fullHeight = h * 2;
  7497. *
  7498. * --A--
  7499. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7500. * --B--
  7501. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7502. * --C--
  7503. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7504. * --D--
  7505. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7506. * --E--
  7507. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7508. * --F--
  7509. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7510. *
  7511. * Note there is no reason monitors have to be the same size or in a grid.
  7512. */
  7513. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7514. this.aspect = fullWidth / fullHeight;
  7515. if ( this.view === null ) {
  7516. this.view = {
  7517. enabled: true,
  7518. fullWidth: 1,
  7519. fullHeight: 1,
  7520. offsetX: 0,
  7521. offsetY: 0,
  7522. width: 1,
  7523. height: 1
  7524. };
  7525. }
  7526. this.view.enabled = true;
  7527. this.view.fullWidth = fullWidth;
  7528. this.view.fullHeight = fullHeight;
  7529. this.view.offsetX = x;
  7530. this.view.offsetY = y;
  7531. this.view.width = width;
  7532. this.view.height = height;
  7533. this.updateProjectionMatrix();
  7534. }
  7535. clearViewOffset() {
  7536. if ( this.view !== null ) {
  7537. this.view.enabled = false;
  7538. }
  7539. this.updateProjectionMatrix();
  7540. }
  7541. updateProjectionMatrix() {
  7542. const near = this.near;
  7543. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7544. let height = 2 * top;
  7545. let width = this.aspect * height;
  7546. let left = - 0.5 * width;
  7547. const view = this.view;
  7548. if ( this.view !== null && this.view.enabled ) {
  7549. const fullWidth = view.fullWidth,
  7550. fullHeight = view.fullHeight;
  7551. left += view.offsetX * width / fullWidth;
  7552. top -= view.offsetY * height / fullHeight;
  7553. width *= view.width / fullWidth;
  7554. height *= view.height / fullHeight;
  7555. }
  7556. const skew = this.filmOffset;
  7557. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7558. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7559. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7560. }
  7561. toJSON( meta ) {
  7562. const data = super.toJSON( meta );
  7563. data.object.fov = this.fov;
  7564. data.object.zoom = this.zoom;
  7565. data.object.near = this.near;
  7566. data.object.far = this.far;
  7567. data.object.focus = this.focus;
  7568. data.object.aspect = this.aspect;
  7569. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7570. data.object.filmGauge = this.filmGauge;
  7571. data.object.filmOffset = this.filmOffset;
  7572. return data;
  7573. }
  7574. }
  7575. const fov = - 90; // negative fov is not an error
  7576. const aspect = 1;
  7577. class CubeCamera extends Object3D {
  7578. constructor( near, far, renderTarget ) {
  7579. super();
  7580. this.type = 'CubeCamera';
  7581. this.renderTarget = renderTarget;
  7582. this.coordinateSystem = null;
  7583. this.activeMipmapLevel = 0;
  7584. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7585. cameraPX.layers = this.layers;
  7586. this.add( cameraPX );
  7587. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7588. cameraNX.layers = this.layers;
  7589. this.add( cameraNX );
  7590. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7591. cameraPY.layers = this.layers;
  7592. this.add( cameraPY );
  7593. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7594. cameraNY.layers = this.layers;
  7595. this.add( cameraNY );
  7596. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7597. cameraPZ.layers = this.layers;
  7598. this.add( cameraPZ );
  7599. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7600. cameraNZ.layers = this.layers;
  7601. this.add( cameraNZ );
  7602. }
  7603. updateCoordinateSystem() {
  7604. const coordinateSystem = this.coordinateSystem;
  7605. const cameras = this.children.concat();
  7606. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7607. for ( const camera of cameras ) this.remove( camera );
  7608. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7609. cameraPX.up.set( 0, 1, 0 );
  7610. cameraPX.lookAt( 1, 0, 0 );
  7611. cameraNX.up.set( 0, 1, 0 );
  7612. cameraNX.lookAt( - 1, 0, 0 );
  7613. cameraPY.up.set( 0, 0, - 1 );
  7614. cameraPY.lookAt( 0, 1, 0 );
  7615. cameraNY.up.set( 0, 0, 1 );
  7616. cameraNY.lookAt( 0, - 1, 0 );
  7617. cameraPZ.up.set( 0, 1, 0 );
  7618. cameraPZ.lookAt( 0, 0, 1 );
  7619. cameraNZ.up.set( 0, 1, 0 );
  7620. cameraNZ.lookAt( 0, 0, - 1 );
  7621. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7622. cameraPX.up.set( 0, - 1, 0 );
  7623. cameraPX.lookAt( - 1, 0, 0 );
  7624. cameraNX.up.set( 0, - 1, 0 );
  7625. cameraNX.lookAt( 1, 0, 0 );
  7626. cameraPY.up.set( 0, 0, 1 );
  7627. cameraPY.lookAt( 0, 1, 0 );
  7628. cameraNY.up.set( 0, 0, - 1 );
  7629. cameraNY.lookAt( 0, - 1, 0 );
  7630. cameraPZ.up.set( 0, - 1, 0 );
  7631. cameraPZ.lookAt( 0, 0, 1 );
  7632. cameraNZ.up.set( 0, - 1, 0 );
  7633. cameraNZ.lookAt( 0, 0, - 1 );
  7634. } else {
  7635. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7636. }
  7637. for ( const camera of cameras ) {
  7638. this.add( camera );
  7639. camera.updateMatrixWorld();
  7640. }
  7641. }
  7642. update( renderer, scene ) {
  7643. if ( this.parent === null ) this.updateMatrixWorld();
  7644. const { renderTarget, activeMipmapLevel } = this;
  7645. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7646. this.coordinateSystem = renderer.coordinateSystem;
  7647. this.updateCoordinateSystem();
  7648. }
  7649. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7650. const currentRenderTarget = renderer.getRenderTarget();
  7651. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7652. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7653. const currentXrEnabled = renderer.xr.enabled;
  7654. renderer.xr.enabled = false;
  7655. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7656. renderTarget.texture.generateMipmaps = false;
  7657. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7658. renderer.render( scene, cameraPX );
  7659. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7660. renderer.render( scene, cameraNX );
  7661. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7662. renderer.render( scene, cameraPY );
  7663. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7664. renderer.render( scene, cameraNY );
  7665. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7666. renderer.render( scene, cameraPZ );
  7667. // mipmaps are generated during the last call of render()
  7668. // at this point, all sides of the cube render target are defined
  7669. renderTarget.texture.generateMipmaps = generateMipmaps;
  7670. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7671. renderer.render( scene, cameraNZ );
  7672. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7673. renderer.xr.enabled = currentXrEnabled;
  7674. renderTarget.texture.needsPMREMUpdate = true;
  7675. }
  7676. }
  7677. class CubeTexture extends Texture {
  7678. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7679. images = images !== undefined ? images : [];
  7680. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7681. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7682. this.isCubeTexture = true;
  7683. this.flipY = false;
  7684. }
  7685. get images() {
  7686. return this.image;
  7687. }
  7688. set images( value ) {
  7689. this.image = value;
  7690. }
  7691. }
  7692. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7693. constructor( size = 1, options = {} ) {
  7694. super( size, size, options );
  7695. this.isWebGLCubeRenderTarget = true;
  7696. const image = { width: size, height: size, depth: 1 };
  7697. const images = [ image, image, image, image, image, image ];
  7698. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7699. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7700. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7701. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7702. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7703. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7704. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7705. this.texture.isRenderTargetTexture = true;
  7706. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7707. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7708. }
  7709. fromEquirectangularTexture( renderer, texture ) {
  7710. this.texture.type = texture.type;
  7711. this.texture.colorSpace = texture.colorSpace;
  7712. this.texture.generateMipmaps = texture.generateMipmaps;
  7713. this.texture.minFilter = texture.minFilter;
  7714. this.texture.magFilter = texture.magFilter;
  7715. const shader = {
  7716. uniforms: {
  7717. tEquirect: { value: null },
  7718. },
  7719. vertexShader: /* glsl */`
  7720. varying vec3 vWorldDirection;
  7721. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7722. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7723. }
  7724. void main() {
  7725. vWorldDirection = transformDirection( position, modelMatrix );
  7726. #include <begin_vertex>
  7727. #include <project_vertex>
  7728. }
  7729. `,
  7730. fragmentShader: /* glsl */`
  7731. uniform sampler2D tEquirect;
  7732. varying vec3 vWorldDirection;
  7733. #include <common>
  7734. void main() {
  7735. vec3 direction = normalize( vWorldDirection );
  7736. vec2 sampleUV = equirectUv( direction );
  7737. gl_FragColor = texture2D( tEquirect, sampleUV );
  7738. }
  7739. `
  7740. };
  7741. const geometry = new BoxGeometry( 5, 5, 5 );
  7742. const material = new ShaderMaterial( {
  7743. name: 'CubemapFromEquirect',
  7744. uniforms: cloneUniforms( shader.uniforms ),
  7745. vertexShader: shader.vertexShader,
  7746. fragmentShader: shader.fragmentShader,
  7747. side: BackSide,
  7748. blending: NoBlending
  7749. } );
  7750. material.uniforms.tEquirect.value = texture;
  7751. const mesh = new Mesh( geometry, material );
  7752. const currentMinFilter = texture.minFilter;
  7753. // Avoid blurred poles
  7754. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7755. const camera = new CubeCamera( 1, 10, this );
  7756. camera.update( renderer, mesh );
  7757. texture.minFilter = currentMinFilter;
  7758. mesh.geometry.dispose();
  7759. mesh.material.dispose();
  7760. return this;
  7761. }
  7762. clear( renderer, color, depth, stencil ) {
  7763. const currentRenderTarget = renderer.getRenderTarget();
  7764. for ( let i = 0; i < 6; i ++ ) {
  7765. renderer.setRenderTarget( this, i );
  7766. renderer.clear( color, depth, stencil );
  7767. }
  7768. renderer.setRenderTarget( currentRenderTarget );
  7769. }
  7770. }
  7771. class FogExp2 {
  7772. constructor( color, density = 0.00025 ) {
  7773. this.isFogExp2 = true;
  7774. this.name = '';
  7775. this.color = new Color( color );
  7776. this.density = density;
  7777. }
  7778. clone() {
  7779. return new FogExp2( this.color, this.density );
  7780. }
  7781. toJSON( /* meta */ ) {
  7782. return {
  7783. type: 'FogExp2',
  7784. name: this.name,
  7785. color: this.color.getHex(),
  7786. density: this.density
  7787. };
  7788. }
  7789. }
  7790. class Fog {
  7791. constructor( color, near = 1, far = 1000 ) {
  7792. this.isFog = true;
  7793. this.name = '';
  7794. this.color = new Color( color );
  7795. this.near = near;
  7796. this.far = far;
  7797. }
  7798. clone() {
  7799. return new Fog( this.color, this.near, this.far );
  7800. }
  7801. toJSON( /* meta */ ) {
  7802. return {
  7803. type: 'Fog',
  7804. name: this.name,
  7805. color: this.color.getHex(),
  7806. near: this.near,
  7807. far: this.far
  7808. };
  7809. }
  7810. }
  7811. class Scene extends Object3D {
  7812. constructor() {
  7813. super();
  7814. this.isScene = true;
  7815. this.type = 'Scene';
  7816. this.background = null;
  7817. this.environment = null;
  7818. this.fog = null;
  7819. this.backgroundBlurriness = 0;
  7820. this.backgroundIntensity = 1;
  7821. this.backgroundRotation = new Euler();
  7822. this.environmentIntensity = 1;
  7823. this.environmentRotation = new Euler();
  7824. this.overrideMaterial = null;
  7825. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7826. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7827. }
  7828. }
  7829. copy( source, recursive ) {
  7830. super.copy( source, recursive );
  7831. if ( source.background !== null ) this.background = source.background.clone();
  7832. if ( source.environment !== null ) this.environment = source.environment.clone();
  7833. if ( source.fog !== null ) this.fog = source.fog.clone();
  7834. this.backgroundBlurriness = source.backgroundBlurriness;
  7835. this.backgroundIntensity = source.backgroundIntensity;
  7836. this.backgroundRotation.copy( source.backgroundRotation );
  7837. this.environmentIntensity = source.environmentIntensity;
  7838. this.environmentRotation.copy( source.environmentRotation );
  7839. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7840. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7841. return this;
  7842. }
  7843. toJSON( meta ) {
  7844. const data = super.toJSON( meta );
  7845. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7846. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7847. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7848. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7849. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7850. data.object.environmentRotation = this.environmentRotation.toArray();
  7851. return data;
  7852. }
  7853. }
  7854. class InterleavedBuffer {
  7855. constructor( array, stride ) {
  7856. this.isInterleavedBuffer = true;
  7857. this.array = array;
  7858. this.stride = stride;
  7859. this.count = array !== undefined ? array.length / stride : 0;
  7860. this.usage = StaticDrawUsage;
  7861. this._updateRange = { offset: 0, count: - 1 };
  7862. this.updateRanges = [];
  7863. this.version = 0;
  7864. this.uuid = generateUUID();
  7865. }
  7866. onUploadCallback() {}
  7867. set needsUpdate( value ) {
  7868. if ( value === true ) this.version ++;
  7869. }
  7870. get updateRange() {
  7871. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  7872. return this._updateRange;
  7873. }
  7874. setUsage( value ) {
  7875. this.usage = value;
  7876. return this;
  7877. }
  7878. addUpdateRange( start, count ) {
  7879. this.updateRanges.push( { start, count } );
  7880. }
  7881. clearUpdateRanges() {
  7882. this.updateRanges.length = 0;
  7883. }
  7884. copy( source ) {
  7885. this.array = new source.array.constructor( source.array );
  7886. this.count = source.count;
  7887. this.stride = source.stride;
  7888. this.usage = source.usage;
  7889. return this;
  7890. }
  7891. copyAt( index1, attribute, index2 ) {
  7892. index1 *= this.stride;
  7893. index2 *= attribute.stride;
  7894. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7895. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7896. }
  7897. return this;
  7898. }
  7899. set( value, offset = 0 ) {
  7900. this.array.set( value, offset );
  7901. return this;
  7902. }
  7903. clone( data ) {
  7904. if ( data.arrayBuffers === undefined ) {
  7905. data.arrayBuffers = {};
  7906. }
  7907. if ( this.array.buffer._uuid === undefined ) {
  7908. this.array.buffer._uuid = generateUUID();
  7909. }
  7910. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7911. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7912. }
  7913. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7914. const ib = new this.constructor( array, this.stride );
  7915. ib.setUsage( this.usage );
  7916. return ib;
  7917. }
  7918. onUpload( callback ) {
  7919. this.onUploadCallback = callback;
  7920. return this;
  7921. }
  7922. toJSON( data ) {
  7923. if ( data.arrayBuffers === undefined ) {
  7924. data.arrayBuffers = {};
  7925. }
  7926. // generate UUID for array buffer if necessary
  7927. if ( this.array.buffer._uuid === undefined ) {
  7928. this.array.buffer._uuid = generateUUID();
  7929. }
  7930. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7931. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7932. }
  7933. //
  7934. return {
  7935. uuid: this.uuid,
  7936. buffer: this.array.buffer._uuid,
  7937. type: this.array.constructor.name,
  7938. stride: this.stride
  7939. };
  7940. }
  7941. }
  7942. const _vector$7 = /*@__PURE__*/ new Vector3();
  7943. class InterleavedBufferAttribute {
  7944. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7945. this.isInterleavedBufferAttribute = true;
  7946. this.name = '';
  7947. this.data = interleavedBuffer;
  7948. this.itemSize = itemSize;
  7949. this.offset = offset;
  7950. this.normalized = normalized;
  7951. }
  7952. get count() {
  7953. return this.data.count;
  7954. }
  7955. get array() {
  7956. return this.data.array;
  7957. }
  7958. set needsUpdate( value ) {
  7959. this.data.needsUpdate = value;
  7960. }
  7961. applyMatrix4( m ) {
  7962. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7963. _vector$7.fromBufferAttribute( this, i );
  7964. _vector$7.applyMatrix4( m );
  7965. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7966. }
  7967. return this;
  7968. }
  7969. applyNormalMatrix( m ) {
  7970. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7971. _vector$7.fromBufferAttribute( this, i );
  7972. _vector$7.applyNormalMatrix( m );
  7973. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7974. }
  7975. return this;
  7976. }
  7977. transformDirection( m ) {
  7978. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7979. _vector$7.fromBufferAttribute( this, i );
  7980. _vector$7.transformDirection( m );
  7981. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7982. }
  7983. return this;
  7984. }
  7985. getComponent( index, component ) {
  7986. let value = this.array[ index * this.data.stride + this.offset + component ];
  7987. if ( this.normalized ) value = denormalize( value, this.array );
  7988. return value;
  7989. }
  7990. setComponent( index, component, value ) {
  7991. if ( this.normalized ) value = normalize$1( value, this.array );
  7992. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  7993. return this;
  7994. }
  7995. setX( index, x ) {
  7996. if ( this.normalized ) x = normalize$1( x, this.array );
  7997. this.data.array[ index * this.data.stride + this.offset ] = x;
  7998. return this;
  7999. }
  8000. setY( index, y ) {
  8001. if ( this.normalized ) y = normalize$1( y, this.array );
  8002. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8003. return this;
  8004. }
  8005. setZ( index, z ) {
  8006. if ( this.normalized ) z = normalize$1( z, this.array );
  8007. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8008. return this;
  8009. }
  8010. setW( index, w ) {
  8011. if ( this.normalized ) w = normalize$1( w, this.array );
  8012. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8013. return this;
  8014. }
  8015. getX( index ) {
  8016. let x = this.data.array[ index * this.data.stride + this.offset ];
  8017. if ( this.normalized ) x = denormalize( x, this.array );
  8018. return x;
  8019. }
  8020. getY( index ) {
  8021. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8022. if ( this.normalized ) y = denormalize( y, this.array );
  8023. return y;
  8024. }
  8025. getZ( index ) {
  8026. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8027. if ( this.normalized ) z = denormalize( z, this.array );
  8028. return z;
  8029. }
  8030. getW( index ) {
  8031. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8032. if ( this.normalized ) w = denormalize( w, this.array );
  8033. return w;
  8034. }
  8035. setXY( index, x, y ) {
  8036. index = index * this.data.stride + this.offset;
  8037. if ( this.normalized ) {
  8038. x = normalize$1( x, this.array );
  8039. y = normalize$1( y, this.array );
  8040. }
  8041. this.data.array[ index + 0 ] = x;
  8042. this.data.array[ index + 1 ] = y;
  8043. return this;
  8044. }
  8045. setXYZ( index, x, y, z ) {
  8046. index = index * this.data.stride + this.offset;
  8047. if ( this.normalized ) {
  8048. x = normalize$1( x, this.array );
  8049. y = normalize$1( y, this.array );
  8050. z = normalize$1( z, this.array );
  8051. }
  8052. this.data.array[ index + 0 ] = x;
  8053. this.data.array[ index + 1 ] = y;
  8054. this.data.array[ index + 2 ] = z;
  8055. return this;
  8056. }
  8057. setXYZW( index, x, y, z, w ) {
  8058. index = index * this.data.stride + this.offset;
  8059. if ( this.normalized ) {
  8060. x = normalize$1( x, this.array );
  8061. y = normalize$1( y, this.array );
  8062. z = normalize$1( z, this.array );
  8063. w = normalize$1( w, this.array );
  8064. }
  8065. this.data.array[ index + 0 ] = x;
  8066. this.data.array[ index + 1 ] = y;
  8067. this.data.array[ index + 2 ] = z;
  8068. this.data.array[ index + 3 ] = w;
  8069. return this;
  8070. }
  8071. clone( data ) {
  8072. if ( data === undefined ) {
  8073. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8074. const array = [];
  8075. for ( let i = 0; i < this.count; i ++ ) {
  8076. const index = i * this.data.stride + this.offset;
  8077. for ( let j = 0; j < this.itemSize; j ++ ) {
  8078. array.push( this.data.array[ index + j ] );
  8079. }
  8080. }
  8081. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8082. } else {
  8083. if ( data.interleavedBuffers === undefined ) {
  8084. data.interleavedBuffers = {};
  8085. }
  8086. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8087. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8088. }
  8089. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8090. }
  8091. }
  8092. toJSON( data ) {
  8093. if ( data === undefined ) {
  8094. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8095. const array = [];
  8096. for ( let i = 0; i < this.count; i ++ ) {
  8097. const index = i * this.data.stride + this.offset;
  8098. for ( let j = 0; j < this.itemSize; j ++ ) {
  8099. array.push( this.data.array[ index + j ] );
  8100. }
  8101. }
  8102. // de-interleave data and save it as an ordinary buffer attribute for now
  8103. return {
  8104. itemSize: this.itemSize,
  8105. type: this.array.constructor.name,
  8106. array: array,
  8107. normalized: this.normalized
  8108. };
  8109. } else {
  8110. // save as true interleaved attribute
  8111. if ( data.interleavedBuffers === undefined ) {
  8112. data.interleavedBuffers = {};
  8113. }
  8114. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8115. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8116. }
  8117. return {
  8118. isInterleavedBufferAttribute: true,
  8119. itemSize: this.itemSize,
  8120. data: this.data.uuid,
  8121. offset: this.offset,
  8122. normalized: this.normalized
  8123. };
  8124. }
  8125. }
  8126. }
  8127. class SpriteMaterial extends Material {
  8128. constructor( parameters ) {
  8129. super();
  8130. this.isSpriteMaterial = true;
  8131. this.type = 'SpriteMaterial';
  8132. this.color = new Color( 0xffffff );
  8133. this.map = null;
  8134. this.alphaMap = null;
  8135. this.rotation = 0;
  8136. this.sizeAttenuation = true;
  8137. this.transparent = true;
  8138. this.fog = true;
  8139. this.setValues( parameters );
  8140. }
  8141. copy( source ) {
  8142. super.copy( source );
  8143. this.color.copy( source.color );
  8144. this.map = source.map;
  8145. this.alphaMap = source.alphaMap;
  8146. this.rotation = source.rotation;
  8147. this.sizeAttenuation = source.sizeAttenuation;
  8148. this.fog = source.fog;
  8149. return this;
  8150. }
  8151. }
  8152. let _geometry$1;
  8153. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8154. const _worldScale = /*@__PURE__*/ new Vector3();
  8155. const _mvPosition = /*@__PURE__*/ new Vector3();
  8156. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8157. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8158. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8159. const _vA = /*@__PURE__*/ new Vector3();
  8160. const _vB = /*@__PURE__*/ new Vector3();
  8161. const _vC = /*@__PURE__*/ new Vector3();
  8162. const _uvA = /*@__PURE__*/ new Vector2();
  8163. const _uvB = /*@__PURE__*/ new Vector2();
  8164. const _uvC = /*@__PURE__*/ new Vector2();
  8165. class Sprite extends Object3D {
  8166. constructor( material = new SpriteMaterial() ) {
  8167. super();
  8168. this.isSprite = true;
  8169. this.type = 'Sprite';
  8170. if ( _geometry$1 === undefined ) {
  8171. _geometry$1 = new BufferGeometry();
  8172. const float32Array = new Float32Array( [
  8173. - 0.5, - 0.5, 0, 0, 0,
  8174. 0.5, - 0.5, 0, 1, 0,
  8175. 0.5, 0.5, 0, 1, 1,
  8176. - 0.5, 0.5, 0, 0, 1
  8177. ] );
  8178. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8179. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8180. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8181. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8182. }
  8183. this.geometry = _geometry$1;
  8184. this.material = material;
  8185. this.center = new Vector2( 0.5, 0.5 );
  8186. }
  8187. raycast( raycaster, intersects ) {
  8188. if ( raycaster.camera === null ) {
  8189. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8190. }
  8191. _worldScale.setFromMatrixScale( this.matrixWorld );
  8192. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8193. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8194. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8195. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8196. _worldScale.multiplyScalar( - _mvPosition.z );
  8197. }
  8198. const rotation = this.material.rotation;
  8199. let sin, cos;
  8200. if ( rotation !== 0 ) {
  8201. cos = Math.cos( rotation );
  8202. sin = Math.sin( rotation );
  8203. }
  8204. const center = this.center;
  8205. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8206. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8207. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8208. _uvA.set( 0, 0 );
  8209. _uvB.set( 1, 0 );
  8210. _uvC.set( 1, 1 );
  8211. // check first triangle
  8212. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8213. if ( intersect === null ) {
  8214. // check second triangle
  8215. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8216. _uvB.set( 0, 1 );
  8217. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8218. if ( intersect === null ) {
  8219. return;
  8220. }
  8221. }
  8222. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8223. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8224. intersects.push( {
  8225. distance: distance,
  8226. point: _intersectPoint.clone(),
  8227. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8228. face: null,
  8229. object: this
  8230. } );
  8231. }
  8232. copy( source, recursive ) {
  8233. super.copy( source, recursive );
  8234. if ( source.center !== undefined ) this.center.copy( source.center );
  8235. this.material = source.material;
  8236. return this;
  8237. }
  8238. }
  8239. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8240. // compute position in camera space
  8241. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8242. // to check if rotation is not zero
  8243. if ( sin !== undefined ) {
  8244. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8245. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8246. } else {
  8247. _rotatedPosition.copy( _alignedPosition );
  8248. }
  8249. vertexPosition.copy( mvPosition );
  8250. vertexPosition.x += _rotatedPosition.x;
  8251. vertexPosition.y += _rotatedPosition.y;
  8252. // transform to world space
  8253. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8254. }
  8255. const _v1$2 = /*@__PURE__*/ new Vector3();
  8256. const _v2$1 = /*@__PURE__*/ new Vector3();
  8257. class LOD extends Object3D {
  8258. constructor() {
  8259. super();
  8260. this._currentLevel = 0;
  8261. this.type = 'LOD';
  8262. Object.defineProperties( this, {
  8263. levels: {
  8264. enumerable: true,
  8265. value: []
  8266. },
  8267. isLOD: {
  8268. value: true,
  8269. }
  8270. } );
  8271. this.autoUpdate = true;
  8272. }
  8273. copy( source ) {
  8274. super.copy( source, false );
  8275. const levels = source.levels;
  8276. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8277. const level = levels[ i ];
  8278. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8279. }
  8280. this.autoUpdate = source.autoUpdate;
  8281. return this;
  8282. }
  8283. addLevel( object, distance = 0, hysteresis = 0 ) {
  8284. distance = Math.abs( distance );
  8285. const levels = this.levels;
  8286. let l;
  8287. for ( l = 0; l < levels.length; l ++ ) {
  8288. if ( distance < levels[ l ].distance ) {
  8289. break;
  8290. }
  8291. }
  8292. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8293. this.add( object );
  8294. return this;
  8295. }
  8296. getCurrentLevel() {
  8297. return this._currentLevel;
  8298. }
  8299. getObjectForDistance( distance ) {
  8300. const levels = this.levels;
  8301. if ( levels.length > 0 ) {
  8302. let i, l;
  8303. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8304. let levelDistance = levels[ i ].distance;
  8305. if ( levels[ i ].object.visible ) {
  8306. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8307. }
  8308. if ( distance < levelDistance ) {
  8309. break;
  8310. }
  8311. }
  8312. return levels[ i - 1 ].object;
  8313. }
  8314. return null;
  8315. }
  8316. raycast( raycaster, intersects ) {
  8317. const levels = this.levels;
  8318. if ( levels.length > 0 ) {
  8319. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8320. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8321. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8322. }
  8323. }
  8324. update( camera ) {
  8325. const levels = this.levels;
  8326. if ( levels.length > 1 ) {
  8327. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8328. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8329. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8330. levels[ 0 ].object.visible = true;
  8331. let i, l;
  8332. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8333. let levelDistance = levels[ i ].distance;
  8334. if ( levels[ i ].object.visible ) {
  8335. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8336. }
  8337. if ( distance >= levelDistance ) {
  8338. levels[ i - 1 ].object.visible = false;
  8339. levels[ i ].object.visible = true;
  8340. } else {
  8341. break;
  8342. }
  8343. }
  8344. this._currentLevel = i - 1;
  8345. for ( ; i < l; i ++ ) {
  8346. levels[ i ].object.visible = false;
  8347. }
  8348. }
  8349. }
  8350. toJSON( meta ) {
  8351. const data = super.toJSON( meta );
  8352. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8353. data.object.levels = [];
  8354. const levels = this.levels;
  8355. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8356. const level = levels[ i ];
  8357. data.object.levels.push( {
  8358. object: level.object.uuid,
  8359. distance: level.distance,
  8360. hysteresis: level.hysteresis
  8361. } );
  8362. }
  8363. return data;
  8364. }
  8365. }
  8366. const _basePosition = /*@__PURE__*/ new Vector3();
  8367. const _skinIndex = /*@__PURE__*/ new Vector4();
  8368. const _skinWeight = /*@__PURE__*/ new Vector4();
  8369. const _vector3$1 = /*@__PURE__*/ new Vector3();
  8370. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8371. const _vertex = /*@__PURE__*/ new Vector3();
  8372. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8373. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8374. const _ray$2 = /*@__PURE__*/ new Ray();
  8375. class SkinnedMesh extends Mesh {
  8376. constructor( geometry, material ) {
  8377. super( geometry, material );
  8378. this.isSkinnedMesh = true;
  8379. this.type = 'SkinnedMesh';
  8380. this.bindMode = AttachedBindMode;
  8381. this.bindMatrix = new Matrix4();
  8382. this.bindMatrixInverse = new Matrix4();
  8383. this.boundingBox = null;
  8384. this.boundingSphere = null;
  8385. }
  8386. computeBoundingBox() {
  8387. const geometry = this.geometry;
  8388. if ( this.boundingBox === null ) {
  8389. this.boundingBox = new Box3();
  8390. }
  8391. this.boundingBox.makeEmpty();
  8392. const positionAttribute = geometry.getAttribute( 'position' );
  8393. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8394. this.getVertexPosition( i, _vertex );
  8395. this.boundingBox.expandByPoint( _vertex );
  8396. }
  8397. }
  8398. computeBoundingSphere() {
  8399. const geometry = this.geometry;
  8400. if ( this.boundingSphere === null ) {
  8401. this.boundingSphere = new Sphere();
  8402. }
  8403. this.boundingSphere.makeEmpty();
  8404. const positionAttribute = geometry.getAttribute( 'position' );
  8405. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8406. this.getVertexPosition( i, _vertex );
  8407. this.boundingSphere.expandByPoint( _vertex );
  8408. }
  8409. }
  8410. copy( source, recursive ) {
  8411. super.copy( source, recursive );
  8412. this.bindMode = source.bindMode;
  8413. this.bindMatrix.copy( source.bindMatrix );
  8414. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8415. this.skeleton = source.skeleton;
  8416. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8417. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8418. return this;
  8419. }
  8420. raycast( raycaster, intersects ) {
  8421. const material = this.material;
  8422. const matrixWorld = this.matrixWorld;
  8423. if ( material === undefined ) return;
  8424. // test with bounding sphere in world space
  8425. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8426. _sphere$5.copy( this.boundingSphere );
  8427. _sphere$5.applyMatrix4( matrixWorld );
  8428. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8429. // convert ray to local space of skinned mesh
  8430. _inverseMatrix$2.copy( matrixWorld ).invert();
  8431. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8432. // test with bounding box in local space
  8433. if ( this.boundingBox !== null ) {
  8434. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8435. }
  8436. // test for intersections with geometry
  8437. this._computeIntersections( raycaster, intersects, _ray$2 );
  8438. }
  8439. getVertexPosition( index, target ) {
  8440. super.getVertexPosition( index, target );
  8441. this.applyBoneTransform( index, target );
  8442. return target;
  8443. }
  8444. bind( skeleton, bindMatrix ) {
  8445. this.skeleton = skeleton;
  8446. if ( bindMatrix === undefined ) {
  8447. this.updateMatrixWorld( true );
  8448. this.skeleton.calculateInverses();
  8449. bindMatrix = this.matrixWorld;
  8450. }
  8451. this.bindMatrix.copy( bindMatrix );
  8452. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8453. }
  8454. pose() {
  8455. this.skeleton.pose();
  8456. }
  8457. normalizeSkinWeights() {
  8458. const vector = new Vector4();
  8459. const skinWeight = this.geometry.attributes.skinWeight;
  8460. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8461. vector.fromBufferAttribute( skinWeight, i );
  8462. const scale = 1.0 / vector.manhattanLength();
  8463. if ( scale !== Infinity ) {
  8464. vector.multiplyScalar( scale );
  8465. } else {
  8466. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8467. }
  8468. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8469. }
  8470. }
  8471. updateMatrixWorld( force ) {
  8472. super.updateMatrixWorld( force );
  8473. if ( this.bindMode === AttachedBindMode ) {
  8474. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8475. } else if ( this.bindMode === DetachedBindMode ) {
  8476. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8477. } else {
  8478. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8479. }
  8480. }
  8481. applyBoneTransform( index, vector ) {
  8482. const skeleton = this.skeleton;
  8483. const geometry = this.geometry;
  8484. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8485. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8486. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8487. vector.set( 0, 0, 0 );
  8488. for ( let i = 0; i < 4; i ++ ) {
  8489. const weight = _skinWeight.getComponent( i );
  8490. if ( weight !== 0 ) {
  8491. const boneIndex = _skinIndex.getComponent( i );
  8492. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8493. vector.addScaledVector( _vector3$1.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8494. }
  8495. }
  8496. return vector.applyMatrix4( this.bindMatrixInverse );
  8497. }
  8498. }
  8499. class Bone extends Object3D {
  8500. constructor() {
  8501. super();
  8502. this.isBone = true;
  8503. this.type = 'Bone';
  8504. }
  8505. }
  8506. class DataTexture extends Texture {
  8507. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8508. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8509. this.isDataTexture = true;
  8510. this.image = { data: data, width: width, height: height };
  8511. this.generateMipmaps = false;
  8512. this.flipY = false;
  8513. this.unpackAlignment = 1;
  8514. }
  8515. }
  8516. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8517. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8518. class Skeleton {
  8519. constructor( bones = [], boneInverses = [] ) {
  8520. this.uuid = generateUUID();
  8521. this.bones = bones.slice( 0 );
  8522. this.boneInverses = boneInverses;
  8523. this.boneMatrices = null;
  8524. this.boneTexture = null;
  8525. this.init();
  8526. }
  8527. init() {
  8528. const bones = this.bones;
  8529. const boneInverses = this.boneInverses;
  8530. this.boneMatrices = new Float32Array( bones.length * 16 );
  8531. // calculate inverse bone matrices if necessary
  8532. if ( boneInverses.length === 0 ) {
  8533. this.calculateInverses();
  8534. } else {
  8535. // handle special case
  8536. if ( bones.length !== boneInverses.length ) {
  8537. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8538. this.boneInverses = [];
  8539. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8540. this.boneInverses.push( new Matrix4() );
  8541. }
  8542. }
  8543. }
  8544. }
  8545. calculateInverses() {
  8546. this.boneInverses.length = 0;
  8547. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8548. const inverse = new Matrix4();
  8549. if ( this.bones[ i ] ) {
  8550. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8551. }
  8552. this.boneInverses.push( inverse );
  8553. }
  8554. }
  8555. pose() {
  8556. // recover the bind-time world matrices
  8557. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8558. const bone = this.bones[ i ];
  8559. if ( bone ) {
  8560. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8561. }
  8562. }
  8563. // compute the local matrices, positions, rotations and scales
  8564. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8565. const bone = this.bones[ i ];
  8566. if ( bone ) {
  8567. if ( bone.parent && bone.parent.isBone ) {
  8568. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8569. bone.matrix.multiply( bone.matrixWorld );
  8570. } else {
  8571. bone.matrix.copy( bone.matrixWorld );
  8572. }
  8573. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8574. }
  8575. }
  8576. }
  8577. update() {
  8578. const bones = this.bones;
  8579. const boneInverses = this.boneInverses;
  8580. const boneMatrices = this.boneMatrices;
  8581. const boneTexture = this.boneTexture;
  8582. // flatten bone matrices to array
  8583. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8584. // compute the offset between the current and the original transform
  8585. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8586. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8587. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8588. }
  8589. if ( boneTexture !== null ) {
  8590. boneTexture.needsUpdate = true;
  8591. }
  8592. }
  8593. clone() {
  8594. return new Skeleton( this.bones, this.boneInverses );
  8595. }
  8596. computeBoneTexture() {
  8597. // layout (1 matrix = 4 pixels)
  8598. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8599. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8600. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8601. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8602. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8603. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8604. size = Math.ceil( size / 4 ) * 4;
  8605. size = Math.max( size, 4 );
  8606. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8607. boneMatrices.set( this.boneMatrices ); // copy current values
  8608. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8609. boneTexture.needsUpdate = true;
  8610. this.boneMatrices = boneMatrices;
  8611. this.boneTexture = boneTexture;
  8612. return this;
  8613. }
  8614. getBoneByName( name ) {
  8615. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8616. const bone = this.bones[ i ];
  8617. if ( bone.name === name ) {
  8618. return bone;
  8619. }
  8620. }
  8621. return undefined;
  8622. }
  8623. dispose( ) {
  8624. if ( this.boneTexture !== null ) {
  8625. this.boneTexture.dispose();
  8626. this.boneTexture = null;
  8627. }
  8628. }
  8629. fromJSON( json, bones ) {
  8630. this.uuid = json.uuid;
  8631. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8632. const uuid = json.bones[ i ];
  8633. let bone = bones[ uuid ];
  8634. if ( bone === undefined ) {
  8635. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8636. bone = new Bone();
  8637. }
  8638. this.bones.push( bone );
  8639. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8640. }
  8641. this.init();
  8642. return this;
  8643. }
  8644. toJSON() {
  8645. const data = {
  8646. metadata: {
  8647. version: 4.6,
  8648. type: 'Skeleton',
  8649. generator: 'Skeleton.toJSON'
  8650. },
  8651. bones: [],
  8652. boneInverses: []
  8653. };
  8654. data.uuid = this.uuid;
  8655. const bones = this.bones;
  8656. const boneInverses = this.boneInverses;
  8657. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8658. const bone = bones[ i ];
  8659. data.bones.push( bone.uuid );
  8660. const boneInverse = boneInverses[ i ];
  8661. data.boneInverses.push( boneInverse.toArray() );
  8662. }
  8663. return data;
  8664. }
  8665. }
  8666. class InstancedBufferAttribute extends BufferAttribute {
  8667. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8668. super( array, itemSize, normalized );
  8669. this.isInstancedBufferAttribute = true;
  8670. this.meshPerAttribute = meshPerAttribute;
  8671. }
  8672. copy( source ) {
  8673. super.copy( source );
  8674. this.meshPerAttribute = source.meshPerAttribute;
  8675. return this;
  8676. }
  8677. toJSON() {
  8678. const data = super.toJSON();
  8679. data.meshPerAttribute = this.meshPerAttribute;
  8680. data.isInstancedBufferAttribute = true;
  8681. return data;
  8682. }
  8683. }
  8684. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8685. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8686. const _instanceIntersects = [];
  8687. const _box3 = /*@__PURE__*/ new Box3();
  8688. const _identity = /*@__PURE__*/ new Matrix4();
  8689. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8690. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8691. class InstancedMesh extends Mesh {
  8692. constructor( geometry, material, count ) {
  8693. super( geometry, material );
  8694. this.isInstancedMesh = true;
  8695. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8696. this.instanceColor = null;
  8697. this.morphTexture = null;
  8698. this.count = count;
  8699. this.boundingBox = null;
  8700. this.boundingSphere = null;
  8701. for ( let i = 0; i < count; i ++ ) {
  8702. this.setMatrixAt( i, _identity );
  8703. }
  8704. }
  8705. computeBoundingBox() {
  8706. const geometry = this.geometry;
  8707. const count = this.count;
  8708. if ( this.boundingBox === null ) {
  8709. this.boundingBox = new Box3();
  8710. }
  8711. if ( geometry.boundingBox === null ) {
  8712. geometry.computeBoundingBox();
  8713. }
  8714. this.boundingBox.makeEmpty();
  8715. for ( let i = 0; i < count; i ++ ) {
  8716. this.getMatrixAt( i, _instanceLocalMatrix );
  8717. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8718. this.boundingBox.union( _box3 );
  8719. }
  8720. }
  8721. computeBoundingSphere() {
  8722. const geometry = this.geometry;
  8723. const count = this.count;
  8724. if ( this.boundingSphere === null ) {
  8725. this.boundingSphere = new Sphere();
  8726. }
  8727. if ( geometry.boundingSphere === null ) {
  8728. geometry.computeBoundingSphere();
  8729. }
  8730. this.boundingSphere.makeEmpty();
  8731. for ( let i = 0; i < count; i ++ ) {
  8732. this.getMatrixAt( i, _instanceLocalMatrix );
  8733. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8734. this.boundingSphere.union( _sphere$4 );
  8735. }
  8736. }
  8737. copy( source, recursive ) {
  8738. super.copy( source, recursive );
  8739. this.instanceMatrix.copy( source.instanceMatrix );
  8740. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8741. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8742. this.count = source.count;
  8743. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8744. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8745. return this;
  8746. }
  8747. getColorAt( index, color ) {
  8748. color.fromArray( this.instanceColor.array, index * 3 );
  8749. }
  8750. getMatrixAt( index, matrix ) {
  8751. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8752. }
  8753. getMorphAt( index, object ) {
  8754. const objectInfluences = object.morphTargetInfluences;
  8755. const array = this.morphTexture.source.data.data;
  8756. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8757. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8758. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8759. objectInfluences[ i ] = array[ dataIndex + i ];
  8760. }
  8761. }
  8762. raycast( raycaster, intersects ) {
  8763. const matrixWorld = this.matrixWorld;
  8764. const raycastTimes = this.count;
  8765. _mesh$1.geometry = this.geometry;
  8766. _mesh$1.material = this.material;
  8767. if ( _mesh$1.material === undefined ) return;
  8768. // test with bounding sphere first
  8769. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8770. _sphere$4.copy( this.boundingSphere );
  8771. _sphere$4.applyMatrix4( matrixWorld );
  8772. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8773. // now test each instance
  8774. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8775. // calculate the world matrix for each instance
  8776. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8777. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8778. // the mesh represents this single instance
  8779. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8780. _mesh$1.raycast( raycaster, _instanceIntersects );
  8781. // process the result of raycast
  8782. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8783. const intersect = _instanceIntersects[ i ];
  8784. intersect.instanceId = instanceId;
  8785. intersect.object = this;
  8786. intersects.push( intersect );
  8787. }
  8788. _instanceIntersects.length = 0;
  8789. }
  8790. }
  8791. setColorAt( index, color ) {
  8792. if ( this.instanceColor === null ) {
  8793. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  8794. }
  8795. color.toArray( this.instanceColor.array, index * 3 );
  8796. }
  8797. setMatrixAt( index, matrix ) {
  8798. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8799. }
  8800. setMorphAt( index, object ) {
  8801. const objectInfluences = object.morphTargetInfluences;
  8802. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8803. if ( this.morphTexture === null ) {
  8804. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8805. }
  8806. const array = this.morphTexture.source.data.data;
  8807. let morphInfluencesSum = 0;
  8808. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8809. morphInfluencesSum += objectInfluences[ i ];
  8810. }
  8811. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8812. const dataIndex = len * index;
  8813. array[ dataIndex ] = morphBaseInfluence;
  8814. array.set( objectInfluences, dataIndex + 1 );
  8815. }
  8816. updateMorphTargets() {
  8817. }
  8818. dispose() {
  8819. this.dispatchEvent( { type: 'dispose' } );
  8820. if ( this.morphTexture !== null ) {
  8821. this.morphTexture.dispose();
  8822. this.morphTexture = null;
  8823. }
  8824. return this;
  8825. }
  8826. }
  8827. const _vector1 = /*@__PURE__*/ new Vector3();
  8828. const _vector2 = /*@__PURE__*/ new Vector3();
  8829. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8830. class Plane {
  8831. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8832. this.isPlane = true;
  8833. // normal is assumed to be normalized
  8834. this.normal = normal;
  8835. this.constant = constant;
  8836. }
  8837. set( normal, constant ) {
  8838. this.normal.copy( normal );
  8839. this.constant = constant;
  8840. return this;
  8841. }
  8842. setComponents( x, y, z, w ) {
  8843. this.normal.set( x, y, z );
  8844. this.constant = w;
  8845. return this;
  8846. }
  8847. setFromNormalAndCoplanarPoint( normal, point ) {
  8848. this.normal.copy( normal );
  8849. this.constant = - point.dot( this.normal );
  8850. return this;
  8851. }
  8852. setFromCoplanarPoints( a, b, c ) {
  8853. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8854. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8855. this.setFromNormalAndCoplanarPoint( normal, a );
  8856. return this;
  8857. }
  8858. copy( plane ) {
  8859. this.normal.copy( plane.normal );
  8860. this.constant = plane.constant;
  8861. return this;
  8862. }
  8863. normalize() {
  8864. // Note: will lead to a divide by zero if the plane is invalid.
  8865. const inverseNormalLength = 1.0 / this.normal.length();
  8866. this.normal.multiplyScalar( inverseNormalLength );
  8867. this.constant *= inverseNormalLength;
  8868. return this;
  8869. }
  8870. negate() {
  8871. this.constant *= - 1;
  8872. this.normal.negate();
  8873. return this;
  8874. }
  8875. distanceToPoint( point ) {
  8876. return this.normal.dot( point ) + this.constant;
  8877. }
  8878. distanceToSphere( sphere ) {
  8879. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8880. }
  8881. projectPoint( point, target ) {
  8882. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8883. }
  8884. intersectLine( line, target ) {
  8885. const direction = line.delta( _vector1 );
  8886. const denominator = this.normal.dot( direction );
  8887. if ( denominator === 0 ) {
  8888. // line is coplanar, return origin
  8889. if ( this.distanceToPoint( line.start ) === 0 ) {
  8890. return target.copy( line.start );
  8891. }
  8892. // Unsure if this is the correct method to handle this case.
  8893. return null;
  8894. }
  8895. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8896. if ( t < 0 || t > 1 ) {
  8897. return null;
  8898. }
  8899. return target.copy( line.start ).addScaledVector( direction, t );
  8900. }
  8901. intersectsLine( line ) {
  8902. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8903. const startSign = this.distanceToPoint( line.start );
  8904. const endSign = this.distanceToPoint( line.end );
  8905. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8906. }
  8907. intersectsBox( box ) {
  8908. return box.intersectsPlane( this );
  8909. }
  8910. intersectsSphere( sphere ) {
  8911. return sphere.intersectsPlane( this );
  8912. }
  8913. coplanarPoint( target ) {
  8914. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8915. }
  8916. applyMatrix4( matrix, optionalNormalMatrix ) {
  8917. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8918. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8919. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8920. this.constant = - referencePoint.dot( normal );
  8921. return this;
  8922. }
  8923. translate( offset ) {
  8924. this.constant -= offset.dot( this.normal );
  8925. return this;
  8926. }
  8927. equals( plane ) {
  8928. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8929. }
  8930. clone() {
  8931. return new this.constructor().copy( this );
  8932. }
  8933. }
  8934. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8935. const _vector$6 = /*@__PURE__*/ new Vector3();
  8936. class Frustum {
  8937. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8938. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8939. }
  8940. set( p0, p1, p2, p3, p4, p5 ) {
  8941. const planes = this.planes;
  8942. planes[ 0 ].copy( p0 );
  8943. planes[ 1 ].copy( p1 );
  8944. planes[ 2 ].copy( p2 );
  8945. planes[ 3 ].copy( p3 );
  8946. planes[ 4 ].copy( p4 );
  8947. planes[ 5 ].copy( p5 );
  8948. return this;
  8949. }
  8950. copy( frustum ) {
  8951. const planes = this.planes;
  8952. for ( let i = 0; i < 6; i ++ ) {
  8953. planes[ i ].copy( frustum.planes[ i ] );
  8954. }
  8955. return this;
  8956. }
  8957. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  8958. const planes = this.planes;
  8959. const me = m.elements;
  8960. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8961. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8962. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8963. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8964. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8965. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8966. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8967. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8968. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8969. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8970. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8971. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8972. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  8973. } else {
  8974. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  8975. }
  8976. return this;
  8977. }
  8978. intersectsObject( object ) {
  8979. if ( object.boundingSphere !== undefined ) {
  8980. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  8981. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  8982. } else {
  8983. const geometry = object.geometry;
  8984. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8985. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8986. }
  8987. return this.intersectsSphere( _sphere$3 );
  8988. }
  8989. intersectsSprite( sprite ) {
  8990. _sphere$3.center.set( 0, 0, 0 );
  8991. _sphere$3.radius = 0.7071067811865476;
  8992. _sphere$3.applyMatrix4( sprite.matrixWorld );
  8993. return this.intersectsSphere( _sphere$3 );
  8994. }
  8995. intersectsSphere( sphere ) {
  8996. const planes = this.planes;
  8997. const center = sphere.center;
  8998. const negRadius = - sphere.radius;
  8999. for ( let i = 0; i < 6; i ++ ) {
  9000. const distance = planes[ i ].distanceToPoint( center );
  9001. if ( distance < negRadius ) {
  9002. return false;
  9003. }
  9004. }
  9005. return true;
  9006. }
  9007. intersectsBox( box ) {
  9008. const planes = this.planes;
  9009. for ( let i = 0; i < 6; i ++ ) {
  9010. const plane = planes[ i ];
  9011. // corner at max distance
  9012. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9013. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9014. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9015. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9016. return false;
  9017. }
  9018. }
  9019. return true;
  9020. }
  9021. containsPoint( point ) {
  9022. const planes = this.planes;
  9023. for ( let i = 0; i < 6; i ++ ) {
  9024. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9025. return false;
  9026. }
  9027. }
  9028. return true;
  9029. }
  9030. clone() {
  9031. return new this.constructor().copy( this );
  9032. }
  9033. }
  9034. function sortOpaque( a, b ) {
  9035. return a.z - b.z;
  9036. }
  9037. function sortTransparent( a, b ) {
  9038. return b.z - a.z;
  9039. }
  9040. class MultiDrawRenderList {
  9041. constructor() {
  9042. this.index = 0;
  9043. this.pool = [];
  9044. this.list = [];
  9045. }
  9046. push( drawRange, z, index ) {
  9047. const pool = this.pool;
  9048. const list = this.list;
  9049. if ( this.index >= pool.length ) {
  9050. pool.push( {
  9051. start: - 1,
  9052. count: - 1,
  9053. z: - 1,
  9054. index: - 1,
  9055. } );
  9056. }
  9057. const item = pool[ this.index ];
  9058. list.push( item );
  9059. this.index ++;
  9060. item.start = drawRange.start;
  9061. item.count = drawRange.count;
  9062. item.z = z;
  9063. item.index = index;
  9064. }
  9065. reset() {
  9066. this.list.length = 0;
  9067. this.index = 0;
  9068. }
  9069. }
  9070. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9071. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9072. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9073. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9074. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9075. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9076. const _box$1 = /*@__PURE__*/ new Box3();
  9077. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9078. const _vector$5 = /*@__PURE__*/ new Vector3();
  9079. const _forward = /*@__PURE__*/ new Vector3();
  9080. const _temp = /*@__PURE__*/ new Vector3();
  9081. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9082. const _mesh = /*@__PURE__*/ new Mesh();
  9083. const _batchIntersects = [];
  9084. // @TODO: SkinnedMesh support?
  9085. // @TODO: geometry.groups support?
  9086. // @TODO: geometry.drawRange support?
  9087. // @TODO: geometry.morphAttributes support?
  9088. // @TODO: Support uniform parameter per geometry
  9089. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9090. // copies data from attribute "src" into "target" starting at "targetOffset"
  9091. function copyAttributeData( src, target, targetOffset = 0 ) {
  9092. const itemSize = target.itemSize;
  9093. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9094. // use the component getters and setters if the array data cannot
  9095. // be copied directly
  9096. const vertexCount = src.count;
  9097. for ( let i = 0; i < vertexCount; i ++ ) {
  9098. for ( let c = 0; c < itemSize; c ++ ) {
  9099. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9100. }
  9101. }
  9102. } else {
  9103. // faster copy approach using typed array set function
  9104. target.array.set( src.array, targetOffset * itemSize );
  9105. }
  9106. target.needsUpdate = true;
  9107. }
  9108. class BatchedMesh extends Mesh {
  9109. get maxInstanceCount() {
  9110. return this._maxInstanceCount;
  9111. }
  9112. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9113. super( new BufferGeometry(), material );
  9114. this.isBatchedMesh = true;
  9115. this.perObjectFrustumCulled = true;
  9116. this.sortObjects = true;
  9117. this.boundingBox = null;
  9118. this.boundingSphere = null;
  9119. this.customSort = null;
  9120. // stores visible, active, and geometry id per object
  9121. this._drawInfo = [];
  9122. // geometry information
  9123. this._drawRanges = [];
  9124. this._reservedRanges = [];
  9125. this._bounds = [];
  9126. this._maxInstanceCount = maxInstanceCount;
  9127. this._maxVertexCount = maxVertexCount;
  9128. this._maxIndexCount = maxIndexCount;
  9129. this._geometryInitialized = false;
  9130. this._geometryCount = 0;
  9131. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9132. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9133. this._multiDrawCount = 0;
  9134. this._multiDrawInstances = null;
  9135. this._visibilityChanged = true;
  9136. // Local matrix per geometry by using data texture
  9137. this._matricesTexture = null;
  9138. this._indirectTexture = null;
  9139. this._colorsTexture = null;
  9140. this._initMatricesTexture();
  9141. this._initIndirectTexture();
  9142. }
  9143. _initMatricesTexture() {
  9144. // layout (1 matrix = 4 pixels)
  9145. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9146. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9147. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9148. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9149. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9150. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9151. size = Math.ceil( size / 4 ) * 4;
  9152. size = Math.max( size, 4 );
  9153. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9154. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9155. this._matricesTexture = matricesTexture;
  9156. }
  9157. _initIndirectTexture() {
  9158. let size = Math.sqrt( this._maxInstanceCount );
  9159. size = Math.ceil( size );
  9160. const indirectArray = new Uint32Array( size * size );
  9161. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9162. this._indirectTexture = indirectTexture;
  9163. }
  9164. _initColorsTexture() {
  9165. let size = Math.sqrt( this._maxIndexCount );
  9166. size = Math.ceil( size );
  9167. // 4 floats per RGBA pixel initialized to white
  9168. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9169. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9170. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9171. this._colorsTexture = colorsTexture;
  9172. }
  9173. _initializeGeometry( reference ) {
  9174. const geometry = this.geometry;
  9175. const maxVertexCount = this._maxVertexCount;
  9176. const maxIndexCount = this._maxIndexCount;
  9177. if ( this._geometryInitialized === false ) {
  9178. for ( const attributeName in reference.attributes ) {
  9179. const srcAttribute = reference.getAttribute( attributeName );
  9180. const { array, itemSize, normalized } = srcAttribute;
  9181. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9182. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9183. geometry.setAttribute( attributeName, dstAttribute );
  9184. }
  9185. if ( reference.getIndex() !== null ) {
  9186. // Reserve last u16 index for primitive restart.
  9187. const indexArray = maxVertexCount > 65535
  9188. ? new Uint32Array( maxIndexCount )
  9189. : new Uint16Array( maxIndexCount );
  9190. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9191. }
  9192. this._geometryInitialized = true;
  9193. }
  9194. }
  9195. // Make sure the geometry is compatible with the existing combined geometry attributes
  9196. _validateGeometry( geometry ) {
  9197. // check to ensure the geometries are using consistent attributes and indices
  9198. const batchGeometry = this.geometry;
  9199. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9200. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9201. }
  9202. for ( const attributeName in batchGeometry.attributes ) {
  9203. if ( ! geometry.hasAttribute( attributeName ) ) {
  9204. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9205. }
  9206. const srcAttribute = geometry.getAttribute( attributeName );
  9207. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9208. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9209. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9210. }
  9211. }
  9212. }
  9213. setCustomSort( func ) {
  9214. this.customSort = func;
  9215. return this;
  9216. }
  9217. computeBoundingBox() {
  9218. if ( this.boundingBox === null ) {
  9219. this.boundingBox = new Box3();
  9220. }
  9221. const geometryCount = this._geometryCount;
  9222. const boundingBox = this.boundingBox;
  9223. const drawInfo = this._drawInfo;
  9224. boundingBox.makeEmpty();
  9225. for ( let i = 0; i < geometryCount; i ++ ) {
  9226. if ( drawInfo[ i ].active === false ) continue;
  9227. const geometryId = drawInfo[ i ].geometryIndex;
  9228. this.getMatrixAt( i, _matrix$1 );
  9229. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9230. boundingBox.union( _box$1 );
  9231. }
  9232. }
  9233. computeBoundingSphere() {
  9234. if ( this.boundingSphere === null ) {
  9235. this.boundingSphere = new Sphere();
  9236. }
  9237. const boundingSphere = this.boundingSphere;
  9238. const drawInfo = this._drawInfo;
  9239. boundingSphere.makeEmpty();
  9240. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9241. if ( drawInfo[ i ].active === false ) continue;
  9242. const geometryId = drawInfo[ i ].geometryIndex;
  9243. this.getMatrixAt( i, _matrix$1 );
  9244. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9245. boundingSphere.union( _sphere$2 );
  9246. }
  9247. }
  9248. addInstance( geometryId ) {
  9249. // ensure we're not over geometry
  9250. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9251. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9252. }
  9253. this._drawInfo.push( {
  9254. visible: true,
  9255. active: true,
  9256. geometryIndex: geometryId,
  9257. } );
  9258. // initialize the matrix
  9259. const drawId = this._drawInfo.length - 1;
  9260. const matricesTexture = this._matricesTexture;
  9261. const matricesArray = matricesTexture.image.data;
  9262. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9263. matricesTexture.needsUpdate = true;
  9264. const colorsTexture = this._colorsTexture;
  9265. if ( colorsTexture ) {
  9266. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9267. colorsTexture.needsUpdate = true;
  9268. }
  9269. return drawId;
  9270. }
  9271. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9272. this._initializeGeometry( geometry );
  9273. this._validateGeometry( geometry );
  9274. // ensure we're not over geometry
  9275. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9276. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9277. }
  9278. // get the necessary range fo the geometry
  9279. const reservedRange = {
  9280. vertexStart: - 1,
  9281. vertexCount: - 1,
  9282. indexStart: - 1,
  9283. indexCount: - 1,
  9284. };
  9285. let lastRange = null;
  9286. const reservedRanges = this._reservedRanges;
  9287. const drawRanges = this._drawRanges;
  9288. const bounds = this._bounds;
  9289. if ( this._geometryCount !== 0 ) {
  9290. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9291. }
  9292. if ( vertexCount === - 1 ) {
  9293. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9294. } else {
  9295. reservedRange.vertexCount = vertexCount;
  9296. }
  9297. if ( lastRange === null ) {
  9298. reservedRange.vertexStart = 0;
  9299. } else {
  9300. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9301. }
  9302. const index = geometry.getIndex();
  9303. const hasIndex = index !== null;
  9304. if ( hasIndex ) {
  9305. if ( indexCount === - 1 ) {
  9306. reservedRange.indexCount = index.count;
  9307. } else {
  9308. reservedRange.indexCount = indexCount;
  9309. }
  9310. if ( lastRange === null ) {
  9311. reservedRange.indexStart = 0;
  9312. } else {
  9313. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9314. }
  9315. }
  9316. if (
  9317. reservedRange.indexStart !== - 1 &&
  9318. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9319. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9320. ) {
  9321. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9322. }
  9323. // update id
  9324. const geometryId = this._geometryCount;
  9325. this._geometryCount ++;
  9326. // add the reserved range and draw range objects
  9327. reservedRanges.push( reservedRange );
  9328. drawRanges.push( {
  9329. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9330. count: - 1
  9331. } );
  9332. bounds.push( {
  9333. boxInitialized: false,
  9334. box: new Box3(),
  9335. sphereInitialized: false,
  9336. sphere: new Sphere()
  9337. } );
  9338. // update the geometry
  9339. this.setGeometryAt( geometryId, geometry );
  9340. return geometryId;
  9341. }
  9342. setGeometryAt( geometryId, geometry ) {
  9343. if ( geometryId >= this._geometryCount ) {
  9344. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9345. }
  9346. this._validateGeometry( geometry );
  9347. const batchGeometry = this.geometry;
  9348. const hasIndex = batchGeometry.getIndex() !== null;
  9349. const dstIndex = batchGeometry.getIndex();
  9350. const srcIndex = geometry.getIndex();
  9351. const reservedRange = this._reservedRanges[ geometryId ];
  9352. if (
  9353. hasIndex &&
  9354. srcIndex.count > reservedRange.indexCount ||
  9355. geometry.attributes.position.count > reservedRange.vertexCount
  9356. ) {
  9357. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9358. }
  9359. // copy geometry over
  9360. const vertexStart = reservedRange.vertexStart;
  9361. const vertexCount = reservedRange.vertexCount;
  9362. for ( const attributeName in batchGeometry.attributes ) {
  9363. // copy attribute data
  9364. const srcAttribute = geometry.getAttribute( attributeName );
  9365. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9366. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9367. // fill the rest in with zeroes
  9368. const itemSize = srcAttribute.itemSize;
  9369. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9370. const index = vertexStart + i;
  9371. for ( let c = 0; c < itemSize; c ++ ) {
  9372. dstAttribute.setComponent( index, c, 0 );
  9373. }
  9374. }
  9375. dstAttribute.needsUpdate = true;
  9376. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9377. }
  9378. // copy index
  9379. if ( hasIndex ) {
  9380. const indexStart = reservedRange.indexStart;
  9381. // copy index data over
  9382. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9383. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9384. }
  9385. // fill the rest in with zeroes
  9386. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9387. dstIndex.setX( indexStart + i, vertexStart );
  9388. }
  9389. dstIndex.needsUpdate = true;
  9390. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9391. }
  9392. // store the bounding boxes
  9393. const bound = this._bounds[ geometryId ];
  9394. if ( geometry.boundingBox !== null ) {
  9395. bound.box.copy( geometry.boundingBox );
  9396. bound.boxInitialized = true;
  9397. } else {
  9398. bound.boxInitialized = false;
  9399. }
  9400. if ( geometry.boundingSphere !== null ) {
  9401. bound.sphere.copy( geometry.boundingSphere );
  9402. bound.sphereInitialized = true;
  9403. } else {
  9404. bound.sphereInitialized = false;
  9405. }
  9406. // set drawRange count
  9407. const drawRange = this._drawRanges[ geometryId ];
  9408. const posAttr = geometry.getAttribute( 'position' );
  9409. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9410. this._visibilityChanged = true;
  9411. return geometryId;
  9412. }
  9413. /*
  9414. deleteGeometry( geometryId ) {
  9415. // TODO: delete geometry and associated instances
  9416. }
  9417. */
  9418. /*
  9419. deleteInstance( instanceId ) {
  9420. // Note: User needs to call optimize() afterward to pack the data.
  9421. const drawInfo = this._drawInfo;
  9422. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9423. return this;
  9424. }
  9425. drawInfo[ instanceId ].active = false;
  9426. this._visibilityChanged = true;
  9427. return this;
  9428. }
  9429. */
  9430. // get bounding box and compute it if it doesn't exist
  9431. getBoundingBoxAt( geometryId, target ) {
  9432. if ( geometryId >= this._geometryCount ) {
  9433. return null;
  9434. }
  9435. // compute bounding box
  9436. const bound = this._bounds[ geometryId ];
  9437. const box = bound.box;
  9438. const geometry = this.geometry;
  9439. if ( bound.boxInitialized === false ) {
  9440. box.makeEmpty();
  9441. const index = geometry.index;
  9442. const position = geometry.attributes.position;
  9443. const drawRange = this._drawRanges[ geometryId ];
  9444. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9445. let iv = i;
  9446. if ( index ) {
  9447. iv = index.getX( iv );
  9448. }
  9449. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9450. }
  9451. bound.boxInitialized = true;
  9452. }
  9453. target.copy( box );
  9454. return target;
  9455. }
  9456. // get bounding sphere and compute it if it doesn't exist
  9457. getBoundingSphereAt( geometryId, target ) {
  9458. if ( geometryId >= this._geometryCount ) {
  9459. return null;
  9460. }
  9461. // compute bounding sphere
  9462. const bound = this._bounds[ geometryId ];
  9463. const sphere = bound.sphere;
  9464. const geometry = this.geometry;
  9465. if ( bound.sphereInitialized === false ) {
  9466. sphere.makeEmpty();
  9467. this.getBoundingBoxAt( geometryId, _box$1 );
  9468. _box$1.getCenter( sphere.center );
  9469. const index = geometry.index;
  9470. const position = geometry.attributes.position;
  9471. const drawRange = this._drawRanges[ geometryId ];
  9472. let maxRadiusSq = 0;
  9473. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9474. let iv = i;
  9475. if ( index ) {
  9476. iv = index.getX( iv );
  9477. }
  9478. _vector$5.fromBufferAttribute( position, iv );
  9479. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9480. }
  9481. sphere.radius = Math.sqrt( maxRadiusSq );
  9482. bound.sphereInitialized = true;
  9483. }
  9484. target.copy( sphere );
  9485. return target;
  9486. }
  9487. setMatrixAt( instanceId, matrix ) {
  9488. // @TODO: Map geometryId to index of the arrays because
  9489. // optimize() can make geometryId mismatch the index
  9490. const drawInfo = this._drawInfo;
  9491. const matricesTexture = this._matricesTexture;
  9492. const matricesArray = this._matricesTexture.image.data;
  9493. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9494. return this;
  9495. }
  9496. matrix.toArray( matricesArray, instanceId * 16 );
  9497. matricesTexture.needsUpdate = true;
  9498. return this;
  9499. }
  9500. getMatrixAt( instanceId, matrix ) {
  9501. const drawInfo = this._drawInfo;
  9502. const matricesArray = this._matricesTexture.image.data;
  9503. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9504. return null;
  9505. }
  9506. return matrix.fromArray( matricesArray, instanceId * 16 );
  9507. }
  9508. setColorAt( instanceId, color ) {
  9509. if ( this._colorsTexture === null ) {
  9510. this._initColorsTexture();
  9511. }
  9512. // @TODO: Map id to index of the arrays because
  9513. // optimize() can make id mismatch the index
  9514. const colorsTexture = this._colorsTexture;
  9515. const colorsArray = this._colorsTexture.image.data;
  9516. const drawInfo = this._drawInfo;
  9517. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9518. return this;
  9519. }
  9520. color.toArray( colorsArray, instanceId * 4 );
  9521. colorsTexture.needsUpdate = true;
  9522. return this;
  9523. }
  9524. getColorAt( instanceId, color ) {
  9525. const colorsArray = this._colorsTexture.image.data;
  9526. const drawInfo = this._drawInfo;
  9527. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9528. return null;
  9529. }
  9530. return color.fromArray( colorsArray, instanceId * 4 );
  9531. }
  9532. setVisibleAt( instanceId, value ) {
  9533. // if the geometry is out of range, not active, or visibility state
  9534. // does not change then return early
  9535. const drawInfo = this._drawInfo;
  9536. if (
  9537. instanceId >= drawInfo.length ||
  9538. drawInfo[ instanceId ].active === false ||
  9539. drawInfo[ instanceId ].visible === value
  9540. ) {
  9541. return this;
  9542. }
  9543. drawInfo[ instanceId ].visible = value;
  9544. this._visibilityChanged = true;
  9545. return this;
  9546. }
  9547. getVisibleAt( instanceId ) {
  9548. // return early if the geometry is out of range or not active
  9549. const drawInfo = this._drawInfo;
  9550. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9551. return false;
  9552. }
  9553. return drawInfo[ instanceId ].visible;
  9554. }
  9555. raycast( raycaster, intersects ) {
  9556. const drawInfo = this._drawInfo;
  9557. const drawRanges = this._drawRanges;
  9558. const matrixWorld = this.matrixWorld;
  9559. const batchGeometry = this.geometry;
  9560. // iterate over each geometry
  9561. _mesh.material = this.material;
  9562. _mesh.geometry.index = batchGeometry.index;
  9563. _mesh.geometry.attributes = batchGeometry.attributes;
  9564. if ( _mesh.geometry.boundingBox === null ) {
  9565. _mesh.geometry.boundingBox = new Box3();
  9566. }
  9567. if ( _mesh.geometry.boundingSphere === null ) {
  9568. _mesh.geometry.boundingSphere = new Sphere();
  9569. }
  9570. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9571. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9572. continue;
  9573. }
  9574. const geometryId = drawInfo[ i ].geometryIndex;
  9575. const drawRange = drawRanges[ geometryId ];
  9576. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9577. // ge the intersects
  9578. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9579. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9580. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9581. _mesh.raycast( raycaster, _batchIntersects );
  9582. // add batch id to the intersects
  9583. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9584. const intersect = _batchIntersects[ j ];
  9585. intersect.object = this;
  9586. intersect.batchId = i;
  9587. intersects.push( intersect );
  9588. }
  9589. _batchIntersects.length = 0;
  9590. }
  9591. _mesh.material = null;
  9592. _mesh.geometry.index = null;
  9593. _mesh.geometry.attributes = {};
  9594. _mesh.geometry.setDrawRange( 0, Infinity );
  9595. }
  9596. copy( source ) {
  9597. super.copy( source );
  9598. this.geometry = source.geometry.clone();
  9599. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9600. this.sortObjects = source.sortObjects;
  9601. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9602. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9603. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9604. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9605. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9606. this._bounds = source._bounds.map( bound => ( {
  9607. boxInitialized: bound.boxInitialized,
  9608. box: bound.box.clone(),
  9609. sphereInitialized: bound.sphereInitialized,
  9610. sphere: bound.sphere.clone()
  9611. } ) );
  9612. this._maxInstanceCount = source._maxInstanceCount;
  9613. this._maxVertexCount = source._maxVertexCount;
  9614. this._maxIndexCount = source._maxIndexCount;
  9615. this._geometryInitialized = source._geometryInitialized;
  9616. this._geometryCount = source._geometryCount;
  9617. this._multiDrawCounts = source._multiDrawCounts.slice();
  9618. this._multiDrawStarts = source._multiDrawStarts.slice();
  9619. this._matricesTexture = source._matricesTexture.clone();
  9620. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9621. if ( this._colorsTexture !== null ) {
  9622. this._colorsTexture = source._colorsTexture.clone();
  9623. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9624. }
  9625. return this;
  9626. }
  9627. dispose() {
  9628. // Assuming the geometry is not shared with other meshes
  9629. this.geometry.dispose();
  9630. this._matricesTexture.dispose();
  9631. this._matricesTexture = null;
  9632. this._indirectTexture.dispose();
  9633. this._indirectTexture = null;
  9634. if ( this._colorsTexture !== null ) {
  9635. this._colorsTexture.dispose();
  9636. this._colorsTexture = null;
  9637. }
  9638. return this;
  9639. }
  9640. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9641. // if visibility has not changed and frustum culling and object sorting is not required
  9642. // then skip iterating over all items
  9643. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9644. return;
  9645. }
  9646. // the indexed version of the multi draw function requires specifying the start
  9647. // offset in bytes.
  9648. const index = geometry.getIndex();
  9649. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9650. const drawInfo = this._drawInfo;
  9651. const multiDrawStarts = this._multiDrawStarts;
  9652. const multiDrawCounts = this._multiDrawCounts;
  9653. const drawRanges = this._drawRanges;
  9654. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9655. const indirectTexture = this._indirectTexture;
  9656. const indirectArray = indirectTexture.image.data;
  9657. // prepare the frustum in the local frame
  9658. if ( perObjectFrustumCulled ) {
  9659. _projScreenMatrix$3
  9660. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9661. .multiply( this.matrixWorld );
  9662. _frustum$1.setFromProjectionMatrix(
  9663. _projScreenMatrix$3,
  9664. renderer.coordinateSystem
  9665. );
  9666. }
  9667. let count = 0;
  9668. if ( this.sortObjects ) {
  9669. // get the camera position in the local frame
  9670. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9671. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9672. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9673. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9674. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9675. const geometryId = drawInfo[ i ].geometryIndex;
  9676. // get the bounds in world space
  9677. this.getMatrixAt( i, _matrix$1 );
  9678. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9679. // determine whether the batched geometry is within the frustum
  9680. let culled = false;
  9681. if ( perObjectFrustumCulled ) {
  9682. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9683. }
  9684. if ( ! culled ) {
  9685. // get the distance from camera used for sorting
  9686. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9687. _renderList.push( drawRanges[ geometryId ], z, i );
  9688. }
  9689. }
  9690. }
  9691. // Sort the draw ranges and prep for rendering
  9692. const list = _renderList.list;
  9693. const customSort = this.customSort;
  9694. if ( customSort === null ) {
  9695. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9696. } else {
  9697. customSort.call( this, list, camera );
  9698. }
  9699. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9700. const item = list[ i ];
  9701. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9702. multiDrawCounts[ count ] = item.count;
  9703. indirectArray[ count ] = item.index;
  9704. count ++;
  9705. }
  9706. _renderList.reset();
  9707. } else {
  9708. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9709. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9710. const geometryId = drawInfo[ i ].geometryIndex;
  9711. // determine whether the batched geometry is within the frustum
  9712. let culled = false;
  9713. if ( perObjectFrustumCulled ) {
  9714. // get the bounds in world space
  9715. this.getMatrixAt( i, _matrix$1 );
  9716. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9717. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9718. }
  9719. if ( ! culled ) {
  9720. const range = drawRanges[ geometryId ];
  9721. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9722. multiDrawCounts[ count ] = range.count;
  9723. indirectArray[ count ] = i;
  9724. count ++;
  9725. }
  9726. }
  9727. }
  9728. }
  9729. indirectTexture.needsUpdate = true;
  9730. this._multiDrawCount = count;
  9731. this._visibilityChanged = false;
  9732. }
  9733. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9734. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9735. }
  9736. }
  9737. class LineBasicMaterial extends Material {
  9738. constructor( parameters ) {
  9739. super();
  9740. this.isLineBasicMaterial = true;
  9741. this.type = 'LineBasicMaterial';
  9742. this.color = new Color( 0xffffff );
  9743. this.map = null;
  9744. this.linewidth = 1;
  9745. this.linecap = 'round';
  9746. this.linejoin = 'round';
  9747. this.fog = true;
  9748. this.setValues( parameters );
  9749. }
  9750. copy( source ) {
  9751. super.copy( source );
  9752. this.color.copy( source.color );
  9753. this.map = source.map;
  9754. this.linewidth = source.linewidth;
  9755. this.linecap = source.linecap;
  9756. this.linejoin = source.linejoin;
  9757. this.fog = source.fog;
  9758. return this;
  9759. }
  9760. }
  9761. const _vStart = /*@__PURE__*/ new Vector3();
  9762. const _vEnd = /*@__PURE__*/ new Vector3();
  9763. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9764. const _ray$1 = /*@__PURE__*/ new Ray();
  9765. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9766. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9767. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9768. class Line extends Object3D {
  9769. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9770. super();
  9771. this.isLine = true;
  9772. this.type = 'Line';
  9773. this.geometry = geometry;
  9774. this.material = material;
  9775. this.updateMorphTargets();
  9776. }
  9777. copy( source, recursive ) {
  9778. super.copy( source, recursive );
  9779. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9780. this.geometry = source.geometry;
  9781. return this;
  9782. }
  9783. computeLineDistances() {
  9784. const geometry = this.geometry;
  9785. // we assume non-indexed geometry
  9786. if ( geometry.index === null ) {
  9787. const positionAttribute = geometry.attributes.position;
  9788. const lineDistances = [ 0 ];
  9789. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  9790. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  9791. _vEnd.fromBufferAttribute( positionAttribute, i );
  9792. lineDistances[ i ] = lineDistances[ i - 1 ];
  9793. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  9794. }
  9795. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9796. } else {
  9797. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9798. }
  9799. return this;
  9800. }
  9801. raycast( raycaster, intersects ) {
  9802. const geometry = this.geometry;
  9803. const matrixWorld = this.matrixWorld;
  9804. const threshold = raycaster.params.Line.threshold;
  9805. const drawRange = geometry.drawRange;
  9806. // Checking boundingSphere distance to ray
  9807. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9808. _sphere$1.copy( geometry.boundingSphere );
  9809. _sphere$1.applyMatrix4( matrixWorld );
  9810. _sphere$1.radius += threshold;
  9811. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  9812. //
  9813. _inverseMatrix$1.copy( matrixWorld ).invert();
  9814. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  9815. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9816. const localThresholdSq = localThreshold * localThreshold;
  9817. const step = this.isLineSegments ? 2 : 1;
  9818. const index = geometry.index;
  9819. const attributes = geometry.attributes;
  9820. const positionAttribute = attributes.position;
  9821. if ( index !== null ) {
  9822. const start = Math.max( 0, drawRange.start );
  9823. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9824. for ( let i = start, l = end - 1; i < l; i += step ) {
  9825. const a = index.getX( i );
  9826. const b = index.getX( i + 1 );
  9827. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9828. if ( intersect ) {
  9829. intersects.push( intersect );
  9830. }
  9831. }
  9832. if ( this.isLineLoop ) {
  9833. const a = index.getX( end - 1 );
  9834. const b = index.getX( start );
  9835. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9836. if ( intersect ) {
  9837. intersects.push( intersect );
  9838. }
  9839. }
  9840. } else {
  9841. const start = Math.max( 0, drawRange.start );
  9842. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  9843. for ( let i = start, l = end - 1; i < l; i += step ) {
  9844. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  9845. if ( intersect ) {
  9846. intersects.push( intersect );
  9847. }
  9848. }
  9849. if ( this.isLineLoop ) {
  9850. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  9851. if ( intersect ) {
  9852. intersects.push( intersect );
  9853. }
  9854. }
  9855. }
  9856. }
  9857. updateMorphTargets() {
  9858. const geometry = this.geometry;
  9859. const morphAttributes = geometry.morphAttributes;
  9860. const keys = Object.keys( morphAttributes );
  9861. if ( keys.length > 0 ) {
  9862. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  9863. if ( morphAttribute !== undefined ) {
  9864. this.morphTargetInfluences = [];
  9865. this.morphTargetDictionary = {};
  9866. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9867. const name = morphAttribute[ m ].name || String( m );
  9868. this.morphTargetInfluences.push( 0 );
  9869. this.morphTargetDictionary[ name ] = m;
  9870. }
  9871. }
  9872. }
  9873. }
  9874. }
  9875. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  9876. const positionAttribute = object.geometry.attributes.position;
  9877. _vStart.fromBufferAttribute( positionAttribute, a );
  9878. _vEnd.fromBufferAttribute( positionAttribute, b );
  9879. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  9880. if ( distSq > thresholdSq ) return;
  9881. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  9882. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  9883. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9884. return {
  9885. distance: distance,
  9886. // What do we want? intersection point on the ray or on the segment??
  9887. // point: raycaster.ray.at( distance ),
  9888. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  9889. index: a,
  9890. face: null,
  9891. faceIndex: null,
  9892. object: object
  9893. };
  9894. }
  9895. const _start = /*@__PURE__*/ new Vector3();
  9896. const _end = /*@__PURE__*/ new Vector3();
  9897. class LineSegments extends Line {
  9898. constructor( geometry, material ) {
  9899. super( geometry, material );
  9900. this.isLineSegments = true;
  9901. this.type = 'LineSegments';
  9902. }
  9903. computeLineDistances() {
  9904. const geometry = this.geometry;
  9905. // we assume non-indexed geometry
  9906. if ( geometry.index === null ) {
  9907. const positionAttribute = geometry.attributes.position;
  9908. const lineDistances = [];
  9909. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  9910. _start.fromBufferAttribute( positionAttribute, i );
  9911. _end.fromBufferAttribute( positionAttribute, i + 1 );
  9912. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  9913. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  9914. }
  9915. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9916. } else {
  9917. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9918. }
  9919. return this;
  9920. }
  9921. }
  9922. class LineLoop extends Line {
  9923. constructor( geometry, material ) {
  9924. super( geometry, material );
  9925. this.isLineLoop = true;
  9926. this.type = 'LineLoop';
  9927. }
  9928. }
  9929. class PointsMaterial extends Material {
  9930. constructor( parameters ) {
  9931. super();
  9932. this.isPointsMaterial = true;
  9933. this.type = 'PointsMaterial';
  9934. this.color = new Color( 0xffffff );
  9935. this.map = null;
  9936. this.alphaMap = null;
  9937. this.size = 1;
  9938. this.sizeAttenuation = true;
  9939. this.fog = true;
  9940. this.setValues( parameters );
  9941. }
  9942. copy( source ) {
  9943. super.copy( source );
  9944. this.color.copy( source.color );
  9945. this.map = source.map;
  9946. this.alphaMap = source.alphaMap;
  9947. this.size = source.size;
  9948. this.sizeAttenuation = source.sizeAttenuation;
  9949. this.fog = source.fog;
  9950. return this;
  9951. }
  9952. }
  9953. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  9954. const _ray = /*@__PURE__*/ new Ray();
  9955. const _sphere = /*@__PURE__*/ new Sphere();
  9956. const _position$2 = /*@__PURE__*/ new Vector3();
  9957. class Points extends Object3D {
  9958. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  9959. super();
  9960. this.isPoints = true;
  9961. this.type = 'Points';
  9962. this.geometry = geometry;
  9963. this.material = material;
  9964. this.updateMorphTargets();
  9965. }
  9966. copy( source, recursive ) {
  9967. super.copy( source, recursive );
  9968. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9969. this.geometry = source.geometry;
  9970. return this;
  9971. }
  9972. raycast( raycaster, intersects ) {
  9973. const geometry = this.geometry;
  9974. const matrixWorld = this.matrixWorld;
  9975. const threshold = raycaster.params.Points.threshold;
  9976. const drawRange = geometry.drawRange;
  9977. // Checking boundingSphere distance to ray
  9978. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9979. _sphere.copy( geometry.boundingSphere );
  9980. _sphere.applyMatrix4( matrixWorld );
  9981. _sphere.radius += threshold;
  9982. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  9983. //
  9984. _inverseMatrix.copy( matrixWorld ).invert();
  9985. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  9986. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9987. const localThresholdSq = localThreshold * localThreshold;
  9988. const index = geometry.index;
  9989. const attributes = geometry.attributes;
  9990. const positionAttribute = attributes.position;
  9991. if ( index !== null ) {
  9992. const start = Math.max( 0, drawRange.start );
  9993. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9994. for ( let i = start, il = end; i < il; i ++ ) {
  9995. const a = index.getX( i );
  9996. _position$2.fromBufferAttribute( positionAttribute, a );
  9997. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  9998. }
  9999. } else {
  10000. const start = Math.max( 0, drawRange.start );
  10001. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10002. for ( let i = start, l = end; i < l; i ++ ) {
  10003. _position$2.fromBufferAttribute( positionAttribute, i );
  10004. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10005. }
  10006. }
  10007. }
  10008. updateMorphTargets() {
  10009. const geometry = this.geometry;
  10010. const morphAttributes = geometry.morphAttributes;
  10011. const keys = Object.keys( morphAttributes );
  10012. if ( keys.length > 0 ) {
  10013. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10014. if ( morphAttribute !== undefined ) {
  10015. this.morphTargetInfluences = [];
  10016. this.morphTargetDictionary = {};
  10017. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10018. const name = morphAttribute[ m ].name || String( m );
  10019. this.morphTargetInfluences.push( 0 );
  10020. this.morphTargetDictionary[ name ] = m;
  10021. }
  10022. }
  10023. }
  10024. }
  10025. }
  10026. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10027. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10028. if ( rayPointDistanceSq < localThresholdSq ) {
  10029. const intersectPoint = new Vector3();
  10030. _ray.closestPointToPoint( point, intersectPoint );
  10031. intersectPoint.applyMatrix4( matrixWorld );
  10032. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10033. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10034. intersects.push( {
  10035. distance: distance,
  10036. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10037. point: intersectPoint,
  10038. index: index,
  10039. face: null,
  10040. object: object
  10041. } );
  10042. }
  10043. }
  10044. class Group extends Object3D {
  10045. constructor() {
  10046. super();
  10047. this.isGroup = true;
  10048. this.type = 'Group';
  10049. }
  10050. }
  10051. class VideoTexture extends Texture {
  10052. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10053. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10054. this.isVideoTexture = true;
  10055. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10056. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10057. this.generateMipmaps = false;
  10058. const scope = this;
  10059. function updateVideo() {
  10060. scope.needsUpdate = true;
  10061. video.requestVideoFrameCallback( updateVideo );
  10062. }
  10063. if ( 'requestVideoFrameCallback' in video ) {
  10064. video.requestVideoFrameCallback( updateVideo );
  10065. }
  10066. }
  10067. clone() {
  10068. return new this.constructor( this.image ).copy( this );
  10069. }
  10070. update() {
  10071. const video = this.image;
  10072. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10073. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10074. this.needsUpdate = true;
  10075. }
  10076. }
  10077. }
  10078. class FramebufferTexture extends Texture {
  10079. constructor( width, height ) {
  10080. super( { width, height } );
  10081. this.isFramebufferTexture = true;
  10082. this.magFilter = NearestFilter;
  10083. this.minFilter = NearestFilter;
  10084. this.generateMipmaps = false;
  10085. this.needsUpdate = true;
  10086. }
  10087. }
  10088. class CompressedTexture extends Texture {
  10089. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10090. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10091. this.isCompressedTexture = true;
  10092. this.image = { width: width, height: height };
  10093. this.mipmaps = mipmaps;
  10094. // no flipping for cube textures
  10095. // (also flipping doesn't work for compressed textures )
  10096. this.flipY = false;
  10097. // can't generate mipmaps for compressed textures
  10098. // mips must be embedded in DDS files
  10099. this.generateMipmaps = false;
  10100. }
  10101. }
  10102. class CompressedArrayTexture extends CompressedTexture {
  10103. constructor( mipmaps, width, height, depth, format, type ) {
  10104. super( mipmaps, width, height, format, type );
  10105. this.isCompressedArrayTexture = true;
  10106. this.image.depth = depth;
  10107. this.wrapR = ClampToEdgeWrapping;
  10108. this.layerUpdates = new Set();
  10109. }
  10110. addLayerUpdate( layerIndex ) {
  10111. this.layerUpdates.add( layerIndex );
  10112. }
  10113. clearLayerUpdates() {
  10114. this.layerUpdates.clear();
  10115. }
  10116. }
  10117. class CompressedCubeTexture extends CompressedTexture {
  10118. constructor( images, format, type ) {
  10119. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10120. this.isCompressedCubeTexture = true;
  10121. this.isCubeTexture = true;
  10122. this.image = images;
  10123. }
  10124. }
  10125. class CanvasTexture extends Texture {
  10126. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10127. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10128. this.isCanvasTexture = true;
  10129. this.needsUpdate = true;
  10130. }
  10131. }
  10132. class DepthTexture extends Texture {
  10133. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10134. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10135. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10136. }
  10137. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10138. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10139. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10140. this.isDepthTexture = true;
  10141. this.image = { width: width, height: height };
  10142. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10143. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10144. this.flipY = false;
  10145. this.generateMipmaps = false;
  10146. this.compareFunction = null;
  10147. }
  10148. copy( source ) {
  10149. super.copy( source );
  10150. this.compareFunction = source.compareFunction;
  10151. return this;
  10152. }
  10153. toJSON( meta ) {
  10154. const data = super.toJSON( meta );
  10155. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10156. return data;
  10157. }
  10158. }
  10159. /**
  10160. * Extensible curve object.
  10161. *
  10162. * Some common of curve methods:
  10163. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10164. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10165. * .getPoints(), .getSpacedPoints()
  10166. * .getLength()
  10167. * .updateArcLengths()
  10168. *
  10169. * This following curves inherit from THREE.Curve:
  10170. *
  10171. * -- 2D curves --
  10172. * THREE.ArcCurve
  10173. * THREE.CubicBezierCurve
  10174. * THREE.EllipseCurve
  10175. * THREE.LineCurve
  10176. * THREE.QuadraticBezierCurve
  10177. * THREE.SplineCurve
  10178. *
  10179. * -- 3D curves --
  10180. * THREE.CatmullRomCurve3
  10181. * THREE.CubicBezierCurve3
  10182. * THREE.LineCurve3
  10183. * THREE.QuadraticBezierCurve3
  10184. *
  10185. * A series of curves can be represented as a THREE.CurvePath.
  10186. *
  10187. **/
  10188. class Curve {
  10189. constructor() {
  10190. this.type = 'Curve';
  10191. this.arcLengthDivisions = 200;
  10192. }
  10193. // Virtual base class method to overwrite and implement in subclasses
  10194. // - t [0 .. 1]
  10195. getPoint( /* t, optionalTarget */ ) {
  10196. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10197. return null;
  10198. }
  10199. // Get point at relative position in curve according to arc length
  10200. // - u [0 .. 1]
  10201. getPointAt( u, optionalTarget ) {
  10202. const t = this.getUtoTmapping( u );
  10203. return this.getPoint( t, optionalTarget );
  10204. }
  10205. // Get sequence of points using getPoint( t )
  10206. getPoints( divisions = 5 ) {
  10207. const points = [];
  10208. for ( let d = 0; d <= divisions; d ++ ) {
  10209. points.push( this.getPoint( d / divisions ) );
  10210. }
  10211. return points;
  10212. }
  10213. // Get sequence of points using getPointAt( u )
  10214. getSpacedPoints( divisions = 5 ) {
  10215. const points = [];
  10216. for ( let d = 0; d <= divisions; d ++ ) {
  10217. points.push( this.getPointAt( d / divisions ) );
  10218. }
  10219. return points;
  10220. }
  10221. // Get total curve arc length
  10222. getLength() {
  10223. const lengths = this.getLengths();
  10224. return lengths[ lengths.length - 1 ];
  10225. }
  10226. // Get list of cumulative segment lengths
  10227. getLengths( divisions = this.arcLengthDivisions ) {
  10228. if ( this.cacheArcLengths &&
  10229. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10230. ! this.needsUpdate ) {
  10231. return this.cacheArcLengths;
  10232. }
  10233. this.needsUpdate = false;
  10234. const cache = [];
  10235. let current, last = this.getPoint( 0 );
  10236. let sum = 0;
  10237. cache.push( 0 );
  10238. for ( let p = 1; p <= divisions; p ++ ) {
  10239. current = this.getPoint( p / divisions );
  10240. sum += current.distanceTo( last );
  10241. cache.push( sum );
  10242. last = current;
  10243. }
  10244. this.cacheArcLengths = cache;
  10245. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10246. }
  10247. updateArcLengths() {
  10248. this.needsUpdate = true;
  10249. this.getLengths();
  10250. }
  10251. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10252. getUtoTmapping( u, distance ) {
  10253. const arcLengths = this.getLengths();
  10254. let i = 0;
  10255. const il = arcLengths.length;
  10256. let targetArcLength; // The targeted u distance value to get
  10257. if ( distance ) {
  10258. targetArcLength = distance;
  10259. } else {
  10260. targetArcLength = u * arcLengths[ il - 1 ];
  10261. }
  10262. // binary search for the index with largest value smaller than target u distance
  10263. let low = 0, high = il - 1, comparison;
  10264. while ( low <= high ) {
  10265. 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
  10266. comparison = arcLengths[ i ] - targetArcLength;
  10267. if ( comparison < 0 ) {
  10268. low = i + 1;
  10269. } else if ( comparison > 0 ) {
  10270. high = i - 1;
  10271. } else {
  10272. high = i;
  10273. break;
  10274. // DONE
  10275. }
  10276. }
  10277. i = high;
  10278. if ( arcLengths[ i ] === targetArcLength ) {
  10279. return i / ( il - 1 );
  10280. }
  10281. // we could get finer grain at lengths, or use simple interpolation between two points
  10282. const lengthBefore = arcLengths[ i ];
  10283. const lengthAfter = arcLengths[ i + 1 ];
  10284. const segmentLength = lengthAfter - lengthBefore;
  10285. // determine where we are between the 'before' and 'after' points
  10286. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10287. // add that fractional amount to t
  10288. const t = ( i + segmentFraction ) / ( il - 1 );
  10289. return t;
  10290. }
  10291. // Returns a unit vector tangent at t
  10292. // In case any sub curve does not implement its tangent derivation,
  10293. // 2 points a small delta apart will be used to find its gradient
  10294. // which seems to give a reasonable approximation
  10295. getTangent( t, optionalTarget ) {
  10296. const delta = 0.0001;
  10297. let t1 = t - delta;
  10298. let t2 = t + delta;
  10299. // Capping in case of danger
  10300. if ( t1 < 0 ) t1 = 0;
  10301. if ( t2 > 1 ) t2 = 1;
  10302. const pt1 = this.getPoint( t1 );
  10303. const pt2 = this.getPoint( t2 );
  10304. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10305. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10306. return tangent;
  10307. }
  10308. getTangentAt( u, optionalTarget ) {
  10309. const t = this.getUtoTmapping( u );
  10310. return this.getTangent( t, optionalTarget );
  10311. }
  10312. computeFrenetFrames( segments, closed ) {
  10313. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10314. const normal = new Vector3();
  10315. const tangents = [];
  10316. const normals = [];
  10317. const binormals = [];
  10318. const vec = new Vector3();
  10319. const mat = new Matrix4();
  10320. // compute the tangent vectors for each segment on the curve
  10321. for ( let i = 0; i <= segments; i ++ ) {
  10322. const u = i / segments;
  10323. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10324. }
  10325. // select an initial normal vector perpendicular to the first tangent vector,
  10326. // and in the direction of the minimum tangent xyz component
  10327. normals[ 0 ] = new Vector3();
  10328. binormals[ 0 ] = new Vector3();
  10329. let min = Number.MAX_VALUE;
  10330. const tx = Math.abs( tangents[ 0 ].x );
  10331. const ty = Math.abs( tangents[ 0 ].y );
  10332. const tz = Math.abs( tangents[ 0 ].z );
  10333. if ( tx <= min ) {
  10334. min = tx;
  10335. normal.set( 1, 0, 0 );
  10336. }
  10337. if ( ty <= min ) {
  10338. min = ty;
  10339. normal.set( 0, 1, 0 );
  10340. }
  10341. if ( tz <= min ) {
  10342. normal.set( 0, 0, 1 );
  10343. }
  10344. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10345. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10346. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10347. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10348. for ( let i = 1; i <= segments; i ++ ) {
  10349. normals[ i ] = normals[ i - 1 ].clone();
  10350. binormals[ i ] = binormals[ i - 1 ].clone();
  10351. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10352. if ( vec.length() > Number.EPSILON ) {
  10353. vec.normalize();
  10354. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10355. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10356. }
  10357. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10358. }
  10359. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10360. if ( closed === true ) {
  10361. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10362. theta /= segments;
  10363. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10364. theta = - theta;
  10365. }
  10366. for ( let i = 1; i <= segments; i ++ ) {
  10367. // twist a little...
  10368. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10369. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10370. }
  10371. }
  10372. return {
  10373. tangents: tangents,
  10374. normals: normals,
  10375. binormals: binormals
  10376. };
  10377. }
  10378. clone() {
  10379. return new this.constructor().copy( this );
  10380. }
  10381. copy( source ) {
  10382. this.arcLengthDivisions = source.arcLengthDivisions;
  10383. return this;
  10384. }
  10385. toJSON() {
  10386. const data = {
  10387. metadata: {
  10388. version: 4.6,
  10389. type: 'Curve',
  10390. generator: 'Curve.toJSON'
  10391. }
  10392. };
  10393. data.arcLengthDivisions = this.arcLengthDivisions;
  10394. data.type = this.type;
  10395. return data;
  10396. }
  10397. fromJSON( json ) {
  10398. this.arcLengthDivisions = json.arcLengthDivisions;
  10399. return this;
  10400. }
  10401. }
  10402. class EllipseCurve extends Curve {
  10403. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10404. super();
  10405. this.isEllipseCurve = true;
  10406. this.type = 'EllipseCurve';
  10407. this.aX = aX;
  10408. this.aY = aY;
  10409. this.xRadius = xRadius;
  10410. this.yRadius = yRadius;
  10411. this.aStartAngle = aStartAngle;
  10412. this.aEndAngle = aEndAngle;
  10413. this.aClockwise = aClockwise;
  10414. this.aRotation = aRotation;
  10415. }
  10416. getPoint( t, optionalTarget = new Vector2() ) {
  10417. const point = optionalTarget;
  10418. const twoPi = Math.PI * 2;
  10419. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10420. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10421. // ensures that deltaAngle is 0 .. 2 PI
  10422. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10423. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10424. if ( deltaAngle < Number.EPSILON ) {
  10425. if ( samePoints ) {
  10426. deltaAngle = 0;
  10427. } else {
  10428. deltaAngle = twoPi;
  10429. }
  10430. }
  10431. if ( this.aClockwise === true && ! samePoints ) {
  10432. if ( deltaAngle === twoPi ) {
  10433. deltaAngle = - twoPi;
  10434. } else {
  10435. deltaAngle = deltaAngle - twoPi;
  10436. }
  10437. }
  10438. const angle = this.aStartAngle + t * deltaAngle;
  10439. let x = this.aX + this.xRadius * Math.cos( angle );
  10440. let y = this.aY + this.yRadius * Math.sin( angle );
  10441. if ( this.aRotation !== 0 ) {
  10442. const cos = Math.cos( this.aRotation );
  10443. const sin = Math.sin( this.aRotation );
  10444. const tx = x - this.aX;
  10445. const ty = y - this.aY;
  10446. // Rotate the point about the center of the ellipse.
  10447. x = tx * cos - ty * sin + this.aX;
  10448. y = tx * sin + ty * cos + this.aY;
  10449. }
  10450. return point.set( x, y );
  10451. }
  10452. copy( source ) {
  10453. super.copy( source );
  10454. this.aX = source.aX;
  10455. this.aY = source.aY;
  10456. this.xRadius = source.xRadius;
  10457. this.yRadius = source.yRadius;
  10458. this.aStartAngle = source.aStartAngle;
  10459. this.aEndAngle = source.aEndAngle;
  10460. this.aClockwise = source.aClockwise;
  10461. this.aRotation = source.aRotation;
  10462. return this;
  10463. }
  10464. toJSON() {
  10465. const data = super.toJSON();
  10466. data.aX = this.aX;
  10467. data.aY = this.aY;
  10468. data.xRadius = this.xRadius;
  10469. data.yRadius = this.yRadius;
  10470. data.aStartAngle = this.aStartAngle;
  10471. data.aEndAngle = this.aEndAngle;
  10472. data.aClockwise = this.aClockwise;
  10473. data.aRotation = this.aRotation;
  10474. return data;
  10475. }
  10476. fromJSON( json ) {
  10477. super.fromJSON( json );
  10478. this.aX = json.aX;
  10479. this.aY = json.aY;
  10480. this.xRadius = json.xRadius;
  10481. this.yRadius = json.yRadius;
  10482. this.aStartAngle = json.aStartAngle;
  10483. this.aEndAngle = json.aEndAngle;
  10484. this.aClockwise = json.aClockwise;
  10485. this.aRotation = json.aRotation;
  10486. return this;
  10487. }
  10488. }
  10489. class ArcCurve extends EllipseCurve {
  10490. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10491. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10492. this.isArcCurve = true;
  10493. this.type = 'ArcCurve';
  10494. }
  10495. }
  10496. /**
  10497. * Centripetal CatmullRom Curve - which is useful for avoiding
  10498. * cusps and self-intersections in non-uniform catmull rom curves.
  10499. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10500. *
  10501. * curve.type accepts centripetal(default), chordal and catmullrom
  10502. * curve.tension is used for catmullrom which defaults to 0.5
  10503. */
  10504. /*
  10505. Based on an optimized c++ solution in
  10506. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10507. - http://ideone.com/NoEbVM
  10508. This CubicPoly class could be used for reusing some variables and calculations,
  10509. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10510. which can be placed in CurveUtils.
  10511. */
  10512. function CubicPoly() {
  10513. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10514. /*
  10515. * Compute coefficients for a cubic polynomial
  10516. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10517. * such that
  10518. * p(0) = x0, p(1) = x1
  10519. * and
  10520. * p'(0) = t0, p'(1) = t1.
  10521. */
  10522. function init( x0, x1, t0, t1 ) {
  10523. c0 = x0;
  10524. c1 = t0;
  10525. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10526. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10527. }
  10528. return {
  10529. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10530. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10531. },
  10532. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10533. // compute tangents when parameterized in [t1,t2]
  10534. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10535. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10536. // rescale tangents for parametrization in [0,1]
  10537. t1 *= dt1;
  10538. t2 *= dt1;
  10539. init( x1, x2, t1, t2 );
  10540. },
  10541. calc: function ( t ) {
  10542. const t2 = t * t;
  10543. const t3 = t2 * t;
  10544. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10545. }
  10546. };
  10547. }
  10548. //
  10549. const tmp = /*@__PURE__*/ new Vector3();
  10550. const px = /*@__PURE__*/ new CubicPoly();
  10551. const py = /*@__PURE__*/ new CubicPoly();
  10552. const pz = /*@__PURE__*/ new CubicPoly();
  10553. class CatmullRomCurve3 extends Curve {
  10554. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10555. super();
  10556. this.isCatmullRomCurve3 = true;
  10557. this.type = 'CatmullRomCurve3';
  10558. this.points = points;
  10559. this.closed = closed;
  10560. this.curveType = curveType;
  10561. this.tension = tension;
  10562. }
  10563. getPoint( t, optionalTarget = new Vector3() ) {
  10564. const point = optionalTarget;
  10565. const points = this.points;
  10566. const l = points.length;
  10567. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10568. let intPoint = Math.floor( p );
  10569. let weight = p - intPoint;
  10570. if ( this.closed ) {
  10571. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10572. } else if ( weight === 0 && intPoint === l - 1 ) {
  10573. intPoint = l - 2;
  10574. weight = 1;
  10575. }
  10576. let p0, p3; // 4 points (p1 & p2 defined below)
  10577. if ( this.closed || intPoint > 0 ) {
  10578. p0 = points[ ( intPoint - 1 ) % l ];
  10579. } else {
  10580. // extrapolate first point
  10581. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10582. p0 = tmp;
  10583. }
  10584. const p1 = points[ intPoint % l ];
  10585. const p2 = points[ ( intPoint + 1 ) % l ];
  10586. if ( this.closed || intPoint + 2 < l ) {
  10587. p3 = points[ ( intPoint + 2 ) % l ];
  10588. } else {
  10589. // extrapolate last point
  10590. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10591. p3 = tmp;
  10592. }
  10593. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10594. // init Centripetal / Chordal Catmull-Rom
  10595. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10596. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10597. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10598. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10599. // safety check for repeated points
  10600. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10601. if ( dt0 < 1e-4 ) dt0 = dt1;
  10602. if ( dt2 < 1e-4 ) dt2 = dt1;
  10603. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10604. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10605. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10606. } else if ( this.curveType === 'catmullrom' ) {
  10607. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10608. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10609. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10610. }
  10611. point.set(
  10612. px.calc( weight ),
  10613. py.calc( weight ),
  10614. pz.calc( weight )
  10615. );
  10616. return point;
  10617. }
  10618. copy( source ) {
  10619. super.copy( source );
  10620. this.points = [];
  10621. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10622. const point = source.points[ i ];
  10623. this.points.push( point.clone() );
  10624. }
  10625. this.closed = source.closed;
  10626. this.curveType = source.curveType;
  10627. this.tension = source.tension;
  10628. return this;
  10629. }
  10630. toJSON() {
  10631. const data = super.toJSON();
  10632. data.points = [];
  10633. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10634. const point = this.points[ i ];
  10635. data.points.push( point.toArray() );
  10636. }
  10637. data.closed = this.closed;
  10638. data.curveType = this.curveType;
  10639. data.tension = this.tension;
  10640. return data;
  10641. }
  10642. fromJSON( json ) {
  10643. super.fromJSON( json );
  10644. this.points = [];
  10645. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10646. const point = json.points[ i ];
  10647. this.points.push( new Vector3().fromArray( point ) );
  10648. }
  10649. this.closed = json.closed;
  10650. this.curveType = json.curveType;
  10651. this.tension = json.tension;
  10652. return this;
  10653. }
  10654. }
  10655. /**
  10656. * Bezier Curves formulas obtained from
  10657. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10658. */
  10659. function CatmullRom( t, p0, p1, p2, p3 ) {
  10660. const v0 = ( p2 - p0 ) * 0.5;
  10661. const v1 = ( p3 - p1 ) * 0.5;
  10662. const t2 = t * t;
  10663. const t3 = t * t2;
  10664. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10665. }
  10666. //
  10667. function QuadraticBezierP0( t, p ) {
  10668. const k = 1 - t;
  10669. return k * k * p;
  10670. }
  10671. function QuadraticBezierP1( t, p ) {
  10672. return 2 * ( 1 - t ) * t * p;
  10673. }
  10674. function QuadraticBezierP2( t, p ) {
  10675. return t * t * p;
  10676. }
  10677. function QuadraticBezier( t, p0, p1, p2 ) {
  10678. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10679. QuadraticBezierP2( t, p2 );
  10680. }
  10681. //
  10682. function CubicBezierP0( t, p ) {
  10683. const k = 1 - t;
  10684. return k * k * k * p;
  10685. }
  10686. function CubicBezierP1( t, p ) {
  10687. const k = 1 - t;
  10688. return 3 * k * k * t * p;
  10689. }
  10690. function CubicBezierP2( t, p ) {
  10691. return 3 * ( 1 - t ) * t * t * p;
  10692. }
  10693. function CubicBezierP3( t, p ) {
  10694. return t * t * t * p;
  10695. }
  10696. function CubicBezier( t, p0, p1, p2, p3 ) {
  10697. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10698. CubicBezierP3( t, p3 );
  10699. }
  10700. class CubicBezierCurve extends Curve {
  10701. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10702. super();
  10703. this.isCubicBezierCurve = true;
  10704. this.type = 'CubicBezierCurve';
  10705. this.v0 = v0;
  10706. this.v1 = v1;
  10707. this.v2 = v2;
  10708. this.v3 = v3;
  10709. }
  10710. getPoint( t, optionalTarget = new Vector2() ) {
  10711. const point = optionalTarget;
  10712. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10713. point.set(
  10714. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10715. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10716. );
  10717. return point;
  10718. }
  10719. copy( source ) {
  10720. super.copy( source );
  10721. this.v0.copy( source.v0 );
  10722. this.v1.copy( source.v1 );
  10723. this.v2.copy( source.v2 );
  10724. this.v3.copy( source.v3 );
  10725. return this;
  10726. }
  10727. toJSON() {
  10728. const data = super.toJSON();
  10729. data.v0 = this.v0.toArray();
  10730. data.v1 = this.v1.toArray();
  10731. data.v2 = this.v2.toArray();
  10732. data.v3 = this.v3.toArray();
  10733. return data;
  10734. }
  10735. fromJSON( json ) {
  10736. super.fromJSON( json );
  10737. this.v0.fromArray( json.v0 );
  10738. this.v1.fromArray( json.v1 );
  10739. this.v2.fromArray( json.v2 );
  10740. this.v3.fromArray( json.v3 );
  10741. return this;
  10742. }
  10743. }
  10744. class CubicBezierCurve3 extends Curve {
  10745. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10746. super();
  10747. this.isCubicBezierCurve3 = true;
  10748. this.type = 'CubicBezierCurve3';
  10749. this.v0 = v0;
  10750. this.v1 = v1;
  10751. this.v2 = v2;
  10752. this.v3 = v3;
  10753. }
  10754. getPoint( t, optionalTarget = new Vector3() ) {
  10755. const point = optionalTarget;
  10756. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10757. point.set(
  10758. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10759. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10760. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10761. );
  10762. return point;
  10763. }
  10764. copy( source ) {
  10765. super.copy( source );
  10766. this.v0.copy( source.v0 );
  10767. this.v1.copy( source.v1 );
  10768. this.v2.copy( source.v2 );
  10769. this.v3.copy( source.v3 );
  10770. return this;
  10771. }
  10772. toJSON() {
  10773. const data = super.toJSON();
  10774. data.v0 = this.v0.toArray();
  10775. data.v1 = this.v1.toArray();
  10776. data.v2 = this.v2.toArray();
  10777. data.v3 = this.v3.toArray();
  10778. return data;
  10779. }
  10780. fromJSON( json ) {
  10781. super.fromJSON( json );
  10782. this.v0.fromArray( json.v0 );
  10783. this.v1.fromArray( json.v1 );
  10784. this.v2.fromArray( json.v2 );
  10785. this.v3.fromArray( json.v3 );
  10786. return this;
  10787. }
  10788. }
  10789. class LineCurve extends Curve {
  10790. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  10791. super();
  10792. this.isLineCurve = true;
  10793. this.type = 'LineCurve';
  10794. this.v1 = v1;
  10795. this.v2 = v2;
  10796. }
  10797. getPoint( t, optionalTarget = new Vector2() ) {
  10798. const point = optionalTarget;
  10799. if ( t === 1 ) {
  10800. point.copy( this.v2 );
  10801. } else {
  10802. point.copy( this.v2 ).sub( this.v1 );
  10803. point.multiplyScalar( t ).add( this.v1 );
  10804. }
  10805. return point;
  10806. }
  10807. // Line curve is linear, so we can overwrite default getPointAt
  10808. getPointAt( u, optionalTarget ) {
  10809. return this.getPoint( u, optionalTarget );
  10810. }
  10811. getTangent( t, optionalTarget = new Vector2() ) {
  10812. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10813. }
  10814. getTangentAt( u, optionalTarget ) {
  10815. return this.getTangent( u, optionalTarget );
  10816. }
  10817. copy( source ) {
  10818. super.copy( source );
  10819. this.v1.copy( source.v1 );
  10820. this.v2.copy( source.v2 );
  10821. return this;
  10822. }
  10823. toJSON() {
  10824. const data = super.toJSON();
  10825. data.v1 = this.v1.toArray();
  10826. data.v2 = this.v2.toArray();
  10827. return data;
  10828. }
  10829. fromJSON( json ) {
  10830. super.fromJSON( json );
  10831. this.v1.fromArray( json.v1 );
  10832. this.v2.fromArray( json.v2 );
  10833. return this;
  10834. }
  10835. }
  10836. class LineCurve3 extends Curve {
  10837. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  10838. super();
  10839. this.isLineCurve3 = true;
  10840. this.type = 'LineCurve3';
  10841. this.v1 = v1;
  10842. this.v2 = v2;
  10843. }
  10844. getPoint( t, optionalTarget = new Vector3() ) {
  10845. const point = optionalTarget;
  10846. if ( t === 1 ) {
  10847. point.copy( this.v2 );
  10848. } else {
  10849. point.copy( this.v2 ).sub( this.v1 );
  10850. point.multiplyScalar( t ).add( this.v1 );
  10851. }
  10852. return point;
  10853. }
  10854. // Line curve is linear, so we can overwrite default getPointAt
  10855. getPointAt( u, optionalTarget ) {
  10856. return this.getPoint( u, optionalTarget );
  10857. }
  10858. getTangent( t, optionalTarget = new Vector3() ) {
  10859. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10860. }
  10861. getTangentAt( u, optionalTarget ) {
  10862. return this.getTangent( u, optionalTarget );
  10863. }
  10864. copy( source ) {
  10865. super.copy( source );
  10866. this.v1.copy( source.v1 );
  10867. this.v2.copy( source.v2 );
  10868. return this;
  10869. }
  10870. toJSON() {
  10871. const data = super.toJSON();
  10872. data.v1 = this.v1.toArray();
  10873. data.v2 = this.v2.toArray();
  10874. return data;
  10875. }
  10876. fromJSON( json ) {
  10877. super.fromJSON( json );
  10878. this.v1.fromArray( json.v1 );
  10879. this.v2.fromArray( json.v2 );
  10880. return this;
  10881. }
  10882. }
  10883. class QuadraticBezierCurve extends Curve {
  10884. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  10885. super();
  10886. this.isQuadraticBezierCurve = true;
  10887. this.type = 'QuadraticBezierCurve';
  10888. this.v0 = v0;
  10889. this.v1 = v1;
  10890. this.v2 = v2;
  10891. }
  10892. getPoint( t, optionalTarget = new Vector2() ) {
  10893. const point = optionalTarget;
  10894. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10895. point.set(
  10896. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10897. QuadraticBezier( t, v0.y, v1.y, v2.y )
  10898. );
  10899. return point;
  10900. }
  10901. copy( source ) {
  10902. super.copy( source );
  10903. this.v0.copy( source.v0 );
  10904. this.v1.copy( source.v1 );
  10905. this.v2.copy( source.v2 );
  10906. return this;
  10907. }
  10908. toJSON() {
  10909. const data = super.toJSON();
  10910. data.v0 = this.v0.toArray();
  10911. data.v1 = this.v1.toArray();
  10912. data.v2 = this.v2.toArray();
  10913. return data;
  10914. }
  10915. fromJSON( json ) {
  10916. super.fromJSON( json );
  10917. this.v0.fromArray( json.v0 );
  10918. this.v1.fromArray( json.v1 );
  10919. this.v2.fromArray( json.v2 );
  10920. return this;
  10921. }
  10922. }
  10923. class QuadraticBezierCurve3 extends Curve {
  10924. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  10925. super();
  10926. this.isQuadraticBezierCurve3 = true;
  10927. this.type = 'QuadraticBezierCurve3';
  10928. this.v0 = v0;
  10929. this.v1 = v1;
  10930. this.v2 = v2;
  10931. }
  10932. getPoint( t, optionalTarget = new Vector3() ) {
  10933. const point = optionalTarget;
  10934. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10935. point.set(
  10936. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10937. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  10938. QuadraticBezier( t, v0.z, v1.z, v2.z )
  10939. );
  10940. return point;
  10941. }
  10942. copy( source ) {
  10943. super.copy( source );
  10944. this.v0.copy( source.v0 );
  10945. this.v1.copy( source.v1 );
  10946. this.v2.copy( source.v2 );
  10947. return this;
  10948. }
  10949. toJSON() {
  10950. const data = super.toJSON();
  10951. data.v0 = this.v0.toArray();
  10952. data.v1 = this.v1.toArray();
  10953. data.v2 = this.v2.toArray();
  10954. return data;
  10955. }
  10956. fromJSON( json ) {
  10957. super.fromJSON( json );
  10958. this.v0.fromArray( json.v0 );
  10959. this.v1.fromArray( json.v1 );
  10960. this.v2.fromArray( json.v2 );
  10961. return this;
  10962. }
  10963. }
  10964. class SplineCurve extends Curve {
  10965. constructor( points = [] ) {
  10966. super();
  10967. this.isSplineCurve = true;
  10968. this.type = 'SplineCurve';
  10969. this.points = points;
  10970. }
  10971. getPoint( t, optionalTarget = new Vector2() ) {
  10972. const point = optionalTarget;
  10973. const points = this.points;
  10974. const p = ( points.length - 1 ) * t;
  10975. const intPoint = Math.floor( p );
  10976. const weight = p - intPoint;
  10977. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  10978. const p1 = points[ intPoint ];
  10979. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  10980. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  10981. point.set(
  10982. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  10983. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  10984. );
  10985. return point;
  10986. }
  10987. copy( source ) {
  10988. super.copy( source );
  10989. this.points = [];
  10990. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10991. const point = source.points[ i ];
  10992. this.points.push( point.clone() );
  10993. }
  10994. return this;
  10995. }
  10996. toJSON() {
  10997. const data = super.toJSON();
  10998. data.points = [];
  10999. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11000. const point = this.points[ i ];
  11001. data.points.push( point.toArray() );
  11002. }
  11003. return data;
  11004. }
  11005. fromJSON( json ) {
  11006. super.fromJSON( json );
  11007. this.points = [];
  11008. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11009. const point = json.points[ i ];
  11010. this.points.push( new Vector2().fromArray( point ) );
  11011. }
  11012. return this;
  11013. }
  11014. }
  11015. var Curves = /*#__PURE__*/Object.freeze({
  11016. __proto__: null,
  11017. ArcCurve: ArcCurve,
  11018. CatmullRomCurve3: CatmullRomCurve3,
  11019. CubicBezierCurve: CubicBezierCurve,
  11020. CubicBezierCurve3: CubicBezierCurve3,
  11021. EllipseCurve: EllipseCurve,
  11022. LineCurve: LineCurve,
  11023. LineCurve3: LineCurve3,
  11024. QuadraticBezierCurve: QuadraticBezierCurve,
  11025. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11026. SplineCurve: SplineCurve
  11027. });
  11028. /**************************************************************
  11029. * Curved Path - a curve path is simply a array of connected
  11030. * curves, but retains the api of a curve
  11031. **************************************************************/
  11032. class CurvePath extends Curve {
  11033. constructor() {
  11034. super();
  11035. this.type = 'CurvePath';
  11036. this.curves = [];
  11037. this.autoClose = false; // Automatically closes the path
  11038. }
  11039. add( curve ) {
  11040. this.curves.push( curve );
  11041. }
  11042. closePath() {
  11043. // Add a line curve if start and end of lines are not connected
  11044. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11045. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11046. if ( ! startPoint.equals( endPoint ) ) {
  11047. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11048. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11049. }
  11050. return this;
  11051. }
  11052. // To get accurate point with reference to
  11053. // entire path distance at time t,
  11054. // following has to be done:
  11055. // 1. Length of each sub path have to be known
  11056. // 2. Locate and identify type of curve
  11057. // 3. Get t for the curve
  11058. // 4. Return curve.getPointAt(t')
  11059. getPoint( t, optionalTarget ) {
  11060. const d = t * this.getLength();
  11061. const curveLengths = this.getCurveLengths();
  11062. let i = 0;
  11063. // To think about boundaries points.
  11064. while ( i < curveLengths.length ) {
  11065. if ( curveLengths[ i ] >= d ) {
  11066. const diff = curveLengths[ i ] - d;
  11067. const curve = this.curves[ i ];
  11068. const segmentLength = curve.getLength();
  11069. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11070. return curve.getPointAt( u, optionalTarget );
  11071. }
  11072. i ++;
  11073. }
  11074. return null;
  11075. // loop where sum != 0, sum > d , sum+1 <d
  11076. }
  11077. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11078. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11079. // getPoint() depends on getLength
  11080. getLength() {
  11081. const lens = this.getCurveLengths();
  11082. return lens[ lens.length - 1 ];
  11083. }
  11084. // cacheLengths must be recalculated.
  11085. updateArcLengths() {
  11086. this.needsUpdate = true;
  11087. this.cacheLengths = null;
  11088. this.getCurveLengths();
  11089. }
  11090. // Compute lengths and cache them
  11091. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11092. getCurveLengths() {
  11093. // We use cache values if curves and cache array are same length
  11094. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11095. return this.cacheLengths;
  11096. }
  11097. // Get length of sub-curve
  11098. // Push sums into cached array
  11099. const lengths = [];
  11100. let sums = 0;
  11101. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11102. sums += this.curves[ i ].getLength();
  11103. lengths.push( sums );
  11104. }
  11105. this.cacheLengths = lengths;
  11106. return lengths;
  11107. }
  11108. getSpacedPoints( divisions = 40 ) {
  11109. const points = [];
  11110. for ( let i = 0; i <= divisions; i ++ ) {
  11111. points.push( this.getPoint( i / divisions ) );
  11112. }
  11113. if ( this.autoClose ) {
  11114. points.push( points[ 0 ] );
  11115. }
  11116. return points;
  11117. }
  11118. getPoints( divisions = 12 ) {
  11119. const points = [];
  11120. let last;
  11121. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11122. const curve = curves[ i ];
  11123. const resolution = curve.isEllipseCurve ? divisions * 2
  11124. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11125. : curve.isSplineCurve ? divisions * curve.points.length
  11126. : divisions;
  11127. const pts = curve.getPoints( resolution );
  11128. for ( let j = 0; j < pts.length; j ++ ) {
  11129. const point = pts[ j ];
  11130. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11131. points.push( point );
  11132. last = point;
  11133. }
  11134. }
  11135. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11136. points.push( points[ 0 ] );
  11137. }
  11138. return points;
  11139. }
  11140. copy( source ) {
  11141. super.copy( source );
  11142. this.curves = [];
  11143. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11144. const curve = source.curves[ i ];
  11145. this.curves.push( curve.clone() );
  11146. }
  11147. this.autoClose = source.autoClose;
  11148. return this;
  11149. }
  11150. toJSON() {
  11151. const data = super.toJSON();
  11152. data.autoClose = this.autoClose;
  11153. data.curves = [];
  11154. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11155. const curve = this.curves[ i ];
  11156. data.curves.push( curve.toJSON() );
  11157. }
  11158. return data;
  11159. }
  11160. fromJSON( json ) {
  11161. super.fromJSON( json );
  11162. this.autoClose = json.autoClose;
  11163. this.curves = [];
  11164. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11165. const curve = json.curves[ i ];
  11166. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11167. }
  11168. return this;
  11169. }
  11170. }
  11171. class Path extends CurvePath {
  11172. constructor( points ) {
  11173. super();
  11174. this.type = 'Path';
  11175. this.currentPoint = new Vector2();
  11176. if ( points ) {
  11177. this.setFromPoints( points );
  11178. }
  11179. }
  11180. setFromPoints( points ) {
  11181. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11182. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11183. this.lineTo( points[ i ].x, points[ i ].y );
  11184. }
  11185. return this;
  11186. }
  11187. moveTo( x, y ) {
  11188. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11189. return this;
  11190. }
  11191. lineTo( x, y ) {
  11192. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11193. this.curves.push( curve );
  11194. this.currentPoint.set( x, y );
  11195. return this;
  11196. }
  11197. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11198. const curve = new QuadraticBezierCurve(
  11199. this.currentPoint.clone(),
  11200. new Vector2( aCPx, aCPy ),
  11201. new Vector2( aX, aY )
  11202. );
  11203. this.curves.push( curve );
  11204. this.currentPoint.set( aX, aY );
  11205. return this;
  11206. }
  11207. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11208. const curve = new CubicBezierCurve(
  11209. this.currentPoint.clone(),
  11210. new Vector2( aCP1x, aCP1y ),
  11211. new Vector2( aCP2x, aCP2y ),
  11212. new Vector2( aX, aY )
  11213. );
  11214. this.curves.push( curve );
  11215. this.currentPoint.set( aX, aY );
  11216. return this;
  11217. }
  11218. splineThru( pts /*Array of Vector*/ ) {
  11219. const npts = [ this.currentPoint.clone() ].concat( pts );
  11220. const curve = new SplineCurve( npts );
  11221. this.curves.push( curve );
  11222. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11223. return this;
  11224. }
  11225. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11226. const x0 = this.currentPoint.x;
  11227. const y0 = this.currentPoint.y;
  11228. this.absarc( aX + x0, aY + y0, aRadius,
  11229. aStartAngle, aEndAngle, aClockwise );
  11230. return this;
  11231. }
  11232. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11233. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11234. return this;
  11235. }
  11236. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11237. const x0 = this.currentPoint.x;
  11238. const y0 = this.currentPoint.y;
  11239. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11240. return this;
  11241. }
  11242. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11243. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11244. if ( this.curves.length > 0 ) {
  11245. // if a previous curve is present, attempt to join
  11246. const firstPoint = curve.getPoint( 0 );
  11247. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11248. this.lineTo( firstPoint.x, firstPoint.y );
  11249. }
  11250. }
  11251. this.curves.push( curve );
  11252. const lastPoint = curve.getPoint( 1 );
  11253. this.currentPoint.copy( lastPoint );
  11254. return this;
  11255. }
  11256. copy( source ) {
  11257. super.copy( source );
  11258. this.currentPoint.copy( source.currentPoint );
  11259. return this;
  11260. }
  11261. toJSON() {
  11262. const data = super.toJSON();
  11263. data.currentPoint = this.currentPoint.toArray();
  11264. return data;
  11265. }
  11266. fromJSON( json ) {
  11267. super.fromJSON( json );
  11268. this.currentPoint.fromArray( json.currentPoint );
  11269. return this;
  11270. }
  11271. }
  11272. class LatheGeometry extends BufferGeometry {
  11273. 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 ) {
  11274. super();
  11275. this.type = 'LatheGeometry';
  11276. this.parameters = {
  11277. points: points,
  11278. segments: segments,
  11279. phiStart: phiStart,
  11280. phiLength: phiLength
  11281. };
  11282. segments = Math.floor( segments );
  11283. // clamp phiLength so it's in range of [ 0, 2PI ]
  11284. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11285. // buffers
  11286. const indices = [];
  11287. const vertices = [];
  11288. const uvs = [];
  11289. const initNormals = [];
  11290. const normals = [];
  11291. // helper variables
  11292. const inverseSegments = 1.0 / segments;
  11293. const vertex = new Vector3();
  11294. const uv = new Vector2();
  11295. const normal = new Vector3();
  11296. const curNormal = new Vector3();
  11297. const prevNormal = new Vector3();
  11298. let dx = 0;
  11299. let dy = 0;
  11300. // pre-compute normals for initial "meridian"
  11301. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11302. switch ( j ) {
  11303. case 0: // special handling for 1st vertex on path
  11304. dx = points[ j + 1 ].x - points[ j ].x;
  11305. dy = points[ j + 1 ].y - points[ j ].y;
  11306. normal.x = dy * 1.0;
  11307. normal.y = - dx;
  11308. normal.z = dy * 0.0;
  11309. prevNormal.copy( normal );
  11310. normal.normalize();
  11311. initNormals.push( normal.x, normal.y, normal.z );
  11312. break;
  11313. case ( points.length - 1 ): // special handling for last Vertex on path
  11314. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11315. break;
  11316. default: // default handling for all vertices in between
  11317. dx = points[ j + 1 ].x - points[ j ].x;
  11318. dy = points[ j + 1 ].y - points[ j ].y;
  11319. normal.x = dy * 1.0;
  11320. normal.y = - dx;
  11321. normal.z = dy * 0.0;
  11322. curNormal.copy( normal );
  11323. normal.x += prevNormal.x;
  11324. normal.y += prevNormal.y;
  11325. normal.z += prevNormal.z;
  11326. normal.normalize();
  11327. initNormals.push( normal.x, normal.y, normal.z );
  11328. prevNormal.copy( curNormal );
  11329. }
  11330. }
  11331. // generate vertices, uvs and normals
  11332. for ( let i = 0; i <= segments; i ++ ) {
  11333. const phi = phiStart + i * inverseSegments * phiLength;
  11334. const sin = Math.sin( phi );
  11335. const cos = Math.cos( phi );
  11336. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11337. // vertex
  11338. vertex.x = points[ j ].x * sin;
  11339. vertex.y = points[ j ].y;
  11340. vertex.z = points[ j ].x * cos;
  11341. vertices.push( vertex.x, vertex.y, vertex.z );
  11342. // uv
  11343. uv.x = i / segments;
  11344. uv.y = j / ( points.length - 1 );
  11345. uvs.push( uv.x, uv.y );
  11346. // normal
  11347. const x = initNormals[ 3 * j + 0 ] * sin;
  11348. const y = initNormals[ 3 * j + 1 ];
  11349. const z = initNormals[ 3 * j + 0 ] * cos;
  11350. normals.push( x, y, z );
  11351. }
  11352. }
  11353. // indices
  11354. for ( let i = 0; i < segments; i ++ ) {
  11355. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11356. const base = j + i * points.length;
  11357. const a = base;
  11358. const b = base + points.length;
  11359. const c = base + points.length + 1;
  11360. const d = base + 1;
  11361. // faces
  11362. indices.push( a, b, d );
  11363. indices.push( c, d, b );
  11364. }
  11365. }
  11366. // build geometry
  11367. this.setIndex( indices );
  11368. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11369. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11370. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11371. }
  11372. copy( source ) {
  11373. super.copy( source );
  11374. this.parameters = Object.assign( {}, source.parameters );
  11375. return this;
  11376. }
  11377. static fromJSON( data ) {
  11378. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11379. }
  11380. }
  11381. class CapsuleGeometry extends LatheGeometry {
  11382. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11383. const path = new Path();
  11384. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11385. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11386. super( path.getPoints( capSegments ), radialSegments );
  11387. this.type = 'CapsuleGeometry';
  11388. this.parameters = {
  11389. radius: radius,
  11390. length: length,
  11391. capSegments: capSegments,
  11392. radialSegments: radialSegments,
  11393. };
  11394. }
  11395. static fromJSON( data ) {
  11396. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11397. }
  11398. }
  11399. class CircleGeometry extends BufferGeometry {
  11400. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11401. super();
  11402. this.type = 'CircleGeometry';
  11403. this.parameters = {
  11404. radius: radius,
  11405. segments: segments,
  11406. thetaStart: thetaStart,
  11407. thetaLength: thetaLength
  11408. };
  11409. segments = Math.max( 3, segments );
  11410. // buffers
  11411. const indices = [];
  11412. const vertices = [];
  11413. const normals = [];
  11414. const uvs = [];
  11415. // helper variables
  11416. const vertex = new Vector3();
  11417. const uv = new Vector2();
  11418. // center point
  11419. vertices.push( 0, 0, 0 );
  11420. normals.push( 0, 0, 1 );
  11421. uvs.push( 0.5, 0.5 );
  11422. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11423. const segment = thetaStart + s / segments * thetaLength;
  11424. // vertex
  11425. vertex.x = radius * Math.cos( segment );
  11426. vertex.y = radius * Math.sin( segment );
  11427. vertices.push( vertex.x, vertex.y, vertex.z );
  11428. // normal
  11429. normals.push( 0, 0, 1 );
  11430. // uvs
  11431. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11432. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11433. uvs.push( uv.x, uv.y );
  11434. }
  11435. // indices
  11436. for ( let i = 1; i <= segments; i ++ ) {
  11437. indices.push( i, i + 1, 0 );
  11438. }
  11439. // build geometry
  11440. this.setIndex( indices );
  11441. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11442. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11443. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11444. }
  11445. copy( source ) {
  11446. super.copy( source );
  11447. this.parameters = Object.assign( {}, source.parameters );
  11448. return this;
  11449. }
  11450. static fromJSON( data ) {
  11451. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11452. }
  11453. }
  11454. class CylinderGeometry extends BufferGeometry {
  11455. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11456. super();
  11457. this.type = 'CylinderGeometry';
  11458. this.parameters = {
  11459. radiusTop: radiusTop,
  11460. radiusBottom: radiusBottom,
  11461. height: height,
  11462. radialSegments: radialSegments,
  11463. heightSegments: heightSegments,
  11464. openEnded: openEnded,
  11465. thetaStart: thetaStart,
  11466. thetaLength: thetaLength
  11467. };
  11468. const scope = this;
  11469. radialSegments = Math.floor( radialSegments );
  11470. heightSegments = Math.floor( heightSegments );
  11471. // buffers
  11472. const indices = [];
  11473. const vertices = [];
  11474. const normals = [];
  11475. const uvs = [];
  11476. // helper variables
  11477. let index = 0;
  11478. const indexArray = [];
  11479. const halfHeight = height / 2;
  11480. let groupStart = 0;
  11481. // generate geometry
  11482. generateTorso();
  11483. if ( openEnded === false ) {
  11484. if ( radiusTop > 0 ) generateCap( true );
  11485. if ( radiusBottom > 0 ) generateCap( false );
  11486. }
  11487. // build geometry
  11488. this.setIndex( indices );
  11489. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11490. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11491. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11492. function generateTorso() {
  11493. const normal = new Vector3();
  11494. const vertex = new Vector3();
  11495. let groupCount = 0;
  11496. // this will be used to calculate the normal
  11497. const slope = ( radiusBottom - radiusTop ) / height;
  11498. // generate vertices, normals and uvs
  11499. for ( let y = 0; y <= heightSegments; y ++ ) {
  11500. const indexRow = [];
  11501. const v = y / heightSegments;
  11502. // calculate the radius of the current row
  11503. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11504. for ( let x = 0; x <= radialSegments; x ++ ) {
  11505. const u = x / radialSegments;
  11506. const theta = u * thetaLength + thetaStart;
  11507. const sinTheta = Math.sin( theta );
  11508. const cosTheta = Math.cos( theta );
  11509. // vertex
  11510. vertex.x = radius * sinTheta;
  11511. vertex.y = - v * height + halfHeight;
  11512. vertex.z = radius * cosTheta;
  11513. vertices.push( vertex.x, vertex.y, vertex.z );
  11514. // normal
  11515. normal.set( sinTheta, slope, cosTheta ).normalize();
  11516. normals.push( normal.x, normal.y, normal.z );
  11517. // uv
  11518. uvs.push( u, 1 - v );
  11519. // save index of vertex in respective row
  11520. indexRow.push( index ++ );
  11521. }
  11522. // now save vertices of the row in our index array
  11523. indexArray.push( indexRow );
  11524. }
  11525. // generate indices
  11526. for ( let x = 0; x < radialSegments; x ++ ) {
  11527. for ( let y = 0; y < heightSegments; y ++ ) {
  11528. // we use the index array to access the correct indices
  11529. const a = indexArray[ y ][ x ];
  11530. const b = indexArray[ y + 1 ][ x ];
  11531. const c = indexArray[ y + 1 ][ x + 1 ];
  11532. const d = indexArray[ y ][ x + 1 ];
  11533. // faces
  11534. indices.push( a, b, d );
  11535. indices.push( b, c, d );
  11536. // update group counter
  11537. groupCount += 6;
  11538. }
  11539. }
  11540. // add a group to the geometry. this will ensure multi material support
  11541. scope.addGroup( groupStart, groupCount, 0 );
  11542. // calculate new start value for groups
  11543. groupStart += groupCount;
  11544. }
  11545. function generateCap( top ) {
  11546. // save the index of the first center vertex
  11547. const centerIndexStart = index;
  11548. const uv = new Vector2();
  11549. const vertex = new Vector3();
  11550. let groupCount = 0;
  11551. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11552. const sign = ( top === true ) ? 1 : - 1;
  11553. // first we generate the center vertex data of the cap.
  11554. // because the geometry needs one set of uvs per face,
  11555. // we must generate a center vertex per face/segment
  11556. for ( let x = 1; x <= radialSegments; x ++ ) {
  11557. // vertex
  11558. vertices.push( 0, halfHeight * sign, 0 );
  11559. // normal
  11560. normals.push( 0, sign, 0 );
  11561. // uv
  11562. uvs.push( 0.5, 0.5 );
  11563. // increase index
  11564. index ++;
  11565. }
  11566. // save the index of the last center vertex
  11567. const centerIndexEnd = index;
  11568. // now we generate the surrounding vertices, normals and uvs
  11569. for ( let x = 0; x <= radialSegments; x ++ ) {
  11570. const u = x / radialSegments;
  11571. const theta = u * thetaLength + thetaStart;
  11572. const cosTheta = Math.cos( theta );
  11573. const sinTheta = Math.sin( theta );
  11574. // vertex
  11575. vertex.x = radius * sinTheta;
  11576. vertex.y = halfHeight * sign;
  11577. vertex.z = radius * cosTheta;
  11578. vertices.push( vertex.x, vertex.y, vertex.z );
  11579. // normal
  11580. normals.push( 0, sign, 0 );
  11581. // uv
  11582. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11583. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11584. uvs.push( uv.x, uv.y );
  11585. // increase index
  11586. index ++;
  11587. }
  11588. // generate indices
  11589. for ( let x = 0; x < radialSegments; x ++ ) {
  11590. const c = centerIndexStart + x;
  11591. const i = centerIndexEnd + x;
  11592. if ( top === true ) {
  11593. // face top
  11594. indices.push( i, i + 1, c );
  11595. } else {
  11596. // face bottom
  11597. indices.push( i + 1, i, c );
  11598. }
  11599. groupCount += 3;
  11600. }
  11601. // add a group to the geometry. this will ensure multi material support
  11602. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11603. // calculate new start value for groups
  11604. groupStart += groupCount;
  11605. }
  11606. }
  11607. copy( source ) {
  11608. super.copy( source );
  11609. this.parameters = Object.assign( {}, source.parameters );
  11610. return this;
  11611. }
  11612. static fromJSON( data ) {
  11613. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11614. }
  11615. }
  11616. class ConeGeometry extends CylinderGeometry {
  11617. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11618. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11619. this.type = 'ConeGeometry';
  11620. this.parameters = {
  11621. radius: radius,
  11622. height: height,
  11623. radialSegments: radialSegments,
  11624. heightSegments: heightSegments,
  11625. openEnded: openEnded,
  11626. thetaStart: thetaStart,
  11627. thetaLength: thetaLength
  11628. };
  11629. }
  11630. static fromJSON( data ) {
  11631. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11632. }
  11633. }
  11634. class PolyhedronGeometry extends BufferGeometry {
  11635. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11636. super();
  11637. this.type = 'PolyhedronGeometry';
  11638. this.parameters = {
  11639. vertices: vertices,
  11640. indices: indices,
  11641. radius: radius,
  11642. detail: detail
  11643. };
  11644. // default buffer data
  11645. const vertexBuffer = [];
  11646. const uvBuffer = [];
  11647. // the subdivision creates the vertex buffer data
  11648. subdivide( detail );
  11649. // all vertices should lie on a conceptual sphere with a given radius
  11650. applyRadius( radius );
  11651. // finally, create the uv data
  11652. generateUVs();
  11653. // build non-indexed geometry
  11654. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11655. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11656. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11657. if ( detail === 0 ) {
  11658. this.computeVertexNormals(); // flat normals
  11659. } else {
  11660. this.normalizeNormals(); // smooth normals
  11661. }
  11662. // helper functions
  11663. function subdivide( detail ) {
  11664. const a = new Vector3();
  11665. const b = new Vector3();
  11666. const c = new Vector3();
  11667. // iterate over all faces and apply a subdivision with the given detail value
  11668. for ( let i = 0; i < indices.length; i += 3 ) {
  11669. // get the vertices of the face
  11670. getVertexByIndex( indices[ i + 0 ], a );
  11671. getVertexByIndex( indices[ i + 1 ], b );
  11672. getVertexByIndex( indices[ i + 2 ], c );
  11673. // perform subdivision
  11674. subdivideFace( a, b, c, detail );
  11675. }
  11676. }
  11677. function subdivideFace( a, b, c, detail ) {
  11678. const cols = detail + 1;
  11679. // we use this multidimensional array as a data structure for creating the subdivision
  11680. const v = [];
  11681. // construct all of the vertices for this subdivision
  11682. for ( let i = 0; i <= cols; i ++ ) {
  11683. v[ i ] = [];
  11684. const aj = a.clone().lerp( c, i / cols );
  11685. const bj = b.clone().lerp( c, i / cols );
  11686. const rows = cols - i;
  11687. for ( let j = 0; j <= rows; j ++ ) {
  11688. if ( j === 0 && i === cols ) {
  11689. v[ i ][ j ] = aj;
  11690. } else {
  11691. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11692. }
  11693. }
  11694. }
  11695. // construct all of the faces
  11696. for ( let i = 0; i < cols; i ++ ) {
  11697. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11698. const k = Math.floor( j / 2 );
  11699. if ( j % 2 === 0 ) {
  11700. pushVertex( v[ i ][ k + 1 ] );
  11701. pushVertex( v[ i + 1 ][ k ] );
  11702. pushVertex( v[ i ][ k ] );
  11703. } else {
  11704. pushVertex( v[ i ][ k + 1 ] );
  11705. pushVertex( v[ i + 1 ][ k + 1 ] );
  11706. pushVertex( v[ i + 1 ][ k ] );
  11707. }
  11708. }
  11709. }
  11710. }
  11711. function applyRadius( radius ) {
  11712. const vertex = new Vector3();
  11713. // iterate over the entire buffer and apply the radius to each vertex
  11714. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11715. vertex.x = vertexBuffer[ i + 0 ];
  11716. vertex.y = vertexBuffer[ i + 1 ];
  11717. vertex.z = vertexBuffer[ i + 2 ];
  11718. vertex.normalize().multiplyScalar( radius );
  11719. vertexBuffer[ i + 0 ] = vertex.x;
  11720. vertexBuffer[ i + 1 ] = vertex.y;
  11721. vertexBuffer[ i + 2 ] = vertex.z;
  11722. }
  11723. }
  11724. function generateUVs() {
  11725. const vertex = new Vector3();
  11726. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11727. vertex.x = vertexBuffer[ i + 0 ];
  11728. vertex.y = vertexBuffer[ i + 1 ];
  11729. vertex.z = vertexBuffer[ i + 2 ];
  11730. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11731. const v = inclination( vertex ) / Math.PI + 0.5;
  11732. uvBuffer.push( u, 1 - v );
  11733. }
  11734. correctUVs();
  11735. correctSeam();
  11736. }
  11737. function correctSeam() {
  11738. // handle case when face straddles the seam, see #3269
  11739. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11740. // uv data of a single face
  11741. const x0 = uvBuffer[ i + 0 ];
  11742. const x1 = uvBuffer[ i + 2 ];
  11743. const x2 = uvBuffer[ i + 4 ];
  11744. const max = Math.max( x0, x1, x2 );
  11745. const min = Math.min( x0, x1, x2 );
  11746. // 0.9 is somewhat arbitrary
  11747. if ( max > 0.9 && min < 0.1 ) {
  11748. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11749. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11750. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11751. }
  11752. }
  11753. }
  11754. function pushVertex( vertex ) {
  11755. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11756. }
  11757. function getVertexByIndex( index, vertex ) {
  11758. const stride = index * 3;
  11759. vertex.x = vertices[ stride + 0 ];
  11760. vertex.y = vertices[ stride + 1 ];
  11761. vertex.z = vertices[ stride + 2 ];
  11762. }
  11763. function correctUVs() {
  11764. const a = new Vector3();
  11765. const b = new Vector3();
  11766. const c = new Vector3();
  11767. const centroid = new Vector3();
  11768. const uvA = new Vector2();
  11769. const uvB = new Vector2();
  11770. const uvC = new Vector2();
  11771. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  11772. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  11773. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  11774. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  11775. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  11776. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  11777. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  11778. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  11779. const azi = azimuth( centroid );
  11780. correctUV( uvA, j + 0, a, azi );
  11781. correctUV( uvB, j + 2, b, azi );
  11782. correctUV( uvC, j + 4, c, azi );
  11783. }
  11784. }
  11785. function correctUV( uv, stride, vector, azimuth ) {
  11786. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  11787. uvBuffer[ stride ] = uv.x - 1;
  11788. }
  11789. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  11790. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  11791. }
  11792. }
  11793. // Angle around the Y axis, counter-clockwise when looking from above.
  11794. function azimuth( vector ) {
  11795. return Math.atan2( vector.z, - vector.x );
  11796. }
  11797. // Angle above the XZ plane.
  11798. function inclination( vector ) {
  11799. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  11800. }
  11801. }
  11802. copy( source ) {
  11803. super.copy( source );
  11804. this.parameters = Object.assign( {}, source.parameters );
  11805. return this;
  11806. }
  11807. static fromJSON( data ) {
  11808. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  11809. }
  11810. }
  11811. class DodecahedronGeometry extends PolyhedronGeometry {
  11812. constructor( radius = 1, detail = 0 ) {
  11813. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  11814. const r = 1 / t;
  11815. const vertices = [
  11816. // (±1, ±1, ±1)
  11817. - 1, - 1, - 1, - 1, - 1, 1,
  11818. - 1, 1, - 1, - 1, 1, 1,
  11819. 1, - 1, - 1, 1, - 1, 1,
  11820. 1, 1, - 1, 1, 1, 1,
  11821. // (0, ±1/φ, ±φ)
  11822. 0, - r, - t, 0, - r, t,
  11823. 0, r, - t, 0, r, t,
  11824. // (±1/φ, ±φ, 0)
  11825. - r, - t, 0, - r, t, 0,
  11826. r, - t, 0, r, t, 0,
  11827. // (±φ, 0, ±1/φ)
  11828. - t, 0, - r, t, 0, - r,
  11829. - t, 0, r, t, 0, r
  11830. ];
  11831. const indices = [
  11832. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  11833. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  11834. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  11835. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  11836. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  11837. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  11838. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  11839. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  11840. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  11841. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  11842. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  11843. 1, 12, 14, 1, 14, 5, 1, 5, 9
  11844. ];
  11845. super( vertices, indices, radius, detail );
  11846. this.type = 'DodecahedronGeometry';
  11847. this.parameters = {
  11848. radius: radius,
  11849. detail: detail
  11850. };
  11851. }
  11852. static fromJSON( data ) {
  11853. return new DodecahedronGeometry( data.radius, data.detail );
  11854. }
  11855. }
  11856. const _v0 = /*@__PURE__*/ new Vector3();
  11857. const _v1$1 = /*@__PURE__*/ new Vector3();
  11858. const _normal$1 = /*@__PURE__*/ new Vector3();
  11859. const _triangle = /*@__PURE__*/ new Triangle();
  11860. class EdgesGeometry extends BufferGeometry {
  11861. constructor( geometry = null, thresholdAngle = 1 ) {
  11862. super();
  11863. this.type = 'EdgesGeometry';
  11864. this.parameters = {
  11865. geometry: geometry,
  11866. thresholdAngle: thresholdAngle
  11867. };
  11868. if ( geometry !== null ) {
  11869. const precisionPoints = 4;
  11870. const precision = Math.pow( 10, precisionPoints );
  11871. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  11872. const indexAttr = geometry.getIndex();
  11873. const positionAttr = geometry.getAttribute( 'position' );
  11874. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  11875. const indexArr = [ 0, 0, 0 ];
  11876. const vertKeys = [ 'a', 'b', 'c' ];
  11877. const hashes = new Array( 3 );
  11878. const edgeData = {};
  11879. const vertices = [];
  11880. for ( let i = 0; i < indexCount; i += 3 ) {
  11881. if ( indexAttr ) {
  11882. indexArr[ 0 ] = indexAttr.getX( i );
  11883. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  11884. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  11885. } else {
  11886. indexArr[ 0 ] = i;
  11887. indexArr[ 1 ] = i + 1;
  11888. indexArr[ 2 ] = i + 2;
  11889. }
  11890. const { a, b, c } = _triangle;
  11891. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  11892. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  11893. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  11894. _triangle.getNormal( _normal$1 );
  11895. // create hashes for the edge from the vertices
  11896. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  11897. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  11898. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  11899. // skip degenerate triangles
  11900. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  11901. continue;
  11902. }
  11903. // iterate over every edge
  11904. for ( let j = 0; j < 3; j ++ ) {
  11905. // get the first and next vertex making up the edge
  11906. const jNext = ( j + 1 ) % 3;
  11907. const vecHash0 = hashes[ j ];
  11908. const vecHash1 = hashes[ jNext ];
  11909. const v0 = _triangle[ vertKeys[ j ] ];
  11910. const v1 = _triangle[ vertKeys[ jNext ] ];
  11911. const hash = `${ vecHash0 }_${ vecHash1 }`;
  11912. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  11913. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  11914. // if we found a sibling edge add it into the vertex array if
  11915. // it meets the angle threshold and delete the edge from the map.
  11916. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  11917. vertices.push( v0.x, v0.y, v0.z );
  11918. vertices.push( v1.x, v1.y, v1.z );
  11919. }
  11920. edgeData[ reverseHash ] = null;
  11921. } else if ( ! ( hash in edgeData ) ) {
  11922. // if we've already got an edge here then skip adding a new one
  11923. edgeData[ hash ] = {
  11924. index0: indexArr[ j ],
  11925. index1: indexArr[ jNext ],
  11926. normal: _normal$1.clone(),
  11927. };
  11928. }
  11929. }
  11930. }
  11931. // iterate over all remaining, unmatched edges and add them to the vertex array
  11932. for ( const key in edgeData ) {
  11933. if ( edgeData[ key ] ) {
  11934. const { index0, index1 } = edgeData[ key ];
  11935. _v0.fromBufferAttribute( positionAttr, index0 );
  11936. _v1$1.fromBufferAttribute( positionAttr, index1 );
  11937. vertices.push( _v0.x, _v0.y, _v0.z );
  11938. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  11939. }
  11940. }
  11941. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11942. }
  11943. }
  11944. copy( source ) {
  11945. super.copy( source );
  11946. this.parameters = Object.assign( {}, source.parameters );
  11947. return this;
  11948. }
  11949. }
  11950. class Shape extends Path {
  11951. constructor( points ) {
  11952. super( points );
  11953. this.uuid = generateUUID();
  11954. this.type = 'Shape';
  11955. this.holes = [];
  11956. }
  11957. getPointsHoles( divisions ) {
  11958. const holesPts = [];
  11959. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11960. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  11961. }
  11962. return holesPts;
  11963. }
  11964. // get points of shape and holes (keypoints based on segments parameter)
  11965. extractPoints( divisions ) {
  11966. return {
  11967. shape: this.getPoints( divisions ),
  11968. holes: this.getPointsHoles( divisions )
  11969. };
  11970. }
  11971. copy( source ) {
  11972. super.copy( source );
  11973. this.holes = [];
  11974. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  11975. const hole = source.holes[ i ];
  11976. this.holes.push( hole.clone() );
  11977. }
  11978. return this;
  11979. }
  11980. toJSON() {
  11981. const data = super.toJSON();
  11982. data.uuid = this.uuid;
  11983. data.holes = [];
  11984. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11985. const hole = this.holes[ i ];
  11986. data.holes.push( hole.toJSON() );
  11987. }
  11988. return data;
  11989. }
  11990. fromJSON( json ) {
  11991. super.fromJSON( json );
  11992. this.uuid = json.uuid;
  11993. this.holes = [];
  11994. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  11995. const hole = json.holes[ i ];
  11996. this.holes.push( new Path().fromJSON( hole ) );
  11997. }
  11998. return this;
  11999. }
  12000. }
  12001. /**
  12002. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12003. */
  12004. const Earcut = {
  12005. triangulate: function ( data, holeIndices, dim = 2 ) {
  12006. const hasHoles = holeIndices && holeIndices.length;
  12007. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12008. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12009. const triangles = [];
  12010. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12011. let minX, minY, maxX, maxY, x, y, invSize;
  12012. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12013. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12014. if ( data.length > 80 * dim ) {
  12015. minX = maxX = data[ 0 ];
  12016. minY = maxY = data[ 1 ];
  12017. for ( let i = dim; i < outerLen; i += dim ) {
  12018. x = data[ i ];
  12019. y = data[ i + 1 ];
  12020. if ( x < minX ) minX = x;
  12021. if ( y < minY ) minY = y;
  12022. if ( x > maxX ) maxX = x;
  12023. if ( y > maxY ) maxY = y;
  12024. }
  12025. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12026. invSize = Math.max( maxX - minX, maxY - minY );
  12027. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12028. }
  12029. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12030. return triangles;
  12031. }
  12032. };
  12033. // create a circular doubly linked list from polygon points in the specified winding order
  12034. function linkedList( data, start, end, dim, clockwise ) {
  12035. let i, last;
  12036. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12037. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12038. } else {
  12039. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12040. }
  12041. if ( last && equals$1( last, last.next ) ) {
  12042. removeNode( last );
  12043. last = last.next;
  12044. }
  12045. return last;
  12046. }
  12047. // eliminate colinear or duplicate points
  12048. function filterPoints( start, end ) {
  12049. if ( ! start ) return start;
  12050. if ( ! end ) end = start;
  12051. let p = start,
  12052. again;
  12053. do {
  12054. again = false;
  12055. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12056. removeNode( p );
  12057. p = end = p.prev;
  12058. if ( p === p.next ) break;
  12059. again = true;
  12060. } else {
  12061. p = p.next;
  12062. }
  12063. } while ( again || p !== end );
  12064. return end;
  12065. }
  12066. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12067. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12068. if ( ! ear ) return;
  12069. // interlink polygon nodes in z-order
  12070. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12071. let stop = ear,
  12072. prev, next;
  12073. // iterate through ears, slicing them one by one
  12074. while ( ear.prev !== ear.next ) {
  12075. prev = ear.prev;
  12076. next = ear.next;
  12077. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12078. // cut off the triangle
  12079. triangles.push( prev.i / dim | 0 );
  12080. triangles.push( ear.i / dim | 0 );
  12081. triangles.push( next.i / dim | 0 );
  12082. removeNode( ear );
  12083. // skipping the next vertex leads to less sliver triangles
  12084. ear = next.next;
  12085. stop = next.next;
  12086. continue;
  12087. }
  12088. ear = next;
  12089. // if we looped through the whole remaining polygon and can't find any more ears
  12090. if ( ear === stop ) {
  12091. // try filtering points and slicing again
  12092. if ( ! pass ) {
  12093. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12094. // if this didn't work, try curing all small self-intersections locally
  12095. } else if ( pass === 1 ) {
  12096. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12097. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12098. // as a last resort, try splitting the remaining polygon into two
  12099. } else if ( pass === 2 ) {
  12100. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12101. }
  12102. break;
  12103. }
  12104. }
  12105. }
  12106. // check whether a polygon node forms a valid ear with adjacent nodes
  12107. function isEar( ear ) {
  12108. const a = ear.prev,
  12109. b = ear,
  12110. c = ear.next;
  12111. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12112. // now make sure we don't have other points inside the potential ear
  12113. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12114. // triangle bbox; min & max are calculated like this for speed
  12115. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12116. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12117. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12118. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12119. let p = c.next;
  12120. while ( p !== a ) {
  12121. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12122. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12123. area( p.prev, p, p.next ) >= 0 ) return false;
  12124. p = p.next;
  12125. }
  12126. return true;
  12127. }
  12128. function isEarHashed( ear, minX, minY, invSize ) {
  12129. const a = ear.prev,
  12130. b = ear,
  12131. c = ear.next;
  12132. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12133. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12134. // triangle bbox; min & max are calculated like this for speed
  12135. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12136. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12137. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12138. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12139. // z-order range for the current triangle bbox;
  12140. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12141. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12142. let p = ear.prevZ,
  12143. n = ear.nextZ;
  12144. // look for points inside the triangle in both directions
  12145. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12146. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12147. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12148. p = p.prevZ;
  12149. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12150. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12151. n = n.nextZ;
  12152. }
  12153. // look for remaining points in decreasing z-order
  12154. while ( p && p.z >= minZ ) {
  12155. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12156. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12157. p = p.prevZ;
  12158. }
  12159. // look for remaining points in increasing z-order
  12160. while ( n && n.z <= maxZ ) {
  12161. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12162. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12163. n = n.nextZ;
  12164. }
  12165. return true;
  12166. }
  12167. // go through all polygon nodes and cure small local self-intersections
  12168. function cureLocalIntersections( start, triangles, dim ) {
  12169. let p = start;
  12170. do {
  12171. const a = p.prev,
  12172. b = p.next.next;
  12173. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12174. triangles.push( a.i / dim | 0 );
  12175. triangles.push( p.i / dim | 0 );
  12176. triangles.push( b.i / dim | 0 );
  12177. // remove two nodes involved
  12178. removeNode( p );
  12179. removeNode( p.next );
  12180. p = start = b;
  12181. }
  12182. p = p.next;
  12183. } while ( p !== start );
  12184. return filterPoints( p );
  12185. }
  12186. // try splitting polygon into two and triangulate them independently
  12187. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12188. // look for a valid diagonal that divides the polygon into two
  12189. let a = start;
  12190. do {
  12191. let b = a.next.next;
  12192. while ( b !== a.prev ) {
  12193. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12194. // split the polygon in two by the diagonal
  12195. let c = splitPolygon( a, b );
  12196. // filter colinear points around the cuts
  12197. a = filterPoints( a, a.next );
  12198. c = filterPoints( c, c.next );
  12199. // run earcut on each half
  12200. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12201. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12202. return;
  12203. }
  12204. b = b.next;
  12205. }
  12206. a = a.next;
  12207. } while ( a !== start );
  12208. }
  12209. // link every hole into the outer loop, producing a single-ring polygon without holes
  12210. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12211. const queue = [];
  12212. let i, len, start, end, list;
  12213. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12214. start = holeIndices[ i ] * dim;
  12215. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12216. list = linkedList( data, start, end, dim, false );
  12217. if ( list === list.next ) list.steiner = true;
  12218. queue.push( getLeftmost( list ) );
  12219. }
  12220. queue.sort( compareX );
  12221. // process holes from left to right
  12222. for ( i = 0; i < queue.length; i ++ ) {
  12223. outerNode = eliminateHole( queue[ i ], outerNode );
  12224. }
  12225. return outerNode;
  12226. }
  12227. function compareX( a, b ) {
  12228. return a.x - b.x;
  12229. }
  12230. // find a bridge between vertices that connects hole with an outer ring and link it
  12231. function eliminateHole( hole, outerNode ) {
  12232. const bridge = findHoleBridge( hole, outerNode );
  12233. if ( ! bridge ) {
  12234. return outerNode;
  12235. }
  12236. const bridgeReverse = splitPolygon( bridge, hole );
  12237. // filter collinear points around the cuts
  12238. filterPoints( bridgeReverse, bridgeReverse.next );
  12239. return filterPoints( bridge, bridge.next );
  12240. }
  12241. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12242. function findHoleBridge( hole, outerNode ) {
  12243. let p = outerNode,
  12244. qx = - Infinity,
  12245. m;
  12246. const hx = hole.x, hy = hole.y;
  12247. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12248. // segment's endpoint with lesser x will be potential connection point
  12249. do {
  12250. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12251. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12252. if ( x <= hx && x > qx ) {
  12253. qx = x;
  12254. m = p.x < p.next.x ? p : p.next;
  12255. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12256. }
  12257. }
  12258. p = p.next;
  12259. } while ( p !== outerNode );
  12260. if ( ! m ) return null;
  12261. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12262. // if there are no points found, we have a valid connection;
  12263. // otherwise choose the point of the minimum angle with the ray as connection point
  12264. const stop = m,
  12265. mx = m.x,
  12266. my = m.y;
  12267. let tanMin = Infinity, tan;
  12268. p = m;
  12269. do {
  12270. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12271. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12272. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12273. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12274. m = p;
  12275. tanMin = tan;
  12276. }
  12277. }
  12278. p = p.next;
  12279. } while ( p !== stop );
  12280. return m;
  12281. }
  12282. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12283. function sectorContainsSector( m, p ) {
  12284. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12285. }
  12286. // interlink polygon nodes in z-order
  12287. function indexCurve( start, minX, minY, invSize ) {
  12288. let p = start;
  12289. do {
  12290. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12291. p.prevZ = p.prev;
  12292. p.nextZ = p.next;
  12293. p = p.next;
  12294. } while ( p !== start );
  12295. p.prevZ.nextZ = null;
  12296. p.prevZ = null;
  12297. sortLinked( p );
  12298. }
  12299. // Simon Tatham's linked list merge sort algorithm
  12300. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12301. function sortLinked( list ) {
  12302. let i, p, q, e, tail, numMerges, pSize, qSize,
  12303. inSize = 1;
  12304. do {
  12305. p = list;
  12306. list = null;
  12307. tail = null;
  12308. numMerges = 0;
  12309. while ( p ) {
  12310. numMerges ++;
  12311. q = p;
  12312. pSize = 0;
  12313. for ( i = 0; i < inSize; i ++ ) {
  12314. pSize ++;
  12315. q = q.nextZ;
  12316. if ( ! q ) break;
  12317. }
  12318. qSize = inSize;
  12319. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12320. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12321. e = p;
  12322. p = p.nextZ;
  12323. pSize --;
  12324. } else {
  12325. e = q;
  12326. q = q.nextZ;
  12327. qSize --;
  12328. }
  12329. if ( tail ) tail.nextZ = e;
  12330. else list = e;
  12331. e.prevZ = tail;
  12332. tail = e;
  12333. }
  12334. p = q;
  12335. }
  12336. tail.nextZ = null;
  12337. inSize *= 2;
  12338. } while ( numMerges > 1 );
  12339. return list;
  12340. }
  12341. // z-order of a point given coords and inverse of the longer side of data bbox
  12342. function zOrder( x, y, minX, minY, invSize ) {
  12343. // coords are transformed into non-negative 15-bit integer range
  12344. x = ( x - minX ) * invSize | 0;
  12345. y = ( y - minY ) * invSize | 0;
  12346. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12347. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12348. x = ( x | ( x << 2 ) ) & 0x33333333;
  12349. x = ( x | ( x << 1 ) ) & 0x55555555;
  12350. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12351. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12352. y = ( y | ( y << 2 ) ) & 0x33333333;
  12353. y = ( y | ( y << 1 ) ) & 0x55555555;
  12354. return x | ( y << 1 );
  12355. }
  12356. // find the leftmost node of a polygon ring
  12357. function getLeftmost( start ) {
  12358. let p = start,
  12359. leftmost = start;
  12360. do {
  12361. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12362. p = p.next;
  12363. } while ( p !== start );
  12364. return leftmost;
  12365. }
  12366. // check if a point lies within a convex triangle
  12367. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12368. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12369. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12370. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12371. }
  12372. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12373. function isValidDiagonal( a, b ) {
  12374. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12375. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12376. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12377. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12378. }
  12379. // signed area of a triangle
  12380. function area( p, q, r ) {
  12381. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12382. }
  12383. // check if two points are equal
  12384. function equals$1( p1, p2 ) {
  12385. return p1.x === p2.x && p1.y === p2.y;
  12386. }
  12387. // check if two segments intersect
  12388. function intersects( p1, q1, p2, q2 ) {
  12389. const o1 = sign$1( area( p1, q1, p2 ) );
  12390. const o2 = sign$1( area( p1, q1, q2 ) );
  12391. const o3 = sign$1( area( p2, q2, p1 ) );
  12392. const o4 = sign$1( area( p2, q2, q1 ) );
  12393. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12394. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12395. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12396. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12397. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12398. return false;
  12399. }
  12400. // for collinear points p, q, r, check if point q lies on segment pr
  12401. function onSegment( p, q, r ) {
  12402. 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 );
  12403. }
  12404. function sign$1( num ) {
  12405. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12406. }
  12407. // check if a polygon diagonal intersects any polygon segments
  12408. function intersectsPolygon( a, b ) {
  12409. let p = a;
  12410. do {
  12411. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12412. intersects( p, p.next, a, b ) ) return true;
  12413. p = p.next;
  12414. } while ( p !== a );
  12415. return false;
  12416. }
  12417. // check if a polygon diagonal is locally inside the polygon
  12418. function locallyInside( a, b ) {
  12419. return area( a.prev, a, a.next ) < 0 ?
  12420. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12421. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12422. }
  12423. // check if the middle point of a polygon diagonal is inside the polygon
  12424. function middleInside( a, b ) {
  12425. let p = a,
  12426. inside = false;
  12427. const px = ( a.x + b.x ) / 2,
  12428. py = ( a.y + b.y ) / 2;
  12429. do {
  12430. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12431. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12432. inside = ! inside;
  12433. p = p.next;
  12434. } while ( p !== a );
  12435. return inside;
  12436. }
  12437. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12438. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12439. function splitPolygon( a, b ) {
  12440. const a2 = new Node$1( a.i, a.x, a.y ),
  12441. b2 = new Node$1( b.i, b.x, b.y ),
  12442. an = a.next,
  12443. bp = b.prev;
  12444. a.next = b;
  12445. b.prev = a;
  12446. a2.next = an;
  12447. an.prev = a2;
  12448. b2.next = a2;
  12449. a2.prev = b2;
  12450. bp.next = b2;
  12451. b2.prev = bp;
  12452. return b2;
  12453. }
  12454. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12455. function insertNode( i, x, y, last ) {
  12456. const p = new Node$1( i, x, y );
  12457. if ( ! last ) {
  12458. p.prev = p;
  12459. p.next = p;
  12460. } else {
  12461. p.next = last.next;
  12462. p.prev = last;
  12463. last.next.prev = p;
  12464. last.next = p;
  12465. }
  12466. return p;
  12467. }
  12468. function removeNode( p ) {
  12469. p.next.prev = p.prev;
  12470. p.prev.next = p.next;
  12471. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12472. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12473. }
  12474. function Node$1( i, x, y ) {
  12475. // vertex index in coordinates array
  12476. this.i = i;
  12477. // vertex coordinates
  12478. this.x = x;
  12479. this.y = y;
  12480. // previous and next vertex nodes in a polygon ring
  12481. this.prev = null;
  12482. this.next = null;
  12483. // z-order curve value
  12484. this.z = 0;
  12485. // previous and next nodes in z-order
  12486. this.prevZ = null;
  12487. this.nextZ = null;
  12488. // indicates whether this is a steiner point
  12489. this.steiner = false;
  12490. }
  12491. function signedArea( data, start, end, dim ) {
  12492. let sum = 0;
  12493. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12494. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12495. j = i;
  12496. }
  12497. return sum;
  12498. }
  12499. class ShapeUtils {
  12500. // calculate area of the contour polygon
  12501. static area( contour ) {
  12502. const n = contour.length;
  12503. let a = 0.0;
  12504. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12505. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12506. }
  12507. return a * 0.5;
  12508. }
  12509. static isClockWise( pts ) {
  12510. return ShapeUtils.area( pts ) < 0;
  12511. }
  12512. static triangulateShape( contour, holes ) {
  12513. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12514. const holeIndices = []; // array of hole indices
  12515. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12516. removeDupEndPts( contour );
  12517. addContour( vertices, contour );
  12518. //
  12519. let holeIndex = contour.length;
  12520. holes.forEach( removeDupEndPts );
  12521. for ( let i = 0; i < holes.length; i ++ ) {
  12522. holeIndices.push( holeIndex );
  12523. holeIndex += holes[ i ].length;
  12524. addContour( vertices, holes[ i ] );
  12525. }
  12526. //
  12527. const triangles = Earcut.triangulate( vertices, holeIndices );
  12528. //
  12529. for ( let i = 0; i < triangles.length; i += 3 ) {
  12530. faces.push( triangles.slice( i, i + 3 ) );
  12531. }
  12532. return faces;
  12533. }
  12534. }
  12535. function removeDupEndPts( points ) {
  12536. const l = points.length;
  12537. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12538. points.pop();
  12539. }
  12540. }
  12541. function addContour( vertices, contour ) {
  12542. for ( let i = 0; i < contour.length; i ++ ) {
  12543. vertices.push( contour[ i ].x );
  12544. vertices.push( contour[ i ].y );
  12545. }
  12546. }
  12547. /**
  12548. * Creates extruded geometry from a path shape.
  12549. *
  12550. * parameters = {
  12551. *
  12552. * curveSegments: <int>, // number of points on the curves
  12553. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12554. * depth: <float>, // Depth to extrude the shape
  12555. *
  12556. * bevelEnabled: <bool>, // turn on bevel
  12557. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12558. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12559. * bevelOffset: <float>, // how far from shape outline does bevel start
  12560. * bevelSegments: <int>, // number of bevel layers
  12561. *
  12562. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12563. *
  12564. * UVGenerator: <Object> // object that provides UV generator functions
  12565. *
  12566. * }
  12567. */
  12568. class ExtrudeGeometry extends BufferGeometry {
  12569. 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 = {} ) {
  12570. super();
  12571. this.type = 'ExtrudeGeometry';
  12572. this.parameters = {
  12573. shapes: shapes,
  12574. options: options
  12575. };
  12576. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12577. const scope = this;
  12578. const verticesArray = [];
  12579. const uvArray = [];
  12580. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12581. const shape = shapes[ i ];
  12582. addShape( shape );
  12583. }
  12584. // build geometry
  12585. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12586. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12587. this.computeVertexNormals();
  12588. // functions
  12589. function addShape( shape ) {
  12590. const placeholder = [];
  12591. // options
  12592. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12593. const steps = options.steps !== undefined ? options.steps : 1;
  12594. const depth = options.depth !== undefined ? options.depth : 1;
  12595. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12596. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12597. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12598. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12599. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12600. const extrudePath = options.extrudePath;
  12601. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12602. //
  12603. let extrudePts, extrudeByPath = false;
  12604. let splineTube, binormal, normal, position2;
  12605. if ( extrudePath ) {
  12606. extrudePts = extrudePath.getSpacedPoints( steps );
  12607. extrudeByPath = true;
  12608. bevelEnabled = false; // bevels not supported for path extrusion
  12609. // SETUP TNB variables
  12610. // TODO1 - have a .isClosed in spline?
  12611. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12612. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12613. binormal = new Vector3();
  12614. normal = new Vector3();
  12615. position2 = new Vector3();
  12616. }
  12617. // Safeguards if bevels are not enabled
  12618. if ( ! bevelEnabled ) {
  12619. bevelSegments = 0;
  12620. bevelThickness = 0;
  12621. bevelSize = 0;
  12622. bevelOffset = 0;
  12623. }
  12624. // Variables initialization
  12625. const shapePoints = shape.extractPoints( curveSegments );
  12626. let vertices = shapePoints.shape;
  12627. const holes = shapePoints.holes;
  12628. const reverse = ! ShapeUtils.isClockWise( vertices );
  12629. if ( reverse ) {
  12630. vertices = vertices.reverse();
  12631. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12632. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12633. const ahole = holes[ h ];
  12634. if ( ShapeUtils.isClockWise( ahole ) ) {
  12635. holes[ h ] = ahole.reverse();
  12636. }
  12637. }
  12638. }
  12639. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12640. /* Vertices */
  12641. const contour = vertices; // vertices has all points but contour has only points of circumference
  12642. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12643. const ahole = holes[ h ];
  12644. vertices = vertices.concat( ahole );
  12645. }
  12646. function scalePt2( pt, vec, size ) {
  12647. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12648. return pt.clone().addScaledVector( vec, size );
  12649. }
  12650. const vlen = vertices.length, flen = faces.length;
  12651. // Find directions for point movement
  12652. function getBevelVec( inPt, inPrev, inNext ) {
  12653. // computes for inPt the corresponding point inPt' on a new contour
  12654. // shifted by 1 unit (length of normalized vector) to the left
  12655. // if we walk along contour clockwise, this new contour is outside the old one
  12656. //
  12657. // inPt' is the intersection of the two lines parallel to the two
  12658. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12659. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12660. // good reading for geometry algorithms (here: line-line intersection)
  12661. // http://geomalgorithms.com/a05-_intersect-1.html
  12662. const v_prev_x = inPt.x - inPrev.x,
  12663. v_prev_y = inPt.y - inPrev.y;
  12664. const v_next_x = inNext.x - inPt.x,
  12665. v_next_y = inNext.y - inPt.y;
  12666. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12667. // check for collinear edges
  12668. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12669. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12670. // not collinear
  12671. // length of vectors for normalizing
  12672. const v_prev_len = Math.sqrt( v_prev_lensq );
  12673. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12674. // shift adjacent points by unit vectors to the left
  12675. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12676. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12677. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12678. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12679. // scaling factor for v_prev to intersection point
  12680. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12681. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12682. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12683. // vector from inPt to intersection point
  12684. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12685. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12686. // Don't normalize!, otherwise sharp corners become ugly
  12687. // but prevent crazy spikes
  12688. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12689. if ( v_trans_lensq <= 2 ) {
  12690. return new Vector2( v_trans_x, v_trans_y );
  12691. } else {
  12692. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12693. }
  12694. } else {
  12695. // handle special case of collinear edges
  12696. let direction_eq = false; // assumes: opposite
  12697. if ( v_prev_x > Number.EPSILON ) {
  12698. if ( v_next_x > Number.EPSILON ) {
  12699. direction_eq = true;
  12700. }
  12701. } else {
  12702. if ( v_prev_x < - Number.EPSILON ) {
  12703. if ( v_next_x < - Number.EPSILON ) {
  12704. direction_eq = true;
  12705. }
  12706. } else {
  12707. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12708. direction_eq = true;
  12709. }
  12710. }
  12711. }
  12712. if ( direction_eq ) {
  12713. // console.log("Warning: lines are a straight sequence");
  12714. v_trans_x = - v_prev_y;
  12715. v_trans_y = v_prev_x;
  12716. shrink_by = Math.sqrt( v_prev_lensq );
  12717. } else {
  12718. // console.log("Warning: lines are a straight spike");
  12719. v_trans_x = v_prev_x;
  12720. v_trans_y = v_prev_y;
  12721. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12722. }
  12723. }
  12724. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12725. }
  12726. const contourMovements = [];
  12727. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12728. if ( j === il ) j = 0;
  12729. if ( k === il ) k = 0;
  12730. // (j)---(i)---(k)
  12731. // console.log('i,j,k', i, j , k)
  12732. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12733. }
  12734. const holesMovements = [];
  12735. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12736. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12737. const ahole = holes[ h ];
  12738. oneHoleMovements = [];
  12739. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12740. if ( j === il ) j = 0;
  12741. if ( k === il ) k = 0;
  12742. // (j)---(i)---(k)
  12743. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12744. }
  12745. holesMovements.push( oneHoleMovements );
  12746. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12747. }
  12748. // Loop bevelSegments, 1 for the front, 1 for the back
  12749. for ( let b = 0; b < bevelSegments; b ++ ) {
  12750. //for ( b = bevelSegments; b > 0; b -- ) {
  12751. const t = b / bevelSegments;
  12752. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12753. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12754. // contract shape
  12755. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12756. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12757. v( vert.x, vert.y, - z );
  12758. }
  12759. // expand holes
  12760. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12761. const ahole = holes[ h ];
  12762. oneHoleMovements = holesMovements[ h ];
  12763. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12764. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12765. v( vert.x, vert.y, - z );
  12766. }
  12767. }
  12768. }
  12769. const bs = bevelSize + bevelOffset;
  12770. // Back facing vertices
  12771. for ( let i = 0; i < vlen; i ++ ) {
  12772. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12773. if ( ! extrudeByPath ) {
  12774. v( vert.x, vert.y, 0 );
  12775. } else {
  12776. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  12777. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  12778. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  12779. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  12780. v( position2.x, position2.y, position2.z );
  12781. }
  12782. }
  12783. // Add stepped vertices...
  12784. // Including front facing vertices
  12785. for ( let s = 1; s <= steps; s ++ ) {
  12786. for ( let i = 0; i < vlen; i ++ ) {
  12787. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12788. if ( ! extrudeByPath ) {
  12789. v( vert.x, vert.y, depth / steps * s );
  12790. } else {
  12791. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  12792. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  12793. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  12794. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  12795. v( position2.x, position2.y, position2.z );
  12796. }
  12797. }
  12798. }
  12799. // Add bevel segments planes
  12800. //for ( b = 1; b <= bevelSegments; b ++ ) {
  12801. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  12802. const t = b / bevelSegments;
  12803. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12804. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12805. // contract shape
  12806. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12807. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12808. v( vert.x, vert.y, depth + z );
  12809. }
  12810. // expand holes
  12811. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12812. const ahole = holes[ h ];
  12813. oneHoleMovements = holesMovements[ h ];
  12814. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12815. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12816. if ( ! extrudeByPath ) {
  12817. v( vert.x, vert.y, depth + z );
  12818. } else {
  12819. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  12820. }
  12821. }
  12822. }
  12823. }
  12824. /* Faces */
  12825. // Top and bottom faces
  12826. buildLidFaces();
  12827. // Sides faces
  12828. buildSideFaces();
  12829. ///// Internal functions
  12830. function buildLidFaces() {
  12831. const start = verticesArray.length / 3;
  12832. if ( bevelEnabled ) {
  12833. let layer = 0; // steps + 1
  12834. let offset = vlen * layer;
  12835. // Bottom faces
  12836. for ( let i = 0; i < flen; i ++ ) {
  12837. const face = faces[ i ];
  12838. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  12839. }
  12840. layer = steps + bevelSegments * 2;
  12841. offset = vlen * layer;
  12842. // Top faces
  12843. for ( let i = 0; i < flen; i ++ ) {
  12844. const face = faces[ i ];
  12845. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  12846. }
  12847. } else {
  12848. // Bottom faces
  12849. for ( let i = 0; i < flen; i ++ ) {
  12850. const face = faces[ i ];
  12851. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  12852. }
  12853. // Top faces
  12854. for ( let i = 0; i < flen; i ++ ) {
  12855. const face = faces[ i ];
  12856. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  12857. }
  12858. }
  12859. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  12860. }
  12861. // Create faces for the z-sides of the shape
  12862. function buildSideFaces() {
  12863. const start = verticesArray.length / 3;
  12864. let layeroffset = 0;
  12865. sidewalls( contour, layeroffset );
  12866. layeroffset += contour.length;
  12867. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12868. const ahole = holes[ h ];
  12869. sidewalls( ahole, layeroffset );
  12870. //, true
  12871. layeroffset += ahole.length;
  12872. }
  12873. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  12874. }
  12875. function sidewalls( contour, layeroffset ) {
  12876. let i = contour.length;
  12877. while ( -- i >= 0 ) {
  12878. const j = i;
  12879. let k = i - 1;
  12880. if ( k < 0 ) k = contour.length - 1;
  12881. //console.log('b', i,j, i-1, k,vertices.length);
  12882. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  12883. const slen1 = vlen * s;
  12884. const slen2 = vlen * ( s + 1 );
  12885. const a = layeroffset + j + slen1,
  12886. b = layeroffset + k + slen1,
  12887. c = layeroffset + k + slen2,
  12888. d = layeroffset + j + slen2;
  12889. f4( a, b, c, d );
  12890. }
  12891. }
  12892. }
  12893. function v( x, y, z ) {
  12894. placeholder.push( x );
  12895. placeholder.push( y );
  12896. placeholder.push( z );
  12897. }
  12898. function f3( a, b, c ) {
  12899. addVertex( a );
  12900. addVertex( b );
  12901. addVertex( c );
  12902. const nextIndex = verticesArray.length / 3;
  12903. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12904. addUV( uvs[ 0 ] );
  12905. addUV( uvs[ 1 ] );
  12906. addUV( uvs[ 2 ] );
  12907. }
  12908. function f4( a, b, c, d ) {
  12909. addVertex( a );
  12910. addVertex( b );
  12911. addVertex( d );
  12912. addVertex( b );
  12913. addVertex( c );
  12914. addVertex( d );
  12915. const nextIndex = verticesArray.length / 3;
  12916. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12917. addUV( uvs[ 0 ] );
  12918. addUV( uvs[ 1 ] );
  12919. addUV( uvs[ 3 ] );
  12920. addUV( uvs[ 1 ] );
  12921. addUV( uvs[ 2 ] );
  12922. addUV( uvs[ 3 ] );
  12923. }
  12924. function addVertex( index ) {
  12925. verticesArray.push( placeholder[ index * 3 + 0 ] );
  12926. verticesArray.push( placeholder[ index * 3 + 1 ] );
  12927. verticesArray.push( placeholder[ index * 3 + 2 ] );
  12928. }
  12929. function addUV( vector2 ) {
  12930. uvArray.push( vector2.x );
  12931. uvArray.push( vector2.y );
  12932. }
  12933. }
  12934. }
  12935. copy( source ) {
  12936. super.copy( source );
  12937. this.parameters = Object.assign( {}, source.parameters );
  12938. return this;
  12939. }
  12940. toJSON() {
  12941. const data = super.toJSON();
  12942. const shapes = this.parameters.shapes;
  12943. const options = this.parameters.options;
  12944. return toJSON$1( shapes, options, data );
  12945. }
  12946. static fromJSON( data, shapes ) {
  12947. const geometryShapes = [];
  12948. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  12949. const shape = shapes[ data.shapes[ j ] ];
  12950. geometryShapes.push( shape );
  12951. }
  12952. const extrudePath = data.options.extrudePath;
  12953. if ( extrudePath !== undefined ) {
  12954. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  12955. }
  12956. return new ExtrudeGeometry( geometryShapes, data.options );
  12957. }
  12958. }
  12959. const WorldUVGenerator = {
  12960. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  12961. const a_x = vertices[ indexA * 3 ];
  12962. const a_y = vertices[ indexA * 3 + 1 ];
  12963. const b_x = vertices[ indexB * 3 ];
  12964. const b_y = vertices[ indexB * 3 + 1 ];
  12965. const c_x = vertices[ indexC * 3 ];
  12966. const c_y = vertices[ indexC * 3 + 1 ];
  12967. return [
  12968. new Vector2( a_x, a_y ),
  12969. new Vector2( b_x, b_y ),
  12970. new Vector2( c_x, c_y )
  12971. ];
  12972. },
  12973. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  12974. const a_x = vertices[ indexA * 3 ];
  12975. const a_y = vertices[ indexA * 3 + 1 ];
  12976. const a_z = vertices[ indexA * 3 + 2 ];
  12977. const b_x = vertices[ indexB * 3 ];
  12978. const b_y = vertices[ indexB * 3 + 1 ];
  12979. const b_z = vertices[ indexB * 3 + 2 ];
  12980. const c_x = vertices[ indexC * 3 ];
  12981. const c_y = vertices[ indexC * 3 + 1 ];
  12982. const c_z = vertices[ indexC * 3 + 2 ];
  12983. const d_x = vertices[ indexD * 3 ];
  12984. const d_y = vertices[ indexD * 3 + 1 ];
  12985. const d_z = vertices[ indexD * 3 + 2 ];
  12986. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  12987. return [
  12988. new Vector2( a_x, 1 - a_z ),
  12989. new Vector2( b_x, 1 - b_z ),
  12990. new Vector2( c_x, 1 - c_z ),
  12991. new Vector2( d_x, 1 - d_z )
  12992. ];
  12993. } else {
  12994. return [
  12995. new Vector2( a_y, 1 - a_z ),
  12996. new Vector2( b_y, 1 - b_z ),
  12997. new Vector2( c_y, 1 - c_z ),
  12998. new Vector2( d_y, 1 - d_z )
  12999. ];
  13000. }
  13001. }
  13002. };
  13003. function toJSON$1( shapes, options, data ) {
  13004. data.shapes = [];
  13005. if ( Array.isArray( shapes ) ) {
  13006. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13007. const shape = shapes[ i ];
  13008. data.shapes.push( shape.uuid );
  13009. }
  13010. } else {
  13011. data.shapes.push( shapes.uuid );
  13012. }
  13013. data.options = Object.assign( {}, options );
  13014. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13015. return data;
  13016. }
  13017. class IcosahedronGeometry extends PolyhedronGeometry {
  13018. constructor( radius = 1, detail = 0 ) {
  13019. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13020. const vertices = [
  13021. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13022. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13023. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13024. ];
  13025. const indices = [
  13026. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13027. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13028. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13029. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13030. ];
  13031. super( vertices, indices, radius, detail );
  13032. this.type = 'IcosahedronGeometry';
  13033. this.parameters = {
  13034. radius: radius,
  13035. detail: detail
  13036. };
  13037. }
  13038. static fromJSON( data ) {
  13039. return new IcosahedronGeometry( data.radius, data.detail );
  13040. }
  13041. }
  13042. class OctahedronGeometry extends PolyhedronGeometry {
  13043. constructor( radius = 1, detail = 0 ) {
  13044. const vertices = [
  13045. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13046. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13047. ];
  13048. const indices = [
  13049. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13050. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13051. 1, 3, 4, 1, 4, 2
  13052. ];
  13053. super( vertices, indices, radius, detail );
  13054. this.type = 'OctahedronGeometry';
  13055. this.parameters = {
  13056. radius: radius,
  13057. detail: detail
  13058. };
  13059. }
  13060. static fromJSON( data ) {
  13061. return new OctahedronGeometry( data.radius, data.detail );
  13062. }
  13063. }
  13064. class PlaneGeometry extends BufferGeometry {
  13065. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13066. super();
  13067. this.type = 'PlaneGeometry';
  13068. this.parameters = {
  13069. width: width,
  13070. height: height,
  13071. widthSegments: widthSegments,
  13072. heightSegments: heightSegments
  13073. };
  13074. const width_half = width / 2;
  13075. const height_half = height / 2;
  13076. const gridX = Math.floor( widthSegments );
  13077. const gridY = Math.floor( heightSegments );
  13078. const gridX1 = gridX + 1;
  13079. const gridY1 = gridY + 1;
  13080. const segment_width = width / gridX;
  13081. const segment_height = height / gridY;
  13082. //
  13083. const indices = [];
  13084. const vertices = [];
  13085. const normals = [];
  13086. const uvs = [];
  13087. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13088. const y = iy * segment_height - height_half;
  13089. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13090. const x = ix * segment_width - width_half;
  13091. vertices.push( x, - y, 0 );
  13092. normals.push( 0, 0, 1 );
  13093. uvs.push( ix / gridX );
  13094. uvs.push( 1 - ( iy / gridY ) );
  13095. }
  13096. }
  13097. for ( let iy = 0; iy < gridY; iy ++ ) {
  13098. for ( let ix = 0; ix < gridX; ix ++ ) {
  13099. const a = ix + gridX1 * iy;
  13100. const b = ix + gridX1 * ( iy + 1 );
  13101. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13102. const d = ( ix + 1 ) + gridX1 * iy;
  13103. indices.push( a, b, d );
  13104. indices.push( b, c, d );
  13105. }
  13106. }
  13107. this.setIndex( indices );
  13108. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13109. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13110. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13111. }
  13112. copy( source ) {
  13113. super.copy( source );
  13114. this.parameters = Object.assign( {}, source.parameters );
  13115. return this;
  13116. }
  13117. static fromJSON( data ) {
  13118. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13119. }
  13120. }
  13121. class RingGeometry extends BufferGeometry {
  13122. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13123. super();
  13124. this.type = 'RingGeometry';
  13125. this.parameters = {
  13126. innerRadius: innerRadius,
  13127. outerRadius: outerRadius,
  13128. thetaSegments: thetaSegments,
  13129. phiSegments: phiSegments,
  13130. thetaStart: thetaStart,
  13131. thetaLength: thetaLength
  13132. };
  13133. thetaSegments = Math.max( 3, thetaSegments );
  13134. phiSegments = Math.max( 1, phiSegments );
  13135. // buffers
  13136. const indices = [];
  13137. const vertices = [];
  13138. const normals = [];
  13139. const uvs = [];
  13140. // some helper variables
  13141. let radius = innerRadius;
  13142. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13143. const vertex = new Vector3();
  13144. const uv = new Vector2();
  13145. // generate vertices, normals and uvs
  13146. for ( let j = 0; j <= phiSegments; j ++ ) {
  13147. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13148. // values are generate from the inside of the ring to the outside
  13149. const segment = thetaStart + i / thetaSegments * thetaLength;
  13150. // vertex
  13151. vertex.x = radius * Math.cos( segment );
  13152. vertex.y = radius * Math.sin( segment );
  13153. vertices.push( vertex.x, vertex.y, vertex.z );
  13154. // normal
  13155. normals.push( 0, 0, 1 );
  13156. // uv
  13157. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13158. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13159. uvs.push( uv.x, uv.y );
  13160. }
  13161. // increase the radius for next row of vertices
  13162. radius += radiusStep;
  13163. }
  13164. // indices
  13165. for ( let j = 0; j < phiSegments; j ++ ) {
  13166. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13167. for ( let i = 0; i < thetaSegments; i ++ ) {
  13168. const segment = i + thetaSegmentLevel;
  13169. const a = segment;
  13170. const b = segment + thetaSegments + 1;
  13171. const c = segment + thetaSegments + 2;
  13172. const d = segment + 1;
  13173. // faces
  13174. indices.push( a, b, d );
  13175. indices.push( b, c, d );
  13176. }
  13177. }
  13178. // build geometry
  13179. this.setIndex( indices );
  13180. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13181. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13182. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13183. }
  13184. copy( source ) {
  13185. super.copy( source );
  13186. this.parameters = Object.assign( {}, source.parameters );
  13187. return this;
  13188. }
  13189. static fromJSON( data ) {
  13190. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13191. }
  13192. }
  13193. class ShapeGeometry extends BufferGeometry {
  13194. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13195. super();
  13196. this.type = 'ShapeGeometry';
  13197. this.parameters = {
  13198. shapes: shapes,
  13199. curveSegments: curveSegments
  13200. };
  13201. // buffers
  13202. const indices = [];
  13203. const vertices = [];
  13204. const normals = [];
  13205. const uvs = [];
  13206. // helper variables
  13207. let groupStart = 0;
  13208. let groupCount = 0;
  13209. // allow single and array values for "shapes" parameter
  13210. if ( Array.isArray( shapes ) === false ) {
  13211. addShape( shapes );
  13212. } else {
  13213. for ( let i = 0; i < shapes.length; i ++ ) {
  13214. addShape( shapes[ i ] );
  13215. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13216. groupStart += groupCount;
  13217. groupCount = 0;
  13218. }
  13219. }
  13220. // build geometry
  13221. this.setIndex( indices );
  13222. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13223. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13224. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13225. // helper functions
  13226. function addShape( shape ) {
  13227. const indexOffset = vertices.length / 3;
  13228. const points = shape.extractPoints( curveSegments );
  13229. let shapeVertices = points.shape;
  13230. const shapeHoles = points.holes;
  13231. // check direction of vertices
  13232. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13233. shapeVertices = shapeVertices.reverse();
  13234. }
  13235. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13236. const shapeHole = shapeHoles[ i ];
  13237. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13238. shapeHoles[ i ] = shapeHole.reverse();
  13239. }
  13240. }
  13241. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13242. // join vertices of inner and outer paths to a single array
  13243. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13244. const shapeHole = shapeHoles[ i ];
  13245. shapeVertices = shapeVertices.concat( shapeHole );
  13246. }
  13247. // vertices, normals, uvs
  13248. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13249. const vertex = shapeVertices[ i ];
  13250. vertices.push( vertex.x, vertex.y, 0 );
  13251. normals.push( 0, 0, 1 );
  13252. uvs.push( vertex.x, vertex.y ); // world uvs
  13253. }
  13254. // indices
  13255. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13256. const face = faces[ i ];
  13257. const a = face[ 0 ] + indexOffset;
  13258. const b = face[ 1 ] + indexOffset;
  13259. const c = face[ 2 ] + indexOffset;
  13260. indices.push( a, b, c );
  13261. groupCount += 3;
  13262. }
  13263. }
  13264. }
  13265. copy( source ) {
  13266. super.copy( source );
  13267. this.parameters = Object.assign( {}, source.parameters );
  13268. return this;
  13269. }
  13270. toJSON() {
  13271. const data = super.toJSON();
  13272. const shapes = this.parameters.shapes;
  13273. return toJSON( shapes, data );
  13274. }
  13275. static fromJSON( data, shapes ) {
  13276. const geometryShapes = [];
  13277. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13278. const shape = shapes[ data.shapes[ j ] ];
  13279. geometryShapes.push( shape );
  13280. }
  13281. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13282. }
  13283. }
  13284. function toJSON( shapes, data ) {
  13285. data.shapes = [];
  13286. if ( Array.isArray( shapes ) ) {
  13287. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13288. const shape = shapes[ i ];
  13289. data.shapes.push( shape.uuid );
  13290. }
  13291. } else {
  13292. data.shapes.push( shapes.uuid );
  13293. }
  13294. return data;
  13295. }
  13296. class SphereGeometry extends BufferGeometry {
  13297. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13298. super();
  13299. this.type = 'SphereGeometry';
  13300. this.parameters = {
  13301. radius: radius,
  13302. widthSegments: widthSegments,
  13303. heightSegments: heightSegments,
  13304. phiStart: phiStart,
  13305. phiLength: phiLength,
  13306. thetaStart: thetaStart,
  13307. thetaLength: thetaLength
  13308. };
  13309. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13310. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13311. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13312. let index = 0;
  13313. const grid = [];
  13314. const vertex = new Vector3();
  13315. const normal = new Vector3();
  13316. // buffers
  13317. const indices = [];
  13318. const vertices = [];
  13319. const normals = [];
  13320. const uvs = [];
  13321. // generate vertices, normals and uvs
  13322. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13323. const verticesRow = [];
  13324. const v = iy / heightSegments;
  13325. // special case for the poles
  13326. let uOffset = 0;
  13327. if ( iy === 0 && thetaStart === 0 ) {
  13328. uOffset = 0.5 / widthSegments;
  13329. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13330. uOffset = - 0.5 / widthSegments;
  13331. }
  13332. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13333. const u = ix / widthSegments;
  13334. // vertex
  13335. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13336. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13337. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13338. vertices.push( vertex.x, vertex.y, vertex.z );
  13339. // normal
  13340. normal.copy( vertex ).normalize();
  13341. normals.push( normal.x, normal.y, normal.z );
  13342. // uv
  13343. uvs.push( u + uOffset, 1 - v );
  13344. verticesRow.push( index ++ );
  13345. }
  13346. grid.push( verticesRow );
  13347. }
  13348. // indices
  13349. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13350. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13351. const a = grid[ iy ][ ix + 1 ];
  13352. const b = grid[ iy ][ ix ];
  13353. const c = grid[ iy + 1 ][ ix ];
  13354. const d = grid[ iy + 1 ][ ix + 1 ];
  13355. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13356. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13357. }
  13358. }
  13359. // build geometry
  13360. this.setIndex( indices );
  13361. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13362. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13363. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13364. }
  13365. copy( source ) {
  13366. super.copy( source );
  13367. this.parameters = Object.assign( {}, source.parameters );
  13368. return this;
  13369. }
  13370. static fromJSON( data ) {
  13371. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13372. }
  13373. }
  13374. class TetrahedronGeometry extends PolyhedronGeometry {
  13375. constructor( radius = 1, detail = 0 ) {
  13376. const vertices = [
  13377. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13378. ];
  13379. const indices = [
  13380. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13381. ];
  13382. super( vertices, indices, radius, detail );
  13383. this.type = 'TetrahedronGeometry';
  13384. this.parameters = {
  13385. radius: radius,
  13386. detail: detail
  13387. };
  13388. }
  13389. static fromJSON( data ) {
  13390. return new TetrahedronGeometry( data.radius, data.detail );
  13391. }
  13392. }
  13393. class TorusGeometry extends BufferGeometry {
  13394. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13395. super();
  13396. this.type = 'TorusGeometry';
  13397. this.parameters = {
  13398. radius: radius,
  13399. tube: tube,
  13400. radialSegments: radialSegments,
  13401. tubularSegments: tubularSegments,
  13402. arc: arc
  13403. };
  13404. radialSegments = Math.floor( radialSegments );
  13405. tubularSegments = Math.floor( tubularSegments );
  13406. // buffers
  13407. const indices = [];
  13408. const vertices = [];
  13409. const normals = [];
  13410. const uvs = [];
  13411. // helper variables
  13412. const center = new Vector3();
  13413. const vertex = new Vector3();
  13414. const normal = new Vector3();
  13415. // generate vertices, normals and uvs
  13416. for ( let j = 0; j <= radialSegments; j ++ ) {
  13417. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13418. const u = i / tubularSegments * arc;
  13419. const v = j / radialSegments * Math.PI * 2;
  13420. // vertex
  13421. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13422. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13423. vertex.z = tube * Math.sin( v );
  13424. vertices.push( vertex.x, vertex.y, vertex.z );
  13425. // normal
  13426. center.x = radius * Math.cos( u );
  13427. center.y = radius * Math.sin( u );
  13428. normal.subVectors( vertex, center ).normalize();
  13429. normals.push( normal.x, normal.y, normal.z );
  13430. // uv
  13431. uvs.push( i / tubularSegments );
  13432. uvs.push( j / radialSegments );
  13433. }
  13434. }
  13435. // generate indices
  13436. for ( let j = 1; j <= radialSegments; j ++ ) {
  13437. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13438. // indices
  13439. const a = ( tubularSegments + 1 ) * j + i - 1;
  13440. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13441. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13442. const d = ( tubularSegments + 1 ) * j + i;
  13443. // faces
  13444. indices.push( a, b, d );
  13445. indices.push( b, c, d );
  13446. }
  13447. }
  13448. // build geometry
  13449. this.setIndex( indices );
  13450. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13451. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13452. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13453. }
  13454. copy( source ) {
  13455. super.copy( source );
  13456. this.parameters = Object.assign( {}, source.parameters );
  13457. return this;
  13458. }
  13459. static fromJSON( data ) {
  13460. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13461. }
  13462. }
  13463. class TorusKnotGeometry extends BufferGeometry {
  13464. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13465. super();
  13466. this.type = 'TorusKnotGeometry';
  13467. this.parameters = {
  13468. radius: radius,
  13469. tube: tube,
  13470. tubularSegments: tubularSegments,
  13471. radialSegments: radialSegments,
  13472. p: p,
  13473. q: q
  13474. };
  13475. tubularSegments = Math.floor( tubularSegments );
  13476. radialSegments = Math.floor( radialSegments );
  13477. // buffers
  13478. const indices = [];
  13479. const vertices = [];
  13480. const normals = [];
  13481. const uvs = [];
  13482. // helper variables
  13483. const vertex = new Vector3();
  13484. const normal = new Vector3();
  13485. const P1 = new Vector3();
  13486. const P2 = new Vector3();
  13487. const B = new Vector3();
  13488. const T = new Vector3();
  13489. const N = new Vector3();
  13490. // generate vertices, normals and uvs
  13491. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13492. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13493. const u = i / tubularSegments * p * Math.PI * 2;
  13494. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13495. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13496. calculatePositionOnCurve( u, p, q, radius, P1 );
  13497. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13498. // calculate orthonormal basis
  13499. T.subVectors( P2, P1 );
  13500. N.addVectors( P2, P1 );
  13501. B.crossVectors( T, N );
  13502. N.crossVectors( B, T );
  13503. // normalize B, N. T can be ignored, we don't use it
  13504. B.normalize();
  13505. N.normalize();
  13506. for ( let j = 0; j <= radialSegments; ++ j ) {
  13507. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13508. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13509. const v = j / radialSegments * Math.PI * 2;
  13510. const cx = - tube * Math.cos( v );
  13511. const cy = tube * Math.sin( v );
  13512. // now calculate the final vertex position.
  13513. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13514. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13515. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13516. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13517. vertices.push( vertex.x, vertex.y, vertex.z );
  13518. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13519. normal.subVectors( vertex, P1 ).normalize();
  13520. normals.push( normal.x, normal.y, normal.z );
  13521. // uv
  13522. uvs.push( i / tubularSegments );
  13523. uvs.push( j / radialSegments );
  13524. }
  13525. }
  13526. // generate indices
  13527. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13528. for ( let i = 1; i <= radialSegments; i ++ ) {
  13529. // indices
  13530. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13531. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13532. const c = ( radialSegments + 1 ) * j + i;
  13533. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13534. // faces
  13535. indices.push( a, b, d );
  13536. indices.push( b, c, d );
  13537. }
  13538. }
  13539. // build geometry
  13540. this.setIndex( indices );
  13541. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13542. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13543. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13544. // this function calculates the current position on the torus curve
  13545. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13546. const cu = Math.cos( u );
  13547. const su = Math.sin( u );
  13548. const quOverP = q / p * u;
  13549. const cs = Math.cos( quOverP );
  13550. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13551. position.y = radius * ( 2 + cs ) * su * 0.5;
  13552. position.z = radius * Math.sin( quOverP ) * 0.5;
  13553. }
  13554. }
  13555. copy( source ) {
  13556. super.copy( source );
  13557. this.parameters = Object.assign( {}, source.parameters );
  13558. return this;
  13559. }
  13560. static fromJSON( data ) {
  13561. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13562. }
  13563. }
  13564. class TubeGeometry extends BufferGeometry {
  13565. 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 ) {
  13566. super();
  13567. this.type = 'TubeGeometry';
  13568. this.parameters = {
  13569. path: path,
  13570. tubularSegments: tubularSegments,
  13571. radius: radius,
  13572. radialSegments: radialSegments,
  13573. closed: closed
  13574. };
  13575. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13576. // expose internals
  13577. this.tangents = frames.tangents;
  13578. this.normals = frames.normals;
  13579. this.binormals = frames.binormals;
  13580. // helper variables
  13581. const vertex = new Vector3();
  13582. const normal = new Vector3();
  13583. const uv = new Vector2();
  13584. let P = new Vector3();
  13585. // buffer
  13586. const vertices = [];
  13587. const normals = [];
  13588. const uvs = [];
  13589. const indices = [];
  13590. // create buffer data
  13591. generateBufferData();
  13592. // build geometry
  13593. this.setIndex( indices );
  13594. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13595. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13596. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13597. // functions
  13598. function generateBufferData() {
  13599. for ( let i = 0; i < tubularSegments; i ++ ) {
  13600. generateSegment( i );
  13601. }
  13602. // if the geometry is not closed, generate the last row of vertices and normals
  13603. // at the regular position on the given path
  13604. //
  13605. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13606. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13607. // uvs are generated in a separate function.
  13608. // this makes it easy compute correct values for closed geometries
  13609. generateUVs();
  13610. // finally create faces
  13611. generateIndices();
  13612. }
  13613. function generateSegment( i ) {
  13614. // we use getPointAt to sample evenly distributed points from the given path
  13615. P = path.getPointAt( i / tubularSegments, P );
  13616. // retrieve corresponding normal and binormal
  13617. const N = frames.normals[ i ];
  13618. const B = frames.binormals[ i ];
  13619. // generate normals and vertices for the current segment
  13620. for ( let j = 0; j <= radialSegments; j ++ ) {
  13621. const v = j / radialSegments * Math.PI * 2;
  13622. const sin = Math.sin( v );
  13623. const cos = - Math.cos( v );
  13624. // normal
  13625. normal.x = ( cos * N.x + sin * B.x );
  13626. normal.y = ( cos * N.y + sin * B.y );
  13627. normal.z = ( cos * N.z + sin * B.z );
  13628. normal.normalize();
  13629. normals.push( normal.x, normal.y, normal.z );
  13630. // vertex
  13631. vertex.x = P.x + radius * normal.x;
  13632. vertex.y = P.y + radius * normal.y;
  13633. vertex.z = P.z + radius * normal.z;
  13634. vertices.push( vertex.x, vertex.y, vertex.z );
  13635. }
  13636. }
  13637. function generateIndices() {
  13638. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13639. for ( let i = 1; i <= radialSegments; i ++ ) {
  13640. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13641. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13642. const c = ( radialSegments + 1 ) * j + i;
  13643. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13644. // faces
  13645. indices.push( a, b, d );
  13646. indices.push( b, c, d );
  13647. }
  13648. }
  13649. }
  13650. function generateUVs() {
  13651. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13652. for ( let j = 0; j <= radialSegments; j ++ ) {
  13653. uv.x = i / tubularSegments;
  13654. uv.y = j / radialSegments;
  13655. uvs.push( uv.x, uv.y );
  13656. }
  13657. }
  13658. }
  13659. }
  13660. copy( source ) {
  13661. super.copy( source );
  13662. this.parameters = Object.assign( {}, source.parameters );
  13663. return this;
  13664. }
  13665. toJSON() {
  13666. const data = super.toJSON();
  13667. data.path = this.parameters.path.toJSON();
  13668. return data;
  13669. }
  13670. static fromJSON( data ) {
  13671. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13672. // User defined curves or instances of CurvePath will not be deserialized.
  13673. return new TubeGeometry(
  13674. new Curves[ data.path.type ]().fromJSON( data.path ),
  13675. data.tubularSegments,
  13676. data.radius,
  13677. data.radialSegments,
  13678. data.closed
  13679. );
  13680. }
  13681. }
  13682. class WireframeGeometry extends BufferGeometry {
  13683. constructor( geometry = null ) {
  13684. super();
  13685. this.type = 'WireframeGeometry';
  13686. this.parameters = {
  13687. geometry: geometry
  13688. };
  13689. if ( geometry !== null ) {
  13690. // buffer
  13691. const vertices = [];
  13692. const edges = new Set();
  13693. // helper variables
  13694. const start = new Vector3();
  13695. const end = new Vector3();
  13696. if ( geometry.index !== null ) {
  13697. // indexed BufferGeometry
  13698. const position = geometry.attributes.position;
  13699. const indices = geometry.index;
  13700. let groups = geometry.groups;
  13701. if ( groups.length === 0 ) {
  13702. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13703. }
  13704. // create a data structure that contains all edges without duplicates
  13705. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13706. const group = groups[ o ];
  13707. const groupStart = group.start;
  13708. const groupCount = group.count;
  13709. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13710. for ( let j = 0; j < 3; j ++ ) {
  13711. const index1 = indices.getX( i + j );
  13712. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13713. start.fromBufferAttribute( position, index1 );
  13714. end.fromBufferAttribute( position, index2 );
  13715. if ( isUniqueEdge( start, end, edges ) === true ) {
  13716. vertices.push( start.x, start.y, start.z );
  13717. vertices.push( end.x, end.y, end.z );
  13718. }
  13719. }
  13720. }
  13721. }
  13722. } else {
  13723. // non-indexed BufferGeometry
  13724. const position = geometry.attributes.position;
  13725. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13726. for ( let j = 0; j < 3; j ++ ) {
  13727. // three edges per triangle, an edge is represented as (index1, index2)
  13728. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13729. const index1 = 3 * i + j;
  13730. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13731. start.fromBufferAttribute( position, index1 );
  13732. end.fromBufferAttribute( position, index2 );
  13733. if ( isUniqueEdge( start, end, edges ) === true ) {
  13734. vertices.push( start.x, start.y, start.z );
  13735. vertices.push( end.x, end.y, end.z );
  13736. }
  13737. }
  13738. }
  13739. }
  13740. // build geometry
  13741. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13742. }
  13743. }
  13744. copy( source ) {
  13745. super.copy( source );
  13746. this.parameters = Object.assign( {}, source.parameters );
  13747. return this;
  13748. }
  13749. }
  13750. function isUniqueEdge( start, end, edges ) {
  13751. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13752. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13753. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13754. return false;
  13755. } else {
  13756. edges.add( hash1 );
  13757. edges.add( hash2 );
  13758. return true;
  13759. }
  13760. }
  13761. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13762. __proto__: null,
  13763. BoxGeometry: BoxGeometry,
  13764. CapsuleGeometry: CapsuleGeometry,
  13765. CircleGeometry: CircleGeometry,
  13766. ConeGeometry: ConeGeometry,
  13767. CylinderGeometry: CylinderGeometry,
  13768. DodecahedronGeometry: DodecahedronGeometry,
  13769. EdgesGeometry: EdgesGeometry,
  13770. ExtrudeGeometry: ExtrudeGeometry,
  13771. IcosahedronGeometry: IcosahedronGeometry,
  13772. LatheGeometry: LatheGeometry,
  13773. OctahedronGeometry: OctahedronGeometry,
  13774. PlaneGeometry: PlaneGeometry,
  13775. PolyhedronGeometry: PolyhedronGeometry,
  13776. RingGeometry: RingGeometry,
  13777. ShapeGeometry: ShapeGeometry,
  13778. SphereGeometry: SphereGeometry,
  13779. TetrahedronGeometry: TetrahedronGeometry,
  13780. TorusGeometry: TorusGeometry,
  13781. TorusKnotGeometry: TorusKnotGeometry,
  13782. TubeGeometry: TubeGeometry,
  13783. WireframeGeometry: WireframeGeometry
  13784. });
  13785. class ShadowMaterial extends Material {
  13786. constructor( parameters ) {
  13787. super();
  13788. this.isShadowMaterial = true;
  13789. this.type = 'ShadowMaterial';
  13790. this.color = new Color( 0x000000 );
  13791. this.transparent = true;
  13792. this.fog = true;
  13793. this.setValues( parameters );
  13794. }
  13795. copy( source ) {
  13796. super.copy( source );
  13797. this.color.copy( source.color );
  13798. this.fog = source.fog;
  13799. return this;
  13800. }
  13801. }
  13802. class RawShaderMaterial extends ShaderMaterial {
  13803. constructor( parameters ) {
  13804. super( parameters );
  13805. this.isRawShaderMaterial = true;
  13806. this.type = 'RawShaderMaterial';
  13807. }
  13808. }
  13809. class MeshStandardMaterial extends Material {
  13810. constructor( parameters ) {
  13811. super();
  13812. this.isMeshStandardMaterial = true;
  13813. this.defines = { 'STANDARD': '' };
  13814. this.type = 'MeshStandardMaterial';
  13815. this.color = new Color( 0xffffff ); // diffuse
  13816. this.roughness = 1.0;
  13817. this.metalness = 0.0;
  13818. this.map = null;
  13819. this.lightMap = null;
  13820. this.lightMapIntensity = 1.0;
  13821. this.aoMap = null;
  13822. this.aoMapIntensity = 1.0;
  13823. this.emissive = new Color( 0x000000 );
  13824. this.emissiveIntensity = 1.0;
  13825. this.emissiveMap = null;
  13826. this.bumpMap = null;
  13827. this.bumpScale = 1;
  13828. this.normalMap = null;
  13829. this.normalMapType = TangentSpaceNormalMap;
  13830. this.normalScale = new Vector2( 1, 1 );
  13831. this.displacementMap = null;
  13832. this.displacementScale = 1;
  13833. this.displacementBias = 0;
  13834. this.roughnessMap = null;
  13835. this.metalnessMap = null;
  13836. this.alphaMap = null;
  13837. this.envMap = null;
  13838. this.envMapRotation = new Euler();
  13839. this.envMapIntensity = 1.0;
  13840. this.wireframe = false;
  13841. this.wireframeLinewidth = 1;
  13842. this.wireframeLinecap = 'round';
  13843. this.wireframeLinejoin = 'round';
  13844. this.flatShading = false;
  13845. this.fog = true;
  13846. this.setValues( parameters );
  13847. }
  13848. copy( source ) {
  13849. super.copy( source );
  13850. this.defines = { 'STANDARD': '' };
  13851. this.color.copy( source.color );
  13852. this.roughness = source.roughness;
  13853. this.metalness = source.metalness;
  13854. this.map = source.map;
  13855. this.lightMap = source.lightMap;
  13856. this.lightMapIntensity = source.lightMapIntensity;
  13857. this.aoMap = source.aoMap;
  13858. this.aoMapIntensity = source.aoMapIntensity;
  13859. this.emissive.copy( source.emissive );
  13860. this.emissiveMap = source.emissiveMap;
  13861. this.emissiveIntensity = source.emissiveIntensity;
  13862. this.bumpMap = source.bumpMap;
  13863. this.bumpScale = source.bumpScale;
  13864. this.normalMap = source.normalMap;
  13865. this.normalMapType = source.normalMapType;
  13866. this.normalScale.copy( source.normalScale );
  13867. this.displacementMap = source.displacementMap;
  13868. this.displacementScale = source.displacementScale;
  13869. this.displacementBias = source.displacementBias;
  13870. this.roughnessMap = source.roughnessMap;
  13871. this.metalnessMap = source.metalnessMap;
  13872. this.alphaMap = source.alphaMap;
  13873. this.envMap = source.envMap;
  13874. this.envMapRotation.copy( source.envMapRotation );
  13875. this.envMapIntensity = source.envMapIntensity;
  13876. this.wireframe = source.wireframe;
  13877. this.wireframeLinewidth = source.wireframeLinewidth;
  13878. this.wireframeLinecap = source.wireframeLinecap;
  13879. this.wireframeLinejoin = source.wireframeLinejoin;
  13880. this.flatShading = source.flatShading;
  13881. this.fog = source.fog;
  13882. return this;
  13883. }
  13884. }
  13885. class MeshPhysicalMaterial extends MeshStandardMaterial {
  13886. constructor( parameters ) {
  13887. super();
  13888. this.isMeshPhysicalMaterial = true;
  13889. this.defines = {
  13890. 'STANDARD': '',
  13891. 'PHYSICAL': ''
  13892. };
  13893. this.type = 'MeshPhysicalMaterial';
  13894. this.anisotropyRotation = 0;
  13895. this.anisotropyMap = null;
  13896. this.clearcoatMap = null;
  13897. this.clearcoatRoughness = 0.0;
  13898. this.clearcoatRoughnessMap = null;
  13899. this.clearcoatNormalScale = new Vector2( 1, 1 );
  13900. this.clearcoatNormalMap = null;
  13901. this.ior = 1.5;
  13902. Object.defineProperty( this, 'reflectivity', {
  13903. get: function () {
  13904. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  13905. },
  13906. set: function ( reflectivity ) {
  13907. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  13908. }
  13909. } );
  13910. this.iridescenceMap = null;
  13911. this.iridescenceIOR = 1.3;
  13912. this.iridescenceThicknessRange = [ 100, 400 ];
  13913. this.iridescenceThicknessMap = null;
  13914. this.sheenColor = new Color( 0x000000 );
  13915. this.sheenColorMap = null;
  13916. this.sheenRoughness = 1.0;
  13917. this.sheenRoughnessMap = null;
  13918. this.transmissionMap = null;
  13919. this.thickness = 0;
  13920. this.thicknessMap = null;
  13921. this.attenuationDistance = Infinity;
  13922. this.attenuationColor = new Color( 1, 1, 1 );
  13923. this.specularIntensity = 1.0;
  13924. this.specularIntensityMap = null;
  13925. this.specularColor = new Color( 1, 1, 1 );
  13926. this.specularColorMap = null;
  13927. this._anisotropy = 0;
  13928. this._clearcoat = 0;
  13929. this._dispersion = 0;
  13930. this._iridescence = 0;
  13931. this._sheen = 0.0;
  13932. this._transmission = 0;
  13933. this.setValues( parameters );
  13934. }
  13935. get anisotropy() {
  13936. return this._anisotropy;
  13937. }
  13938. set anisotropy( value ) {
  13939. if ( this._anisotropy > 0 !== value > 0 ) {
  13940. this.version ++;
  13941. }
  13942. this._anisotropy = value;
  13943. }
  13944. get clearcoat() {
  13945. return this._clearcoat;
  13946. }
  13947. set clearcoat( value ) {
  13948. if ( this._clearcoat > 0 !== value > 0 ) {
  13949. this.version ++;
  13950. }
  13951. this._clearcoat = value;
  13952. }
  13953. get iridescence() {
  13954. return this._iridescence;
  13955. }
  13956. set iridescence( value ) {
  13957. if ( this._iridescence > 0 !== value > 0 ) {
  13958. this.version ++;
  13959. }
  13960. this._iridescence = value;
  13961. }
  13962. get dispersion() {
  13963. return this._dispersion;
  13964. }
  13965. set dispersion( value ) {
  13966. if ( this._dispersion > 0 !== value > 0 ) {
  13967. this.version ++;
  13968. }
  13969. this._dispersion = value;
  13970. }
  13971. get sheen() {
  13972. return this._sheen;
  13973. }
  13974. set sheen( value ) {
  13975. if ( this._sheen > 0 !== value > 0 ) {
  13976. this.version ++;
  13977. }
  13978. this._sheen = value;
  13979. }
  13980. get transmission() {
  13981. return this._transmission;
  13982. }
  13983. set transmission( value ) {
  13984. if ( this._transmission > 0 !== value > 0 ) {
  13985. this.version ++;
  13986. }
  13987. this._transmission = value;
  13988. }
  13989. copy( source ) {
  13990. super.copy( source );
  13991. this.defines = {
  13992. 'STANDARD': '',
  13993. 'PHYSICAL': ''
  13994. };
  13995. this.anisotropy = source.anisotropy;
  13996. this.anisotropyRotation = source.anisotropyRotation;
  13997. this.anisotropyMap = source.anisotropyMap;
  13998. this.clearcoat = source.clearcoat;
  13999. this.clearcoatMap = source.clearcoatMap;
  14000. this.clearcoatRoughness = source.clearcoatRoughness;
  14001. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14002. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14003. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14004. this.dispersion = source.dispersion;
  14005. this.ior = source.ior;
  14006. this.iridescence = source.iridescence;
  14007. this.iridescenceMap = source.iridescenceMap;
  14008. this.iridescenceIOR = source.iridescenceIOR;
  14009. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14010. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14011. this.sheen = source.sheen;
  14012. this.sheenColor.copy( source.sheenColor );
  14013. this.sheenColorMap = source.sheenColorMap;
  14014. this.sheenRoughness = source.sheenRoughness;
  14015. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14016. this.transmission = source.transmission;
  14017. this.transmissionMap = source.transmissionMap;
  14018. this.thickness = source.thickness;
  14019. this.thicknessMap = source.thicknessMap;
  14020. this.attenuationDistance = source.attenuationDistance;
  14021. this.attenuationColor.copy( source.attenuationColor );
  14022. this.specularIntensity = source.specularIntensity;
  14023. this.specularIntensityMap = source.specularIntensityMap;
  14024. this.specularColor.copy( source.specularColor );
  14025. this.specularColorMap = source.specularColorMap;
  14026. return this;
  14027. }
  14028. }
  14029. class MeshPhongMaterial extends Material {
  14030. constructor( parameters ) {
  14031. super();
  14032. this.isMeshPhongMaterial = true;
  14033. this.type = 'MeshPhongMaterial';
  14034. this.color = new Color( 0xffffff ); // diffuse
  14035. this.specular = new Color( 0x111111 );
  14036. this.shininess = 30;
  14037. this.map = null;
  14038. this.lightMap = null;
  14039. this.lightMapIntensity = 1.0;
  14040. this.aoMap = null;
  14041. this.aoMapIntensity = 1.0;
  14042. this.emissive = new Color( 0x000000 );
  14043. this.emissiveIntensity = 1.0;
  14044. this.emissiveMap = null;
  14045. this.bumpMap = null;
  14046. this.bumpScale = 1;
  14047. this.normalMap = null;
  14048. this.normalMapType = TangentSpaceNormalMap;
  14049. this.normalScale = new Vector2( 1, 1 );
  14050. this.displacementMap = null;
  14051. this.displacementScale = 1;
  14052. this.displacementBias = 0;
  14053. this.specularMap = null;
  14054. this.alphaMap = null;
  14055. this.envMap = null;
  14056. this.envMapRotation = new Euler();
  14057. this.combine = MultiplyOperation;
  14058. this.reflectivity = 1;
  14059. this.refractionRatio = 0.98;
  14060. this.wireframe = false;
  14061. this.wireframeLinewidth = 1;
  14062. this.wireframeLinecap = 'round';
  14063. this.wireframeLinejoin = 'round';
  14064. this.flatShading = false;
  14065. this.fog = true;
  14066. this.setValues( parameters );
  14067. }
  14068. copy( source ) {
  14069. super.copy( source );
  14070. this.color.copy( source.color );
  14071. this.specular.copy( source.specular );
  14072. this.shininess = source.shininess;
  14073. this.map = source.map;
  14074. this.lightMap = source.lightMap;
  14075. this.lightMapIntensity = source.lightMapIntensity;
  14076. this.aoMap = source.aoMap;
  14077. this.aoMapIntensity = source.aoMapIntensity;
  14078. this.emissive.copy( source.emissive );
  14079. this.emissiveMap = source.emissiveMap;
  14080. this.emissiveIntensity = source.emissiveIntensity;
  14081. this.bumpMap = source.bumpMap;
  14082. this.bumpScale = source.bumpScale;
  14083. this.normalMap = source.normalMap;
  14084. this.normalMapType = source.normalMapType;
  14085. this.normalScale.copy( source.normalScale );
  14086. this.displacementMap = source.displacementMap;
  14087. this.displacementScale = source.displacementScale;
  14088. this.displacementBias = source.displacementBias;
  14089. this.specularMap = source.specularMap;
  14090. this.alphaMap = source.alphaMap;
  14091. this.envMap = source.envMap;
  14092. this.envMapRotation.copy( source.envMapRotation );
  14093. this.combine = source.combine;
  14094. this.reflectivity = source.reflectivity;
  14095. this.refractionRatio = source.refractionRatio;
  14096. this.wireframe = source.wireframe;
  14097. this.wireframeLinewidth = source.wireframeLinewidth;
  14098. this.wireframeLinecap = source.wireframeLinecap;
  14099. this.wireframeLinejoin = source.wireframeLinejoin;
  14100. this.flatShading = source.flatShading;
  14101. this.fog = source.fog;
  14102. return this;
  14103. }
  14104. }
  14105. class MeshToonMaterial extends Material {
  14106. constructor( parameters ) {
  14107. super();
  14108. this.isMeshToonMaterial = true;
  14109. this.defines = { 'TOON': '' };
  14110. this.type = 'MeshToonMaterial';
  14111. this.color = new Color( 0xffffff );
  14112. this.map = null;
  14113. this.gradientMap = null;
  14114. this.lightMap = null;
  14115. this.lightMapIntensity = 1.0;
  14116. this.aoMap = null;
  14117. this.aoMapIntensity = 1.0;
  14118. this.emissive = new Color( 0x000000 );
  14119. this.emissiveIntensity = 1.0;
  14120. this.emissiveMap = null;
  14121. this.bumpMap = null;
  14122. this.bumpScale = 1;
  14123. this.normalMap = null;
  14124. this.normalMapType = TangentSpaceNormalMap;
  14125. this.normalScale = new Vector2( 1, 1 );
  14126. this.displacementMap = null;
  14127. this.displacementScale = 1;
  14128. this.displacementBias = 0;
  14129. this.alphaMap = null;
  14130. this.wireframe = false;
  14131. this.wireframeLinewidth = 1;
  14132. this.wireframeLinecap = 'round';
  14133. this.wireframeLinejoin = 'round';
  14134. this.fog = true;
  14135. this.setValues( parameters );
  14136. }
  14137. copy( source ) {
  14138. super.copy( source );
  14139. this.color.copy( source.color );
  14140. this.map = source.map;
  14141. this.gradientMap = source.gradientMap;
  14142. this.lightMap = source.lightMap;
  14143. this.lightMapIntensity = source.lightMapIntensity;
  14144. this.aoMap = source.aoMap;
  14145. this.aoMapIntensity = source.aoMapIntensity;
  14146. this.emissive.copy( source.emissive );
  14147. this.emissiveMap = source.emissiveMap;
  14148. this.emissiveIntensity = source.emissiveIntensity;
  14149. this.bumpMap = source.bumpMap;
  14150. this.bumpScale = source.bumpScale;
  14151. this.normalMap = source.normalMap;
  14152. this.normalMapType = source.normalMapType;
  14153. this.normalScale.copy( source.normalScale );
  14154. this.displacementMap = source.displacementMap;
  14155. this.displacementScale = source.displacementScale;
  14156. this.displacementBias = source.displacementBias;
  14157. this.alphaMap = source.alphaMap;
  14158. this.wireframe = source.wireframe;
  14159. this.wireframeLinewidth = source.wireframeLinewidth;
  14160. this.wireframeLinecap = source.wireframeLinecap;
  14161. this.wireframeLinejoin = source.wireframeLinejoin;
  14162. this.fog = source.fog;
  14163. return this;
  14164. }
  14165. }
  14166. class MeshNormalMaterial extends Material {
  14167. constructor( parameters ) {
  14168. super();
  14169. this.isMeshNormalMaterial = true;
  14170. this.type = 'MeshNormalMaterial';
  14171. this.bumpMap = null;
  14172. this.bumpScale = 1;
  14173. this.normalMap = null;
  14174. this.normalMapType = TangentSpaceNormalMap;
  14175. this.normalScale = new Vector2( 1, 1 );
  14176. this.displacementMap = null;
  14177. this.displacementScale = 1;
  14178. this.displacementBias = 0;
  14179. this.wireframe = false;
  14180. this.wireframeLinewidth = 1;
  14181. this.flatShading = false;
  14182. this.setValues( parameters );
  14183. }
  14184. copy( source ) {
  14185. super.copy( source );
  14186. this.bumpMap = source.bumpMap;
  14187. this.bumpScale = source.bumpScale;
  14188. this.normalMap = source.normalMap;
  14189. this.normalMapType = source.normalMapType;
  14190. this.normalScale.copy( source.normalScale );
  14191. this.displacementMap = source.displacementMap;
  14192. this.displacementScale = source.displacementScale;
  14193. this.displacementBias = source.displacementBias;
  14194. this.wireframe = source.wireframe;
  14195. this.wireframeLinewidth = source.wireframeLinewidth;
  14196. this.flatShading = source.flatShading;
  14197. return this;
  14198. }
  14199. }
  14200. class MeshLambertMaterial extends Material {
  14201. constructor( parameters ) {
  14202. super();
  14203. this.isMeshLambertMaterial = true;
  14204. this.type = 'MeshLambertMaterial';
  14205. this.color = new Color( 0xffffff ); // diffuse
  14206. this.map = null;
  14207. this.lightMap = null;
  14208. this.lightMapIntensity = 1.0;
  14209. this.aoMap = null;
  14210. this.aoMapIntensity = 1.0;
  14211. this.emissive = new Color( 0x000000 );
  14212. this.emissiveIntensity = 1.0;
  14213. this.emissiveMap = null;
  14214. this.bumpMap = null;
  14215. this.bumpScale = 1;
  14216. this.normalMap = null;
  14217. this.normalMapType = TangentSpaceNormalMap;
  14218. this.normalScale = new Vector2( 1, 1 );
  14219. this.displacementMap = null;
  14220. this.displacementScale = 1;
  14221. this.displacementBias = 0;
  14222. this.specularMap = null;
  14223. this.alphaMap = null;
  14224. this.envMap = null;
  14225. this.envMapRotation = new Euler();
  14226. this.combine = MultiplyOperation;
  14227. this.reflectivity = 1;
  14228. this.refractionRatio = 0.98;
  14229. this.wireframe = false;
  14230. this.wireframeLinewidth = 1;
  14231. this.wireframeLinecap = 'round';
  14232. this.wireframeLinejoin = 'round';
  14233. this.flatShading = false;
  14234. this.fog = true;
  14235. this.setValues( parameters );
  14236. }
  14237. copy( source ) {
  14238. super.copy( source );
  14239. this.color.copy( source.color );
  14240. this.map = source.map;
  14241. this.lightMap = source.lightMap;
  14242. this.lightMapIntensity = source.lightMapIntensity;
  14243. this.aoMap = source.aoMap;
  14244. this.aoMapIntensity = source.aoMapIntensity;
  14245. this.emissive.copy( source.emissive );
  14246. this.emissiveMap = source.emissiveMap;
  14247. this.emissiveIntensity = source.emissiveIntensity;
  14248. this.bumpMap = source.bumpMap;
  14249. this.bumpScale = source.bumpScale;
  14250. this.normalMap = source.normalMap;
  14251. this.normalMapType = source.normalMapType;
  14252. this.normalScale.copy( source.normalScale );
  14253. this.displacementMap = source.displacementMap;
  14254. this.displacementScale = source.displacementScale;
  14255. this.displacementBias = source.displacementBias;
  14256. this.specularMap = source.specularMap;
  14257. this.alphaMap = source.alphaMap;
  14258. this.envMap = source.envMap;
  14259. this.envMapRotation.copy( source.envMapRotation );
  14260. this.combine = source.combine;
  14261. this.reflectivity = source.reflectivity;
  14262. this.refractionRatio = source.refractionRatio;
  14263. this.wireframe = source.wireframe;
  14264. this.wireframeLinewidth = source.wireframeLinewidth;
  14265. this.wireframeLinecap = source.wireframeLinecap;
  14266. this.wireframeLinejoin = source.wireframeLinejoin;
  14267. this.flatShading = source.flatShading;
  14268. this.fog = source.fog;
  14269. return this;
  14270. }
  14271. }
  14272. class MeshDepthMaterial extends Material {
  14273. constructor( parameters ) {
  14274. super();
  14275. this.isMeshDepthMaterial = true;
  14276. this.type = 'MeshDepthMaterial';
  14277. this.depthPacking = BasicDepthPacking;
  14278. this.map = null;
  14279. this.alphaMap = null;
  14280. this.displacementMap = null;
  14281. this.displacementScale = 1;
  14282. this.displacementBias = 0;
  14283. this.wireframe = false;
  14284. this.wireframeLinewidth = 1;
  14285. this.setValues( parameters );
  14286. }
  14287. copy( source ) {
  14288. super.copy( source );
  14289. this.depthPacking = source.depthPacking;
  14290. this.map = source.map;
  14291. this.alphaMap = source.alphaMap;
  14292. this.displacementMap = source.displacementMap;
  14293. this.displacementScale = source.displacementScale;
  14294. this.displacementBias = source.displacementBias;
  14295. this.wireframe = source.wireframe;
  14296. this.wireframeLinewidth = source.wireframeLinewidth;
  14297. return this;
  14298. }
  14299. }
  14300. class MeshDistanceMaterial extends Material {
  14301. constructor( parameters ) {
  14302. super();
  14303. this.isMeshDistanceMaterial = true;
  14304. this.type = 'MeshDistanceMaterial';
  14305. this.map = null;
  14306. this.alphaMap = null;
  14307. this.displacementMap = null;
  14308. this.displacementScale = 1;
  14309. this.displacementBias = 0;
  14310. this.setValues( parameters );
  14311. }
  14312. copy( source ) {
  14313. super.copy( source );
  14314. this.map = source.map;
  14315. this.alphaMap = source.alphaMap;
  14316. this.displacementMap = source.displacementMap;
  14317. this.displacementScale = source.displacementScale;
  14318. this.displacementBias = source.displacementBias;
  14319. return this;
  14320. }
  14321. }
  14322. class MeshMatcapMaterial extends Material {
  14323. constructor( parameters ) {
  14324. super();
  14325. this.isMeshMatcapMaterial = true;
  14326. this.defines = { 'MATCAP': '' };
  14327. this.type = 'MeshMatcapMaterial';
  14328. this.color = new Color( 0xffffff ); // diffuse
  14329. this.matcap = null;
  14330. this.map = null;
  14331. this.bumpMap = null;
  14332. this.bumpScale = 1;
  14333. this.normalMap = null;
  14334. this.normalMapType = TangentSpaceNormalMap;
  14335. this.normalScale = new Vector2( 1, 1 );
  14336. this.displacementMap = null;
  14337. this.displacementScale = 1;
  14338. this.displacementBias = 0;
  14339. this.alphaMap = null;
  14340. this.flatShading = false;
  14341. this.fog = true;
  14342. this.setValues( parameters );
  14343. }
  14344. copy( source ) {
  14345. super.copy( source );
  14346. this.defines = { 'MATCAP': '' };
  14347. this.color.copy( source.color );
  14348. this.matcap = source.matcap;
  14349. this.map = source.map;
  14350. this.bumpMap = source.bumpMap;
  14351. this.bumpScale = source.bumpScale;
  14352. this.normalMap = source.normalMap;
  14353. this.normalMapType = source.normalMapType;
  14354. this.normalScale.copy( source.normalScale );
  14355. this.displacementMap = source.displacementMap;
  14356. this.displacementScale = source.displacementScale;
  14357. this.displacementBias = source.displacementBias;
  14358. this.alphaMap = source.alphaMap;
  14359. this.flatShading = source.flatShading;
  14360. this.fog = source.fog;
  14361. return this;
  14362. }
  14363. }
  14364. class LineDashedMaterial extends LineBasicMaterial {
  14365. constructor( parameters ) {
  14366. super();
  14367. this.isLineDashedMaterial = true;
  14368. this.type = 'LineDashedMaterial';
  14369. this.scale = 1;
  14370. this.dashSize = 3;
  14371. this.gapSize = 1;
  14372. this.setValues( parameters );
  14373. }
  14374. copy( source ) {
  14375. super.copy( source );
  14376. this.scale = source.scale;
  14377. this.dashSize = source.dashSize;
  14378. this.gapSize = source.gapSize;
  14379. return this;
  14380. }
  14381. }
  14382. // converts an array to a specific type
  14383. function convertArray( array, type, forceClone ) {
  14384. if ( ! array || // let 'undefined' and 'null' pass
  14385. ! forceClone && array.constructor === type ) return array;
  14386. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14387. return new type( array ); // create typed array
  14388. }
  14389. return Array.prototype.slice.call( array ); // create Array
  14390. }
  14391. function isTypedArray( object ) {
  14392. return ArrayBuffer.isView( object ) &&
  14393. ! ( object instanceof DataView );
  14394. }
  14395. // returns an array by which times and values can be sorted
  14396. function getKeyframeOrder( times ) {
  14397. function compareTime( i, j ) {
  14398. return times[ i ] - times[ j ];
  14399. }
  14400. const n = times.length;
  14401. const result = new Array( n );
  14402. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14403. result.sort( compareTime );
  14404. return result;
  14405. }
  14406. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14407. function sortedArray( values, stride, order ) {
  14408. const nValues = values.length;
  14409. const result = new values.constructor( nValues );
  14410. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14411. const srcOffset = order[ i ] * stride;
  14412. for ( let j = 0; j !== stride; ++ j ) {
  14413. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14414. }
  14415. }
  14416. return result;
  14417. }
  14418. // function for parsing AOS keyframe formats
  14419. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14420. let i = 1, key = jsonKeys[ 0 ];
  14421. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14422. key = jsonKeys[ i ++ ];
  14423. }
  14424. if ( key === undefined ) return; // no data
  14425. let value = key[ valuePropertyName ];
  14426. if ( value === undefined ) return; // no data
  14427. if ( Array.isArray( value ) ) {
  14428. do {
  14429. value = key[ valuePropertyName ];
  14430. if ( value !== undefined ) {
  14431. times.push( key.time );
  14432. values.push.apply( values, value ); // push all elements
  14433. }
  14434. key = jsonKeys[ i ++ ];
  14435. } while ( key !== undefined );
  14436. } else if ( value.toArray !== undefined ) {
  14437. // ...assume THREE.Math-ish
  14438. do {
  14439. value = key[ valuePropertyName ];
  14440. if ( value !== undefined ) {
  14441. times.push( key.time );
  14442. value.toArray( values, values.length );
  14443. }
  14444. key = jsonKeys[ i ++ ];
  14445. } while ( key !== undefined );
  14446. } else {
  14447. // otherwise push as-is
  14448. do {
  14449. value = key[ valuePropertyName ];
  14450. if ( value !== undefined ) {
  14451. times.push( key.time );
  14452. values.push( value );
  14453. }
  14454. key = jsonKeys[ i ++ ];
  14455. } while ( key !== undefined );
  14456. }
  14457. }
  14458. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14459. const clip = sourceClip.clone();
  14460. clip.name = name;
  14461. const tracks = [];
  14462. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14463. const track = clip.tracks[ i ];
  14464. const valueSize = track.getValueSize();
  14465. const times = [];
  14466. const values = [];
  14467. for ( let j = 0; j < track.times.length; ++ j ) {
  14468. const frame = track.times[ j ] * fps;
  14469. if ( frame < startFrame || frame >= endFrame ) continue;
  14470. times.push( track.times[ j ] );
  14471. for ( let k = 0; k < valueSize; ++ k ) {
  14472. values.push( track.values[ j * valueSize + k ] );
  14473. }
  14474. }
  14475. if ( times.length === 0 ) continue;
  14476. track.times = convertArray( times, track.times.constructor );
  14477. track.values = convertArray( values, track.values.constructor );
  14478. tracks.push( track );
  14479. }
  14480. clip.tracks = tracks;
  14481. // find minimum .times value across all tracks in the trimmed clip
  14482. let minStartTime = Infinity;
  14483. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14484. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14485. minStartTime = clip.tracks[ i ].times[ 0 ];
  14486. }
  14487. }
  14488. // shift all tracks such that clip begins at t=0
  14489. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14490. clip.tracks[ i ].shift( - 1 * minStartTime );
  14491. }
  14492. clip.resetDuration();
  14493. return clip;
  14494. }
  14495. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14496. if ( fps <= 0 ) fps = 30;
  14497. const numTracks = referenceClip.tracks.length;
  14498. const referenceTime = referenceFrame / fps;
  14499. // Make each track's values relative to the values at the reference frame
  14500. for ( let i = 0; i < numTracks; ++ i ) {
  14501. const referenceTrack = referenceClip.tracks[ i ];
  14502. const referenceTrackType = referenceTrack.ValueTypeName;
  14503. // Skip this track if it's non-numeric
  14504. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14505. // Find the track in the target clip whose name and type matches the reference track
  14506. const targetTrack = targetClip.tracks.find( function ( track ) {
  14507. return track.name === referenceTrack.name
  14508. && track.ValueTypeName === referenceTrackType;
  14509. } );
  14510. if ( targetTrack === undefined ) continue;
  14511. let referenceOffset = 0;
  14512. const referenceValueSize = referenceTrack.getValueSize();
  14513. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14514. referenceOffset = referenceValueSize / 3;
  14515. }
  14516. let targetOffset = 0;
  14517. const targetValueSize = targetTrack.getValueSize();
  14518. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14519. targetOffset = targetValueSize / 3;
  14520. }
  14521. const lastIndex = referenceTrack.times.length - 1;
  14522. let referenceValue;
  14523. // Find the value to subtract out of the track
  14524. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14525. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14526. const startIndex = referenceOffset;
  14527. const endIndex = referenceValueSize - referenceOffset;
  14528. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14529. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14530. // Reference frame is after the last keyframe, so just use the last keyframe
  14531. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14532. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14533. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14534. } else {
  14535. // Interpolate to the reference value
  14536. const interpolant = referenceTrack.createInterpolant();
  14537. const startIndex = referenceOffset;
  14538. const endIndex = referenceValueSize - referenceOffset;
  14539. interpolant.evaluate( referenceTime );
  14540. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14541. }
  14542. // Conjugate the quaternion
  14543. if ( referenceTrackType === 'quaternion' ) {
  14544. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14545. referenceQuat.toArray( referenceValue );
  14546. }
  14547. // Subtract the reference value from all of the track values
  14548. const numTimes = targetTrack.times.length;
  14549. for ( let j = 0; j < numTimes; ++ j ) {
  14550. const valueStart = j * targetValueSize + targetOffset;
  14551. if ( referenceTrackType === 'quaternion' ) {
  14552. // Multiply the conjugate for quaternion track types
  14553. Quaternion.multiplyQuaternionsFlat(
  14554. targetTrack.values,
  14555. valueStart,
  14556. referenceValue,
  14557. 0,
  14558. targetTrack.values,
  14559. valueStart
  14560. );
  14561. } else {
  14562. const valueEnd = targetValueSize - targetOffset * 2;
  14563. // Subtract each value for all other numeric track types
  14564. for ( let k = 0; k < valueEnd; ++ k ) {
  14565. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14566. }
  14567. }
  14568. }
  14569. }
  14570. targetClip.blendMode = AdditiveAnimationBlendMode;
  14571. return targetClip;
  14572. }
  14573. const AnimationUtils = {
  14574. convertArray: convertArray,
  14575. isTypedArray: isTypedArray,
  14576. getKeyframeOrder: getKeyframeOrder,
  14577. sortedArray: sortedArray,
  14578. flattenJSON: flattenJSON,
  14579. subclip: subclip,
  14580. makeClipAdditive: makeClipAdditive
  14581. };
  14582. /**
  14583. * Abstract base class of interpolants over parametric samples.
  14584. *
  14585. * The parameter domain is one dimensional, typically the time or a path
  14586. * along a curve defined by the data.
  14587. *
  14588. * The sample values can have any dimensionality and derived classes may
  14589. * apply special interpretations to the data.
  14590. *
  14591. * This class provides the interval seek in a Template Method, deferring
  14592. * the actual interpolation to derived classes.
  14593. *
  14594. * Time complexity is O(1) for linear access crossing at most two points
  14595. * and O(log N) for random access, where N is the number of positions.
  14596. *
  14597. * References:
  14598. *
  14599. * http://www.oodesign.com/template-method-pattern.html
  14600. *
  14601. */
  14602. class Interpolant {
  14603. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14604. this.parameterPositions = parameterPositions;
  14605. this._cachedIndex = 0;
  14606. this.resultBuffer = resultBuffer !== undefined ?
  14607. resultBuffer : new sampleValues.constructor( sampleSize );
  14608. this.sampleValues = sampleValues;
  14609. this.valueSize = sampleSize;
  14610. this.settings = null;
  14611. this.DefaultSettings_ = {};
  14612. }
  14613. evaluate( t ) {
  14614. const pp = this.parameterPositions;
  14615. let i1 = this._cachedIndex,
  14616. t1 = pp[ i1 ],
  14617. t0 = pp[ i1 - 1 ];
  14618. validate_interval: {
  14619. seek: {
  14620. let right;
  14621. linear_scan: {
  14622. //- See http://jsperf.com/comparison-to-undefined/3
  14623. //- slower code:
  14624. //-
  14625. //- if ( t >= t1 || t1 === undefined ) {
  14626. forward_scan: if ( ! ( t < t1 ) ) {
  14627. for ( let giveUpAt = i1 + 2; ; ) {
  14628. if ( t1 === undefined ) {
  14629. if ( t < t0 ) break forward_scan;
  14630. // after end
  14631. i1 = pp.length;
  14632. this._cachedIndex = i1;
  14633. return this.copySampleValue_( i1 - 1 );
  14634. }
  14635. if ( i1 === giveUpAt ) break; // this loop
  14636. t0 = t1;
  14637. t1 = pp[ ++ i1 ];
  14638. if ( t < t1 ) {
  14639. // we have arrived at the sought interval
  14640. break seek;
  14641. }
  14642. }
  14643. // prepare binary search on the right side of the index
  14644. right = pp.length;
  14645. break linear_scan;
  14646. }
  14647. //- slower code:
  14648. //- if ( t < t0 || t0 === undefined ) {
  14649. if ( ! ( t >= t0 ) ) {
  14650. // looping?
  14651. const t1global = pp[ 1 ];
  14652. if ( t < t1global ) {
  14653. i1 = 2; // + 1, using the scan for the details
  14654. t0 = t1global;
  14655. }
  14656. // linear reverse scan
  14657. for ( let giveUpAt = i1 - 2; ; ) {
  14658. if ( t0 === undefined ) {
  14659. // before start
  14660. this._cachedIndex = 0;
  14661. return this.copySampleValue_( 0 );
  14662. }
  14663. if ( i1 === giveUpAt ) break; // this loop
  14664. t1 = t0;
  14665. t0 = pp[ -- i1 - 1 ];
  14666. if ( t >= t0 ) {
  14667. // we have arrived at the sought interval
  14668. break seek;
  14669. }
  14670. }
  14671. // prepare binary search on the left side of the index
  14672. right = i1;
  14673. i1 = 0;
  14674. break linear_scan;
  14675. }
  14676. // the interval is valid
  14677. break validate_interval;
  14678. } // linear scan
  14679. // binary search
  14680. while ( i1 < right ) {
  14681. const mid = ( i1 + right ) >>> 1;
  14682. if ( t < pp[ mid ] ) {
  14683. right = mid;
  14684. } else {
  14685. i1 = mid + 1;
  14686. }
  14687. }
  14688. t1 = pp[ i1 ];
  14689. t0 = pp[ i1 - 1 ];
  14690. // check boundary cases, again
  14691. if ( t0 === undefined ) {
  14692. this._cachedIndex = 0;
  14693. return this.copySampleValue_( 0 );
  14694. }
  14695. if ( t1 === undefined ) {
  14696. i1 = pp.length;
  14697. this._cachedIndex = i1;
  14698. return this.copySampleValue_( i1 - 1 );
  14699. }
  14700. } // seek
  14701. this._cachedIndex = i1;
  14702. this.intervalChanged_( i1, t0, t1 );
  14703. } // validate_interval
  14704. return this.interpolate_( i1, t0, t, t1 );
  14705. }
  14706. getSettings_() {
  14707. return this.settings || this.DefaultSettings_;
  14708. }
  14709. copySampleValue_( index ) {
  14710. // copies a sample value to the result buffer
  14711. const result = this.resultBuffer,
  14712. values = this.sampleValues,
  14713. stride = this.valueSize,
  14714. offset = index * stride;
  14715. for ( let i = 0; i !== stride; ++ i ) {
  14716. result[ i ] = values[ offset + i ];
  14717. }
  14718. return result;
  14719. }
  14720. // Template methods for derived classes:
  14721. interpolate_( /* i1, t0, t, t1 */ ) {
  14722. throw new Error( 'call to abstract method' );
  14723. // implementations shall return this.resultBuffer
  14724. }
  14725. intervalChanged_( /* i1, t0, t1 */ ) {
  14726. // empty
  14727. }
  14728. }
  14729. /**
  14730. * Fast and simple cubic spline interpolant.
  14731. *
  14732. * It was derived from a Hermitian construction setting the first derivative
  14733. * at each sample position to the linear slope between neighboring positions
  14734. * over their parameter interval.
  14735. */
  14736. class CubicInterpolant extends Interpolant {
  14737. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14738. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14739. this._weightPrev = - 0;
  14740. this._offsetPrev = - 0;
  14741. this._weightNext = - 0;
  14742. this._offsetNext = - 0;
  14743. this.DefaultSettings_ = {
  14744. endingStart: ZeroCurvatureEnding,
  14745. endingEnd: ZeroCurvatureEnding
  14746. };
  14747. }
  14748. intervalChanged_( i1, t0, t1 ) {
  14749. const pp = this.parameterPositions;
  14750. let iPrev = i1 - 2,
  14751. iNext = i1 + 1,
  14752. tPrev = pp[ iPrev ],
  14753. tNext = pp[ iNext ];
  14754. if ( tPrev === undefined ) {
  14755. switch ( this.getSettings_().endingStart ) {
  14756. case ZeroSlopeEnding:
  14757. // f'(t0) = 0
  14758. iPrev = i1;
  14759. tPrev = 2 * t0 - t1;
  14760. break;
  14761. case WrapAroundEnding:
  14762. // use the other end of the curve
  14763. iPrev = pp.length - 2;
  14764. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  14765. break;
  14766. default: // ZeroCurvatureEnding
  14767. // f''(t0) = 0 a.k.a. Natural Spline
  14768. iPrev = i1;
  14769. tPrev = t1;
  14770. }
  14771. }
  14772. if ( tNext === undefined ) {
  14773. switch ( this.getSettings_().endingEnd ) {
  14774. case ZeroSlopeEnding:
  14775. // f'(tN) = 0
  14776. iNext = i1;
  14777. tNext = 2 * t1 - t0;
  14778. break;
  14779. case WrapAroundEnding:
  14780. // use the other end of the curve
  14781. iNext = 1;
  14782. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  14783. break;
  14784. default: // ZeroCurvatureEnding
  14785. // f''(tN) = 0, a.k.a. Natural Spline
  14786. iNext = i1 - 1;
  14787. tNext = t0;
  14788. }
  14789. }
  14790. const halfDt = ( t1 - t0 ) * 0.5,
  14791. stride = this.valueSize;
  14792. this._weightPrev = halfDt / ( t0 - tPrev );
  14793. this._weightNext = halfDt / ( tNext - t1 );
  14794. this._offsetPrev = iPrev * stride;
  14795. this._offsetNext = iNext * stride;
  14796. }
  14797. interpolate_( i1, t0, t, t1 ) {
  14798. const result = this.resultBuffer,
  14799. values = this.sampleValues,
  14800. stride = this.valueSize,
  14801. o1 = i1 * stride, o0 = o1 - stride,
  14802. oP = this._offsetPrev, oN = this._offsetNext,
  14803. wP = this._weightPrev, wN = this._weightNext,
  14804. p = ( t - t0 ) / ( t1 - t0 ),
  14805. pp = p * p,
  14806. ppp = pp * p;
  14807. // evaluate polynomials
  14808. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  14809. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  14810. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  14811. const sN = wN * ppp - wN * pp;
  14812. // combine data linearly
  14813. for ( let i = 0; i !== stride; ++ i ) {
  14814. result[ i ] =
  14815. sP * values[ oP + i ] +
  14816. s0 * values[ o0 + i ] +
  14817. s1 * values[ o1 + i ] +
  14818. sN * values[ oN + i ];
  14819. }
  14820. return result;
  14821. }
  14822. }
  14823. class LinearInterpolant extends Interpolant {
  14824. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14825. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14826. }
  14827. interpolate_( i1, t0, t, t1 ) {
  14828. const result = this.resultBuffer,
  14829. values = this.sampleValues,
  14830. stride = this.valueSize,
  14831. offset1 = i1 * stride,
  14832. offset0 = offset1 - stride,
  14833. weight1 = ( t - t0 ) / ( t1 - t0 ),
  14834. weight0 = 1 - weight1;
  14835. for ( let i = 0; i !== stride; ++ i ) {
  14836. result[ i ] =
  14837. values[ offset0 + i ] * weight0 +
  14838. values[ offset1 + i ] * weight1;
  14839. }
  14840. return result;
  14841. }
  14842. }
  14843. /**
  14844. *
  14845. * Interpolant that evaluates to the sample value at the position preceding
  14846. * the parameter.
  14847. */
  14848. class DiscreteInterpolant extends Interpolant {
  14849. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14850. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14851. }
  14852. interpolate_( i1 /*, t0, t, t1 */ ) {
  14853. return this.copySampleValue_( i1 - 1 );
  14854. }
  14855. }
  14856. class KeyframeTrack {
  14857. constructor( name, times, values, interpolation ) {
  14858. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  14859. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  14860. this.name = name;
  14861. this.times = convertArray( times, this.TimeBufferType );
  14862. this.values = convertArray( values, this.ValueBufferType );
  14863. this.setInterpolation( interpolation || this.DefaultInterpolation );
  14864. }
  14865. // Serialization (in static context, because of constructor invocation
  14866. // and automatic invocation of .toJSON):
  14867. static toJSON( track ) {
  14868. const trackType = track.constructor;
  14869. let json;
  14870. // derived classes can define a static toJSON method
  14871. if ( trackType.toJSON !== this.toJSON ) {
  14872. json = trackType.toJSON( track );
  14873. } else {
  14874. // by default, we assume the data can be serialized as-is
  14875. json = {
  14876. 'name': track.name,
  14877. 'times': convertArray( track.times, Array ),
  14878. 'values': convertArray( track.values, Array )
  14879. };
  14880. const interpolation = track.getInterpolation();
  14881. if ( interpolation !== track.DefaultInterpolation ) {
  14882. json.interpolation = interpolation;
  14883. }
  14884. }
  14885. json.type = track.ValueTypeName; // mandatory
  14886. return json;
  14887. }
  14888. InterpolantFactoryMethodDiscrete( result ) {
  14889. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  14890. }
  14891. InterpolantFactoryMethodLinear( result ) {
  14892. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  14893. }
  14894. InterpolantFactoryMethodSmooth( result ) {
  14895. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  14896. }
  14897. setInterpolation( interpolation ) {
  14898. let factoryMethod;
  14899. switch ( interpolation ) {
  14900. case InterpolateDiscrete:
  14901. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  14902. break;
  14903. case InterpolateLinear:
  14904. factoryMethod = this.InterpolantFactoryMethodLinear;
  14905. break;
  14906. case InterpolateSmooth:
  14907. factoryMethod = this.InterpolantFactoryMethodSmooth;
  14908. break;
  14909. }
  14910. if ( factoryMethod === undefined ) {
  14911. const message = 'unsupported interpolation for ' +
  14912. this.ValueTypeName + ' keyframe track named ' + this.name;
  14913. if ( this.createInterpolant === undefined ) {
  14914. // fall back to default, unless the default itself is messed up
  14915. if ( interpolation !== this.DefaultInterpolation ) {
  14916. this.setInterpolation( this.DefaultInterpolation );
  14917. } else {
  14918. throw new Error( message ); // fatal, in this case
  14919. }
  14920. }
  14921. console.warn( 'THREE.KeyframeTrack:', message );
  14922. return this;
  14923. }
  14924. this.createInterpolant = factoryMethod;
  14925. return this;
  14926. }
  14927. getInterpolation() {
  14928. switch ( this.createInterpolant ) {
  14929. case this.InterpolantFactoryMethodDiscrete:
  14930. return InterpolateDiscrete;
  14931. case this.InterpolantFactoryMethodLinear:
  14932. return InterpolateLinear;
  14933. case this.InterpolantFactoryMethodSmooth:
  14934. return InterpolateSmooth;
  14935. }
  14936. }
  14937. getValueSize() {
  14938. return this.values.length / this.times.length;
  14939. }
  14940. // move all keyframes either forwards or backwards in time
  14941. shift( timeOffset ) {
  14942. if ( timeOffset !== 0.0 ) {
  14943. const times = this.times;
  14944. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14945. times[ i ] += timeOffset;
  14946. }
  14947. }
  14948. return this;
  14949. }
  14950. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  14951. scale( timeScale ) {
  14952. if ( timeScale !== 1.0 ) {
  14953. const times = this.times;
  14954. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14955. times[ i ] *= timeScale;
  14956. }
  14957. }
  14958. return this;
  14959. }
  14960. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  14961. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  14962. trim( startTime, endTime ) {
  14963. const times = this.times,
  14964. nKeys = times.length;
  14965. let from = 0,
  14966. to = nKeys - 1;
  14967. while ( from !== nKeys && times[ from ] < startTime ) {
  14968. ++ from;
  14969. }
  14970. while ( to !== - 1 && times[ to ] > endTime ) {
  14971. -- to;
  14972. }
  14973. ++ to; // inclusive -> exclusive bound
  14974. if ( from !== 0 || to !== nKeys ) {
  14975. // empty tracks are forbidden, so keep at least one keyframe
  14976. if ( from >= to ) {
  14977. to = Math.max( to, 1 );
  14978. from = to - 1;
  14979. }
  14980. const stride = this.getValueSize();
  14981. this.times = times.slice( from, to );
  14982. this.values = this.values.slice( from * stride, to * stride );
  14983. }
  14984. return this;
  14985. }
  14986. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  14987. validate() {
  14988. let valid = true;
  14989. const valueSize = this.getValueSize();
  14990. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  14991. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  14992. valid = false;
  14993. }
  14994. const times = this.times,
  14995. values = this.values,
  14996. nKeys = times.length;
  14997. if ( nKeys === 0 ) {
  14998. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  14999. valid = false;
  15000. }
  15001. let prevTime = null;
  15002. for ( let i = 0; i !== nKeys; i ++ ) {
  15003. const currTime = times[ i ];
  15004. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15005. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15006. valid = false;
  15007. break;
  15008. }
  15009. if ( prevTime !== null && prevTime > currTime ) {
  15010. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15011. valid = false;
  15012. break;
  15013. }
  15014. prevTime = currTime;
  15015. }
  15016. if ( values !== undefined ) {
  15017. if ( isTypedArray( values ) ) {
  15018. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15019. const value = values[ i ];
  15020. if ( isNaN( value ) ) {
  15021. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15022. valid = false;
  15023. break;
  15024. }
  15025. }
  15026. }
  15027. }
  15028. return valid;
  15029. }
  15030. // removes equivalent sequential keys as common in morph target sequences
  15031. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15032. optimize() {
  15033. // times or values may be shared with other tracks, so overwriting is unsafe
  15034. const times = this.times.slice(),
  15035. values = this.values.slice(),
  15036. stride = this.getValueSize(),
  15037. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15038. lastIndex = times.length - 1;
  15039. let writeIndex = 1;
  15040. for ( let i = 1; i < lastIndex; ++ i ) {
  15041. let keep = false;
  15042. const time = times[ i ];
  15043. const timeNext = times[ i + 1 ];
  15044. // remove adjacent keyframes scheduled at the same time
  15045. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15046. if ( ! smoothInterpolation ) {
  15047. // remove unnecessary keyframes same as their neighbors
  15048. const offset = i * stride,
  15049. offsetP = offset - stride,
  15050. offsetN = offset + stride;
  15051. for ( let j = 0; j !== stride; ++ j ) {
  15052. const value = values[ offset + j ];
  15053. if ( value !== values[ offsetP + j ] ||
  15054. value !== values[ offsetN + j ] ) {
  15055. keep = true;
  15056. break;
  15057. }
  15058. }
  15059. } else {
  15060. keep = true;
  15061. }
  15062. }
  15063. // in-place compaction
  15064. if ( keep ) {
  15065. if ( i !== writeIndex ) {
  15066. times[ writeIndex ] = times[ i ];
  15067. const readOffset = i * stride,
  15068. writeOffset = writeIndex * stride;
  15069. for ( let j = 0; j !== stride; ++ j ) {
  15070. values[ writeOffset + j ] = values[ readOffset + j ];
  15071. }
  15072. }
  15073. ++ writeIndex;
  15074. }
  15075. }
  15076. // flush last keyframe (compaction looks ahead)
  15077. if ( lastIndex > 0 ) {
  15078. times[ writeIndex ] = times[ lastIndex ];
  15079. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15080. values[ writeOffset + j ] = values[ readOffset + j ];
  15081. }
  15082. ++ writeIndex;
  15083. }
  15084. if ( writeIndex !== times.length ) {
  15085. this.times = times.slice( 0, writeIndex );
  15086. this.values = values.slice( 0, writeIndex * stride );
  15087. } else {
  15088. this.times = times;
  15089. this.values = values;
  15090. }
  15091. return this;
  15092. }
  15093. clone() {
  15094. const times = this.times.slice();
  15095. const values = this.values.slice();
  15096. const TypedKeyframeTrack = this.constructor;
  15097. const track = new TypedKeyframeTrack( this.name, times, values );
  15098. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15099. track.createInterpolant = this.createInterpolant;
  15100. return track;
  15101. }
  15102. }
  15103. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15104. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15105. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15106. /**
  15107. * A Track of Boolean keyframe values.
  15108. */
  15109. class BooleanKeyframeTrack extends KeyframeTrack {
  15110. // No interpolation parameter because only InterpolateDiscrete is valid.
  15111. constructor( name, times, values ) {
  15112. super( name, times, values );
  15113. }
  15114. }
  15115. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15116. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15117. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15118. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15119. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15120. /**
  15121. * A Track of keyframe values that represent color.
  15122. */
  15123. class ColorKeyframeTrack extends KeyframeTrack {}
  15124. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15125. /**
  15126. * A Track of numeric keyframe values.
  15127. */
  15128. class NumberKeyframeTrack extends KeyframeTrack {}
  15129. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15130. /**
  15131. * Spherical linear unit quaternion interpolant.
  15132. */
  15133. class QuaternionLinearInterpolant extends Interpolant {
  15134. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15135. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15136. }
  15137. interpolate_( i1, t0, t, t1 ) {
  15138. const result = this.resultBuffer,
  15139. values = this.sampleValues,
  15140. stride = this.valueSize,
  15141. alpha = ( t - t0 ) / ( t1 - t0 );
  15142. let offset = i1 * stride;
  15143. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15144. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15145. }
  15146. return result;
  15147. }
  15148. }
  15149. /**
  15150. * A Track of quaternion keyframe values.
  15151. */
  15152. class QuaternionKeyframeTrack extends KeyframeTrack {
  15153. InterpolantFactoryMethodLinear( result ) {
  15154. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15155. }
  15156. }
  15157. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15158. // ValueBufferType is inherited
  15159. // DefaultInterpolation is inherited;
  15160. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15161. /**
  15162. * A Track that interpolates Strings
  15163. */
  15164. class StringKeyframeTrack extends KeyframeTrack {
  15165. // No interpolation parameter because only InterpolateDiscrete is valid.
  15166. constructor( name, times, values ) {
  15167. super( name, times, values );
  15168. }
  15169. }
  15170. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15171. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15172. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15173. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15174. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15175. /**
  15176. * A Track of vectored keyframe values.
  15177. */
  15178. class VectorKeyframeTrack extends KeyframeTrack {}
  15179. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15180. class AnimationClip {
  15181. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15182. this.name = name;
  15183. this.tracks = tracks;
  15184. this.duration = duration;
  15185. this.blendMode = blendMode;
  15186. this.uuid = generateUUID();
  15187. // this means it should figure out its duration by scanning the tracks
  15188. if ( this.duration < 0 ) {
  15189. this.resetDuration();
  15190. }
  15191. }
  15192. static parse( json ) {
  15193. const tracks = [],
  15194. jsonTracks = json.tracks,
  15195. frameTime = 1.0 / ( json.fps || 1.0 );
  15196. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15197. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15198. }
  15199. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15200. clip.uuid = json.uuid;
  15201. return clip;
  15202. }
  15203. static toJSON( clip ) {
  15204. const tracks = [],
  15205. clipTracks = clip.tracks;
  15206. const json = {
  15207. 'name': clip.name,
  15208. 'duration': clip.duration,
  15209. 'tracks': tracks,
  15210. 'uuid': clip.uuid,
  15211. 'blendMode': clip.blendMode
  15212. };
  15213. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15214. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15215. }
  15216. return json;
  15217. }
  15218. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15219. const numMorphTargets = morphTargetSequence.length;
  15220. const tracks = [];
  15221. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15222. let times = [];
  15223. let values = [];
  15224. times.push(
  15225. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15226. i,
  15227. ( i + 1 ) % numMorphTargets );
  15228. values.push( 0, 1, 0 );
  15229. const order = getKeyframeOrder( times );
  15230. times = sortedArray( times, 1, order );
  15231. values = sortedArray( values, 1, order );
  15232. // if there is a key at the first frame, duplicate it as the
  15233. // last frame as well for perfect loop.
  15234. if ( ! noLoop && times[ 0 ] === 0 ) {
  15235. times.push( numMorphTargets );
  15236. values.push( values[ 0 ] );
  15237. }
  15238. tracks.push(
  15239. new NumberKeyframeTrack(
  15240. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15241. times, values
  15242. ).scale( 1.0 / fps ) );
  15243. }
  15244. return new this( name, - 1, tracks );
  15245. }
  15246. static findByName( objectOrClipArray, name ) {
  15247. let clipArray = objectOrClipArray;
  15248. if ( ! Array.isArray( objectOrClipArray ) ) {
  15249. const o = objectOrClipArray;
  15250. clipArray = o.geometry && o.geometry.animations || o.animations;
  15251. }
  15252. for ( let i = 0; i < clipArray.length; i ++ ) {
  15253. if ( clipArray[ i ].name === name ) {
  15254. return clipArray[ i ];
  15255. }
  15256. }
  15257. return null;
  15258. }
  15259. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15260. const animationToMorphTargets = {};
  15261. // tested with https://regex101.com/ on trick sequences
  15262. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15263. const pattern = /^([\w-]*?)([\d]+)$/;
  15264. // sort morph target names into animation groups based
  15265. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15266. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15267. const morphTarget = morphTargets[ i ];
  15268. const parts = morphTarget.name.match( pattern );
  15269. if ( parts && parts.length > 1 ) {
  15270. const name = parts[ 1 ];
  15271. let animationMorphTargets = animationToMorphTargets[ name ];
  15272. if ( ! animationMorphTargets ) {
  15273. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15274. }
  15275. animationMorphTargets.push( morphTarget );
  15276. }
  15277. }
  15278. const clips = [];
  15279. for ( const name in animationToMorphTargets ) {
  15280. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15281. }
  15282. return clips;
  15283. }
  15284. // parse the animation.hierarchy format
  15285. static parseAnimation( animation, bones ) {
  15286. if ( ! animation ) {
  15287. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15288. return null;
  15289. }
  15290. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15291. // only return track if there are actually keys.
  15292. if ( animationKeys.length !== 0 ) {
  15293. const times = [];
  15294. const values = [];
  15295. flattenJSON( animationKeys, times, values, propertyName );
  15296. // empty keys are filtered out, so check again
  15297. if ( times.length !== 0 ) {
  15298. destTracks.push( new trackType( trackName, times, values ) );
  15299. }
  15300. }
  15301. };
  15302. const tracks = [];
  15303. const clipName = animation.name || 'default';
  15304. const fps = animation.fps || 30;
  15305. const blendMode = animation.blendMode;
  15306. // automatic length determination in AnimationClip.
  15307. let duration = animation.length || - 1;
  15308. const hierarchyTracks = animation.hierarchy || [];
  15309. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15310. const animationKeys = hierarchyTracks[ h ].keys;
  15311. // skip empty tracks
  15312. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15313. // process morph targets
  15314. if ( animationKeys[ 0 ].morphTargets ) {
  15315. // figure out all morph targets used in this track
  15316. const morphTargetNames = {};
  15317. let k;
  15318. for ( k = 0; k < animationKeys.length; k ++ ) {
  15319. if ( animationKeys[ k ].morphTargets ) {
  15320. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15321. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15322. }
  15323. }
  15324. }
  15325. // create a track for each morph target with all zero
  15326. // morphTargetInfluences except for the keys in which
  15327. // the morphTarget is named.
  15328. for ( const morphTargetName in morphTargetNames ) {
  15329. const times = [];
  15330. const values = [];
  15331. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15332. const animationKey = animationKeys[ k ];
  15333. times.push( animationKey.time );
  15334. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15335. }
  15336. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15337. }
  15338. duration = morphTargetNames.length * fps;
  15339. } else {
  15340. // ...assume skeletal animation
  15341. const boneName = '.bones[' + bones[ h ].name + ']';
  15342. addNonemptyTrack(
  15343. VectorKeyframeTrack, boneName + '.position',
  15344. animationKeys, 'pos', tracks );
  15345. addNonemptyTrack(
  15346. QuaternionKeyframeTrack, boneName + '.quaternion',
  15347. animationKeys, 'rot', tracks );
  15348. addNonemptyTrack(
  15349. VectorKeyframeTrack, boneName + '.scale',
  15350. animationKeys, 'scl', tracks );
  15351. }
  15352. }
  15353. if ( tracks.length === 0 ) {
  15354. return null;
  15355. }
  15356. const clip = new this( clipName, duration, tracks, blendMode );
  15357. return clip;
  15358. }
  15359. resetDuration() {
  15360. const tracks = this.tracks;
  15361. let duration = 0;
  15362. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15363. const track = this.tracks[ i ];
  15364. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15365. }
  15366. this.duration = duration;
  15367. return this;
  15368. }
  15369. trim() {
  15370. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15371. this.tracks[ i ].trim( 0, this.duration );
  15372. }
  15373. return this;
  15374. }
  15375. validate() {
  15376. let valid = true;
  15377. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15378. valid = valid && this.tracks[ i ].validate();
  15379. }
  15380. return valid;
  15381. }
  15382. optimize() {
  15383. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15384. this.tracks[ i ].optimize();
  15385. }
  15386. return this;
  15387. }
  15388. clone() {
  15389. const tracks = [];
  15390. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15391. tracks.push( this.tracks[ i ].clone() );
  15392. }
  15393. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15394. }
  15395. toJSON() {
  15396. return this.constructor.toJSON( this );
  15397. }
  15398. }
  15399. function getTrackTypeForValueTypeName( typeName ) {
  15400. switch ( typeName.toLowerCase() ) {
  15401. case 'scalar':
  15402. case 'double':
  15403. case 'float':
  15404. case 'number':
  15405. case 'integer':
  15406. return NumberKeyframeTrack;
  15407. case 'vector':
  15408. case 'vector2':
  15409. case 'vector3':
  15410. case 'vector4':
  15411. return VectorKeyframeTrack;
  15412. case 'color':
  15413. return ColorKeyframeTrack;
  15414. case 'quaternion':
  15415. return QuaternionKeyframeTrack;
  15416. case 'bool':
  15417. case 'boolean':
  15418. return BooleanKeyframeTrack;
  15419. case 'string':
  15420. return StringKeyframeTrack;
  15421. }
  15422. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15423. }
  15424. function parseKeyframeTrack( json ) {
  15425. if ( json.type === undefined ) {
  15426. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15427. }
  15428. const trackType = getTrackTypeForValueTypeName( json.type );
  15429. if ( json.times === undefined ) {
  15430. const times = [], values = [];
  15431. flattenJSON( json.keys, times, values, 'value' );
  15432. json.times = times;
  15433. json.values = values;
  15434. }
  15435. // derived classes can define a static parse method
  15436. if ( trackType.parse !== undefined ) {
  15437. return trackType.parse( json );
  15438. } else {
  15439. // by default, we assume a constructor compatible with the base
  15440. return new trackType( json.name, json.times, json.values, json.interpolation );
  15441. }
  15442. }
  15443. const Cache = {
  15444. enabled: false,
  15445. files: {},
  15446. add: function ( key, file ) {
  15447. if ( this.enabled === false ) return;
  15448. // console.log( 'THREE.Cache', 'Adding key:', key );
  15449. this.files[ key ] = file;
  15450. },
  15451. get: function ( key ) {
  15452. if ( this.enabled === false ) return;
  15453. // console.log( 'THREE.Cache', 'Checking key:', key );
  15454. return this.files[ key ];
  15455. },
  15456. remove: function ( key ) {
  15457. delete this.files[ key ];
  15458. },
  15459. clear: function () {
  15460. this.files = {};
  15461. }
  15462. };
  15463. class LoadingManager {
  15464. constructor( onLoad, onProgress, onError ) {
  15465. const scope = this;
  15466. let isLoading = false;
  15467. let itemsLoaded = 0;
  15468. let itemsTotal = 0;
  15469. let urlModifier = undefined;
  15470. const handlers = [];
  15471. // Refer to #5689 for the reason why we don't set .onStart
  15472. // in the constructor
  15473. this.onStart = undefined;
  15474. this.onLoad = onLoad;
  15475. this.onProgress = onProgress;
  15476. this.onError = onError;
  15477. this.itemStart = function ( url ) {
  15478. itemsTotal ++;
  15479. if ( isLoading === false ) {
  15480. if ( scope.onStart !== undefined ) {
  15481. scope.onStart( url, itemsLoaded, itemsTotal );
  15482. }
  15483. }
  15484. isLoading = true;
  15485. };
  15486. this.itemEnd = function ( url ) {
  15487. itemsLoaded ++;
  15488. if ( scope.onProgress !== undefined ) {
  15489. scope.onProgress( url, itemsLoaded, itemsTotal );
  15490. }
  15491. if ( itemsLoaded === itemsTotal ) {
  15492. isLoading = false;
  15493. if ( scope.onLoad !== undefined ) {
  15494. scope.onLoad();
  15495. }
  15496. }
  15497. };
  15498. this.itemError = function ( url ) {
  15499. if ( scope.onError !== undefined ) {
  15500. scope.onError( url );
  15501. }
  15502. };
  15503. this.resolveURL = function ( url ) {
  15504. if ( urlModifier ) {
  15505. return urlModifier( url );
  15506. }
  15507. return url;
  15508. };
  15509. this.setURLModifier = function ( transform ) {
  15510. urlModifier = transform;
  15511. return this;
  15512. };
  15513. this.addHandler = function ( regex, loader ) {
  15514. handlers.push( regex, loader );
  15515. return this;
  15516. };
  15517. this.removeHandler = function ( regex ) {
  15518. const index = handlers.indexOf( regex );
  15519. if ( index !== - 1 ) {
  15520. handlers.splice( index, 2 );
  15521. }
  15522. return this;
  15523. };
  15524. this.getHandler = function ( file ) {
  15525. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15526. const regex = handlers[ i ];
  15527. const loader = handlers[ i + 1 ];
  15528. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15529. if ( regex.test( file ) ) {
  15530. return loader;
  15531. }
  15532. }
  15533. return null;
  15534. };
  15535. }
  15536. }
  15537. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15538. class Loader {
  15539. constructor( manager ) {
  15540. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15541. this.crossOrigin = 'anonymous';
  15542. this.withCredentials = false;
  15543. this.path = '';
  15544. this.resourcePath = '';
  15545. this.requestHeader = {};
  15546. }
  15547. load( /* url, onLoad, onProgress, onError */ ) {}
  15548. loadAsync( url, onProgress ) {
  15549. const scope = this;
  15550. return new Promise( function ( resolve, reject ) {
  15551. scope.load( url, resolve, onProgress, reject );
  15552. } );
  15553. }
  15554. parse( /* data */ ) {}
  15555. setCrossOrigin( crossOrigin ) {
  15556. this.crossOrigin = crossOrigin;
  15557. return this;
  15558. }
  15559. setWithCredentials( value ) {
  15560. this.withCredentials = value;
  15561. return this;
  15562. }
  15563. setPath( path ) {
  15564. this.path = path;
  15565. return this;
  15566. }
  15567. setResourcePath( resourcePath ) {
  15568. this.resourcePath = resourcePath;
  15569. return this;
  15570. }
  15571. setRequestHeader( requestHeader ) {
  15572. this.requestHeader = requestHeader;
  15573. return this;
  15574. }
  15575. }
  15576. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15577. const loading = {};
  15578. class HttpError extends Error {
  15579. constructor( message, response ) {
  15580. super( message );
  15581. this.response = response;
  15582. }
  15583. }
  15584. class FileLoader extends Loader {
  15585. constructor( manager ) {
  15586. super( manager );
  15587. }
  15588. load( url, onLoad, onProgress, onError ) {
  15589. if ( url === undefined ) url = '';
  15590. if ( this.path !== undefined ) url = this.path + url;
  15591. url = this.manager.resolveURL( url );
  15592. const cached = Cache.get( url );
  15593. if ( cached !== undefined ) {
  15594. this.manager.itemStart( url );
  15595. setTimeout( () => {
  15596. if ( onLoad ) onLoad( cached );
  15597. this.manager.itemEnd( url );
  15598. }, 0 );
  15599. return cached;
  15600. }
  15601. // Check if request is duplicate
  15602. if ( loading[ url ] !== undefined ) {
  15603. loading[ url ].push( {
  15604. onLoad: onLoad,
  15605. onProgress: onProgress,
  15606. onError: onError
  15607. } );
  15608. return;
  15609. }
  15610. // Initialise array for duplicate requests
  15611. loading[ url ] = [];
  15612. loading[ url ].push( {
  15613. onLoad: onLoad,
  15614. onProgress: onProgress,
  15615. onError: onError,
  15616. } );
  15617. // create request
  15618. const req = new Request( url, {
  15619. headers: new Headers( this.requestHeader ),
  15620. credentials: this.withCredentials ? 'include' : 'same-origin',
  15621. // An abort controller could be added within a future PR
  15622. } );
  15623. // record states ( avoid data race )
  15624. const mimeType = this.mimeType;
  15625. const responseType = this.responseType;
  15626. // start the fetch
  15627. fetch( req )
  15628. .then( response => {
  15629. if ( response.status === 200 || response.status === 0 ) {
  15630. // Some browsers return HTTP Status 0 when using non-http protocol
  15631. // e.g. 'file://' or 'data://'. Handle as success.
  15632. if ( response.status === 0 ) {
  15633. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15634. }
  15635. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15636. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15637. return response;
  15638. }
  15639. const callbacks = loading[ url ];
  15640. const reader = response.body.getReader();
  15641. // Nginx needs X-File-Size check
  15642. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15643. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15644. const total = contentLength ? parseInt( contentLength ) : 0;
  15645. const lengthComputable = total !== 0;
  15646. let loaded = 0;
  15647. // periodically read data into the new stream tracking while download progress
  15648. const stream = new ReadableStream( {
  15649. start( controller ) {
  15650. readData();
  15651. function readData() {
  15652. reader.read().then( ( { done, value } ) => {
  15653. if ( done ) {
  15654. controller.close();
  15655. } else {
  15656. loaded += value.byteLength;
  15657. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15658. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15659. const callback = callbacks[ i ];
  15660. if ( callback.onProgress ) callback.onProgress( event );
  15661. }
  15662. controller.enqueue( value );
  15663. readData();
  15664. }
  15665. }, ( e ) => {
  15666. controller.error( e );
  15667. } );
  15668. }
  15669. }
  15670. } );
  15671. return new Response( stream );
  15672. } else {
  15673. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15674. }
  15675. } )
  15676. .then( response => {
  15677. switch ( responseType ) {
  15678. case 'arraybuffer':
  15679. return response.arrayBuffer();
  15680. case 'blob':
  15681. return response.blob();
  15682. case 'document':
  15683. return response.text()
  15684. .then( text => {
  15685. const parser = new DOMParser();
  15686. return parser.parseFromString( text, mimeType );
  15687. } );
  15688. case 'json':
  15689. return response.json();
  15690. default:
  15691. if ( mimeType === undefined ) {
  15692. return response.text();
  15693. } else {
  15694. // sniff encoding
  15695. const re = /charset="?([^;"\s]*)"?/i;
  15696. const exec = re.exec( mimeType );
  15697. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15698. const decoder = new TextDecoder( label );
  15699. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15700. }
  15701. }
  15702. } )
  15703. .then( data => {
  15704. // Add to cache only on HTTP success, so that we do not cache
  15705. // error response bodies as proper responses to requests.
  15706. Cache.add( url, data );
  15707. const callbacks = loading[ url ];
  15708. delete loading[ url ];
  15709. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15710. const callback = callbacks[ i ];
  15711. if ( callback.onLoad ) callback.onLoad( data );
  15712. }
  15713. } )
  15714. .catch( err => {
  15715. // Abort errors and other errors are handled the same
  15716. const callbacks = loading[ url ];
  15717. if ( callbacks === undefined ) {
  15718. // When onLoad was called and url was deleted in `loading`
  15719. this.manager.itemError( url );
  15720. throw err;
  15721. }
  15722. delete loading[ url ];
  15723. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15724. const callback = callbacks[ i ];
  15725. if ( callback.onError ) callback.onError( err );
  15726. }
  15727. this.manager.itemError( url );
  15728. } )
  15729. .finally( () => {
  15730. this.manager.itemEnd( url );
  15731. } );
  15732. this.manager.itemStart( url );
  15733. }
  15734. setResponseType( value ) {
  15735. this.responseType = value;
  15736. return this;
  15737. }
  15738. setMimeType( value ) {
  15739. this.mimeType = value;
  15740. return this;
  15741. }
  15742. }
  15743. class AnimationLoader extends Loader {
  15744. constructor( manager ) {
  15745. super( manager );
  15746. }
  15747. load( url, onLoad, onProgress, onError ) {
  15748. const scope = this;
  15749. const loader = new FileLoader( this.manager );
  15750. loader.setPath( this.path );
  15751. loader.setRequestHeader( this.requestHeader );
  15752. loader.setWithCredentials( this.withCredentials );
  15753. loader.load( url, function ( text ) {
  15754. try {
  15755. onLoad( scope.parse( JSON.parse( text ) ) );
  15756. } catch ( e ) {
  15757. if ( onError ) {
  15758. onError( e );
  15759. } else {
  15760. console.error( e );
  15761. }
  15762. scope.manager.itemError( url );
  15763. }
  15764. }, onProgress, onError );
  15765. }
  15766. parse( json ) {
  15767. const animations = [];
  15768. for ( let i = 0; i < json.length; i ++ ) {
  15769. const clip = AnimationClip.parse( json[ i ] );
  15770. animations.push( clip );
  15771. }
  15772. return animations;
  15773. }
  15774. }
  15775. /**
  15776. * Abstract Base class to block based textures loader (dds, pvr, ...)
  15777. *
  15778. * Sub classes have to implement the parse() method which will be used in load().
  15779. */
  15780. class CompressedTextureLoader extends Loader {
  15781. constructor( manager ) {
  15782. super( manager );
  15783. }
  15784. load( url, onLoad, onProgress, onError ) {
  15785. const scope = this;
  15786. const images = [];
  15787. const texture = new CompressedTexture();
  15788. const loader = new FileLoader( this.manager );
  15789. loader.setPath( this.path );
  15790. loader.setResponseType( 'arraybuffer' );
  15791. loader.setRequestHeader( this.requestHeader );
  15792. loader.setWithCredentials( scope.withCredentials );
  15793. let loaded = 0;
  15794. function loadTexture( i ) {
  15795. loader.load( url[ i ], function ( buffer ) {
  15796. const texDatas = scope.parse( buffer, true );
  15797. images[ i ] = {
  15798. width: texDatas.width,
  15799. height: texDatas.height,
  15800. format: texDatas.format,
  15801. mipmaps: texDatas.mipmaps
  15802. };
  15803. loaded += 1;
  15804. if ( loaded === 6 ) {
  15805. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  15806. texture.image = images;
  15807. texture.format = texDatas.format;
  15808. texture.needsUpdate = true;
  15809. if ( onLoad ) onLoad( texture );
  15810. }
  15811. }, onProgress, onError );
  15812. }
  15813. if ( Array.isArray( url ) ) {
  15814. for ( let i = 0, il = url.length; i < il; ++ i ) {
  15815. loadTexture( i );
  15816. }
  15817. } else {
  15818. // compressed cubemap texture stored in a single DDS file
  15819. loader.load( url, function ( buffer ) {
  15820. const texDatas = scope.parse( buffer, true );
  15821. if ( texDatas.isCubemap ) {
  15822. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  15823. for ( let f = 0; f < faces; f ++ ) {
  15824. images[ f ] = { mipmaps: [] };
  15825. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  15826. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  15827. images[ f ].format = texDatas.format;
  15828. images[ f ].width = texDatas.width;
  15829. images[ f ].height = texDatas.height;
  15830. }
  15831. }
  15832. texture.image = images;
  15833. } else {
  15834. texture.image.width = texDatas.width;
  15835. texture.image.height = texDatas.height;
  15836. texture.mipmaps = texDatas.mipmaps;
  15837. }
  15838. if ( texDatas.mipmapCount === 1 ) {
  15839. texture.minFilter = LinearFilter;
  15840. }
  15841. texture.format = texDatas.format;
  15842. texture.needsUpdate = true;
  15843. if ( onLoad ) onLoad( texture );
  15844. }, onProgress, onError );
  15845. }
  15846. return texture;
  15847. }
  15848. }
  15849. class ImageLoader extends Loader {
  15850. constructor( manager ) {
  15851. super( manager );
  15852. }
  15853. load( url, onLoad, onProgress, onError ) {
  15854. if ( this.path !== undefined ) url = this.path + url;
  15855. url = this.manager.resolveURL( url );
  15856. const scope = this;
  15857. const cached = Cache.get( url );
  15858. if ( cached !== undefined ) {
  15859. scope.manager.itemStart( url );
  15860. setTimeout( function () {
  15861. if ( onLoad ) onLoad( cached );
  15862. scope.manager.itemEnd( url );
  15863. }, 0 );
  15864. return cached;
  15865. }
  15866. const image = createElementNS( 'img' );
  15867. function onImageLoad() {
  15868. removeEventListeners();
  15869. Cache.add( url, this );
  15870. if ( onLoad ) onLoad( this );
  15871. scope.manager.itemEnd( url );
  15872. }
  15873. function onImageError( event ) {
  15874. removeEventListeners();
  15875. if ( onError ) onError( event );
  15876. scope.manager.itemError( url );
  15877. scope.manager.itemEnd( url );
  15878. }
  15879. function removeEventListeners() {
  15880. image.removeEventListener( 'load', onImageLoad, false );
  15881. image.removeEventListener( 'error', onImageError, false );
  15882. }
  15883. image.addEventListener( 'load', onImageLoad, false );
  15884. image.addEventListener( 'error', onImageError, false );
  15885. if ( url.slice( 0, 5 ) !== 'data:' ) {
  15886. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  15887. }
  15888. scope.manager.itemStart( url );
  15889. image.src = url;
  15890. return image;
  15891. }
  15892. }
  15893. class CubeTextureLoader extends Loader {
  15894. constructor( manager ) {
  15895. super( manager );
  15896. }
  15897. load( urls, onLoad, onProgress, onError ) {
  15898. const texture = new CubeTexture();
  15899. texture.colorSpace = SRGBColorSpace;
  15900. const loader = new ImageLoader( this.manager );
  15901. loader.setCrossOrigin( this.crossOrigin );
  15902. loader.setPath( this.path );
  15903. let loaded = 0;
  15904. function loadTexture( i ) {
  15905. loader.load( urls[ i ], function ( image ) {
  15906. texture.images[ i ] = image;
  15907. loaded ++;
  15908. if ( loaded === 6 ) {
  15909. texture.needsUpdate = true;
  15910. if ( onLoad ) onLoad( texture );
  15911. }
  15912. }, undefined, onError );
  15913. }
  15914. for ( let i = 0; i < urls.length; ++ i ) {
  15915. loadTexture( i );
  15916. }
  15917. return texture;
  15918. }
  15919. }
  15920. /**
  15921. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  15922. *
  15923. * Sub classes have to implement the parse() method which will be used in load().
  15924. */
  15925. class DataTextureLoader extends Loader {
  15926. constructor( manager ) {
  15927. super( manager );
  15928. }
  15929. load( url, onLoad, onProgress, onError ) {
  15930. const scope = this;
  15931. const texture = new DataTexture();
  15932. const loader = new FileLoader( this.manager );
  15933. loader.setResponseType( 'arraybuffer' );
  15934. loader.setRequestHeader( this.requestHeader );
  15935. loader.setPath( this.path );
  15936. loader.setWithCredentials( scope.withCredentials );
  15937. loader.load( url, function ( buffer ) {
  15938. let texData;
  15939. try {
  15940. texData = scope.parse( buffer );
  15941. } catch ( error ) {
  15942. if ( onError !== undefined ) {
  15943. onError( error );
  15944. } else {
  15945. console.error( error );
  15946. return;
  15947. }
  15948. }
  15949. if ( texData.image !== undefined ) {
  15950. texture.image = texData.image;
  15951. } else if ( texData.data !== undefined ) {
  15952. texture.image.width = texData.width;
  15953. texture.image.height = texData.height;
  15954. texture.image.data = texData.data;
  15955. }
  15956. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  15957. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  15958. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  15959. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  15960. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  15961. if ( texData.colorSpace !== undefined ) {
  15962. texture.colorSpace = texData.colorSpace;
  15963. }
  15964. if ( texData.flipY !== undefined ) {
  15965. texture.flipY = texData.flipY;
  15966. }
  15967. if ( texData.format !== undefined ) {
  15968. texture.format = texData.format;
  15969. }
  15970. if ( texData.type !== undefined ) {
  15971. texture.type = texData.type;
  15972. }
  15973. if ( texData.mipmaps !== undefined ) {
  15974. texture.mipmaps = texData.mipmaps;
  15975. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  15976. }
  15977. if ( texData.mipmapCount === 1 ) {
  15978. texture.minFilter = LinearFilter;
  15979. }
  15980. if ( texData.generateMipmaps !== undefined ) {
  15981. texture.generateMipmaps = texData.generateMipmaps;
  15982. }
  15983. texture.needsUpdate = true;
  15984. if ( onLoad ) onLoad( texture, texData );
  15985. }, onProgress, onError );
  15986. return texture;
  15987. }
  15988. }
  15989. class TextureLoader extends Loader {
  15990. constructor( manager ) {
  15991. super( manager );
  15992. }
  15993. load( url, onLoad, onProgress, onError ) {
  15994. const texture = new Texture();
  15995. const loader = new ImageLoader( this.manager );
  15996. loader.setCrossOrigin( this.crossOrigin );
  15997. loader.setPath( this.path );
  15998. loader.load( url, function ( image ) {
  15999. texture.image = image;
  16000. texture.needsUpdate = true;
  16001. if ( onLoad !== undefined ) {
  16002. onLoad( texture );
  16003. }
  16004. }, onProgress, onError );
  16005. return texture;
  16006. }
  16007. }
  16008. class Light extends Object3D {
  16009. constructor( color, intensity = 1 ) {
  16010. super();
  16011. this.isLight = true;
  16012. this.type = 'Light';
  16013. this.color = new Color( color );
  16014. this.intensity = intensity;
  16015. }
  16016. dispose() {
  16017. // Empty here in base class; some subclasses override.
  16018. }
  16019. copy( source, recursive ) {
  16020. super.copy( source, recursive );
  16021. this.color.copy( source.color );
  16022. this.intensity = source.intensity;
  16023. return this;
  16024. }
  16025. toJSON( meta ) {
  16026. const data = super.toJSON( meta );
  16027. data.object.color = this.color.getHex();
  16028. data.object.intensity = this.intensity;
  16029. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16030. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16031. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16032. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16033. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16034. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16035. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16036. return data;
  16037. }
  16038. }
  16039. class HemisphereLight extends Light {
  16040. constructor( skyColor, groundColor, intensity ) {
  16041. super( skyColor, intensity );
  16042. this.isHemisphereLight = true;
  16043. this.type = 'HemisphereLight';
  16044. this.position.copy( Object3D.DEFAULT_UP );
  16045. this.updateMatrix();
  16046. this.groundColor = new Color( groundColor );
  16047. }
  16048. copy( source, recursive ) {
  16049. super.copy( source, recursive );
  16050. this.groundColor.copy( source.groundColor );
  16051. return this;
  16052. }
  16053. }
  16054. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16055. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16056. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16057. class LightShadow {
  16058. constructor( camera ) {
  16059. this.camera = camera;
  16060. this.intensity = 1;
  16061. this.bias = 0;
  16062. this.normalBias = 0;
  16063. this.radius = 1;
  16064. this.blurSamples = 8;
  16065. this.mapSize = new Vector2( 512, 512 );
  16066. this.map = null;
  16067. this.mapPass = null;
  16068. this.matrix = new Matrix4();
  16069. this.autoUpdate = true;
  16070. this.needsUpdate = false;
  16071. this._frustum = new Frustum();
  16072. this._frameExtents = new Vector2( 1, 1 );
  16073. this._viewportCount = 1;
  16074. this._viewports = [
  16075. new Vector4( 0, 0, 1, 1 )
  16076. ];
  16077. }
  16078. getViewportCount() {
  16079. return this._viewportCount;
  16080. }
  16081. getFrustum() {
  16082. return this._frustum;
  16083. }
  16084. updateMatrices( light ) {
  16085. const shadowCamera = this.camera;
  16086. const shadowMatrix = this.matrix;
  16087. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16088. shadowCamera.position.copy( _lightPositionWorld$1 );
  16089. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16090. shadowCamera.lookAt( _lookTarget$1 );
  16091. shadowCamera.updateMatrixWorld();
  16092. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16093. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16094. shadowMatrix.set(
  16095. 0.5, 0.0, 0.0, 0.5,
  16096. 0.0, 0.5, 0.0, 0.5,
  16097. 0.0, 0.0, 0.5, 0.5,
  16098. 0.0, 0.0, 0.0, 1.0
  16099. );
  16100. shadowMatrix.multiply( _projScreenMatrix$2 );
  16101. }
  16102. getViewport( viewportIndex ) {
  16103. return this._viewports[ viewportIndex ];
  16104. }
  16105. getFrameExtents() {
  16106. return this._frameExtents;
  16107. }
  16108. dispose() {
  16109. if ( this.map ) {
  16110. this.map.dispose();
  16111. }
  16112. if ( this.mapPass ) {
  16113. this.mapPass.dispose();
  16114. }
  16115. }
  16116. copy( source ) {
  16117. this.camera = source.camera.clone();
  16118. this.intensity = source.intensity;
  16119. this.bias = source.bias;
  16120. this.radius = source.radius;
  16121. this.mapSize.copy( source.mapSize );
  16122. return this;
  16123. }
  16124. clone() {
  16125. return new this.constructor().copy( this );
  16126. }
  16127. toJSON() {
  16128. const object = {};
  16129. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16130. if ( this.bias !== 0 ) object.bias = this.bias;
  16131. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16132. if ( this.radius !== 1 ) object.radius = this.radius;
  16133. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16134. object.camera = this.camera.toJSON( false ).object;
  16135. delete object.camera.matrix;
  16136. return object;
  16137. }
  16138. }
  16139. class SpotLightShadow extends LightShadow {
  16140. constructor() {
  16141. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16142. this.isSpotLightShadow = true;
  16143. this.focus = 1;
  16144. }
  16145. updateMatrices( light ) {
  16146. const camera = this.camera;
  16147. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16148. const aspect = this.mapSize.width / this.mapSize.height;
  16149. const far = light.distance || camera.far;
  16150. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16151. camera.fov = fov;
  16152. camera.aspect = aspect;
  16153. camera.far = far;
  16154. camera.updateProjectionMatrix();
  16155. }
  16156. super.updateMatrices( light );
  16157. }
  16158. copy( source ) {
  16159. super.copy( source );
  16160. this.focus = source.focus;
  16161. return this;
  16162. }
  16163. }
  16164. class SpotLight extends Light {
  16165. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16166. super( color, intensity );
  16167. this.isSpotLight = true;
  16168. this.type = 'SpotLight';
  16169. this.position.copy( Object3D.DEFAULT_UP );
  16170. this.updateMatrix();
  16171. this.target = new Object3D();
  16172. this.distance = distance;
  16173. this.angle = angle;
  16174. this.penumbra = penumbra;
  16175. this.decay = decay;
  16176. this.map = null;
  16177. this.shadow = new SpotLightShadow();
  16178. }
  16179. get power() {
  16180. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16181. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16182. return this.intensity * Math.PI;
  16183. }
  16184. set power( power ) {
  16185. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16186. this.intensity = power / Math.PI;
  16187. }
  16188. dispose() {
  16189. this.shadow.dispose();
  16190. }
  16191. copy( source, recursive ) {
  16192. super.copy( source, recursive );
  16193. this.distance = source.distance;
  16194. this.angle = source.angle;
  16195. this.penumbra = source.penumbra;
  16196. this.decay = source.decay;
  16197. this.target = source.target.clone();
  16198. this.shadow = source.shadow.clone();
  16199. return this;
  16200. }
  16201. }
  16202. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16203. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16204. const _lookTarget = /*@__PURE__*/ new Vector3();
  16205. class PointLightShadow extends LightShadow {
  16206. constructor() {
  16207. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16208. this.isPointLightShadow = true;
  16209. this._frameExtents = new Vector2( 4, 2 );
  16210. this._viewportCount = 6;
  16211. this._viewports = [
  16212. // These viewports map a cube-map onto a 2D texture with the
  16213. // following orientation:
  16214. //
  16215. // xzXZ
  16216. // y Y
  16217. //
  16218. // X - Positive x direction
  16219. // x - Negative x direction
  16220. // Y - Positive y direction
  16221. // y - Negative y direction
  16222. // Z - Positive z direction
  16223. // z - Negative z direction
  16224. // positive X
  16225. new Vector4( 2, 1, 1, 1 ),
  16226. // negative X
  16227. new Vector4( 0, 1, 1, 1 ),
  16228. // positive Z
  16229. new Vector4( 3, 1, 1, 1 ),
  16230. // negative Z
  16231. new Vector4( 1, 1, 1, 1 ),
  16232. // positive Y
  16233. new Vector4( 3, 0, 1, 1 ),
  16234. // negative Y
  16235. new Vector4( 1, 0, 1, 1 )
  16236. ];
  16237. this._cubeDirections = [
  16238. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16239. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16240. ];
  16241. this._cubeUps = [
  16242. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16243. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16244. ];
  16245. }
  16246. updateMatrices( light, viewportIndex = 0 ) {
  16247. const camera = this.camera;
  16248. const shadowMatrix = this.matrix;
  16249. const far = light.distance || camera.far;
  16250. if ( far !== camera.far ) {
  16251. camera.far = far;
  16252. camera.updateProjectionMatrix();
  16253. }
  16254. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16255. camera.position.copy( _lightPositionWorld );
  16256. _lookTarget.copy( camera.position );
  16257. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16258. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16259. camera.lookAt( _lookTarget );
  16260. camera.updateMatrixWorld();
  16261. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16262. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16263. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16264. }
  16265. }
  16266. class PointLight extends Light {
  16267. constructor( color, intensity, distance = 0, decay = 2 ) {
  16268. super( color, intensity );
  16269. this.isPointLight = true;
  16270. this.type = 'PointLight';
  16271. this.distance = distance;
  16272. this.decay = decay;
  16273. this.shadow = new PointLightShadow();
  16274. }
  16275. get power() {
  16276. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16277. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16278. return this.intensity * 4 * Math.PI;
  16279. }
  16280. set power( power ) {
  16281. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16282. this.intensity = power / ( 4 * Math.PI );
  16283. }
  16284. dispose() {
  16285. this.shadow.dispose();
  16286. }
  16287. copy( source, recursive ) {
  16288. super.copy( source, recursive );
  16289. this.distance = source.distance;
  16290. this.decay = source.decay;
  16291. this.shadow = source.shadow.clone();
  16292. return this;
  16293. }
  16294. }
  16295. class OrthographicCamera extends Camera {
  16296. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16297. super();
  16298. this.isOrthographicCamera = true;
  16299. this.type = 'OrthographicCamera';
  16300. this.zoom = 1;
  16301. this.view = null;
  16302. this.left = left;
  16303. this.right = right;
  16304. this.top = top;
  16305. this.bottom = bottom;
  16306. this.near = near;
  16307. this.far = far;
  16308. this.updateProjectionMatrix();
  16309. }
  16310. copy( source, recursive ) {
  16311. super.copy( source, recursive );
  16312. this.left = source.left;
  16313. this.right = source.right;
  16314. this.top = source.top;
  16315. this.bottom = source.bottom;
  16316. this.near = source.near;
  16317. this.far = source.far;
  16318. this.zoom = source.zoom;
  16319. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16320. return this;
  16321. }
  16322. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16323. if ( this.view === null ) {
  16324. this.view = {
  16325. enabled: true,
  16326. fullWidth: 1,
  16327. fullHeight: 1,
  16328. offsetX: 0,
  16329. offsetY: 0,
  16330. width: 1,
  16331. height: 1
  16332. };
  16333. }
  16334. this.view.enabled = true;
  16335. this.view.fullWidth = fullWidth;
  16336. this.view.fullHeight = fullHeight;
  16337. this.view.offsetX = x;
  16338. this.view.offsetY = y;
  16339. this.view.width = width;
  16340. this.view.height = height;
  16341. this.updateProjectionMatrix();
  16342. }
  16343. clearViewOffset() {
  16344. if ( this.view !== null ) {
  16345. this.view.enabled = false;
  16346. }
  16347. this.updateProjectionMatrix();
  16348. }
  16349. updateProjectionMatrix() {
  16350. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16351. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16352. const cx = ( this.right + this.left ) / 2;
  16353. const cy = ( this.top + this.bottom ) / 2;
  16354. let left = cx - dx;
  16355. let right = cx + dx;
  16356. let top = cy + dy;
  16357. let bottom = cy - dy;
  16358. if ( this.view !== null && this.view.enabled ) {
  16359. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16360. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16361. left += scaleW * this.view.offsetX;
  16362. right = left + scaleW * this.view.width;
  16363. top -= scaleH * this.view.offsetY;
  16364. bottom = top - scaleH * this.view.height;
  16365. }
  16366. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16367. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16368. }
  16369. toJSON( meta ) {
  16370. const data = super.toJSON( meta );
  16371. data.object.zoom = this.zoom;
  16372. data.object.left = this.left;
  16373. data.object.right = this.right;
  16374. data.object.top = this.top;
  16375. data.object.bottom = this.bottom;
  16376. data.object.near = this.near;
  16377. data.object.far = this.far;
  16378. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16379. return data;
  16380. }
  16381. }
  16382. class DirectionalLightShadow extends LightShadow {
  16383. constructor() {
  16384. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16385. this.isDirectionalLightShadow = true;
  16386. }
  16387. }
  16388. class DirectionalLight extends Light {
  16389. constructor( color, intensity ) {
  16390. super( color, intensity );
  16391. this.isDirectionalLight = true;
  16392. this.type = 'DirectionalLight';
  16393. this.position.copy( Object3D.DEFAULT_UP );
  16394. this.updateMatrix();
  16395. this.target = new Object3D();
  16396. this.shadow = new DirectionalLightShadow();
  16397. }
  16398. dispose() {
  16399. this.shadow.dispose();
  16400. }
  16401. copy( source ) {
  16402. super.copy( source );
  16403. this.target = source.target.clone();
  16404. this.shadow = source.shadow.clone();
  16405. return this;
  16406. }
  16407. }
  16408. class AmbientLight extends Light {
  16409. constructor( color, intensity ) {
  16410. super( color, intensity );
  16411. this.isAmbientLight = true;
  16412. this.type = 'AmbientLight';
  16413. }
  16414. }
  16415. class RectAreaLight extends Light {
  16416. constructor( color, intensity, width = 10, height = 10 ) {
  16417. super( color, intensity );
  16418. this.isRectAreaLight = true;
  16419. this.type = 'RectAreaLight';
  16420. this.width = width;
  16421. this.height = height;
  16422. }
  16423. get power() {
  16424. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16425. return this.intensity * this.width * this.height * Math.PI;
  16426. }
  16427. set power( power ) {
  16428. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16429. this.intensity = power / ( this.width * this.height * Math.PI );
  16430. }
  16431. copy( source ) {
  16432. super.copy( source );
  16433. this.width = source.width;
  16434. this.height = source.height;
  16435. return this;
  16436. }
  16437. toJSON( meta ) {
  16438. const data = super.toJSON( meta );
  16439. data.object.width = this.width;
  16440. data.object.height = this.height;
  16441. return data;
  16442. }
  16443. }
  16444. /**
  16445. * Primary reference:
  16446. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16447. *
  16448. * Secondary reference:
  16449. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16450. */
  16451. // 3-band SH defined by 9 coefficients
  16452. class SphericalHarmonics3 {
  16453. constructor() {
  16454. this.isSphericalHarmonics3 = true;
  16455. this.coefficients = [];
  16456. for ( let i = 0; i < 9; i ++ ) {
  16457. this.coefficients.push( new Vector3() );
  16458. }
  16459. }
  16460. set( coefficients ) {
  16461. for ( let i = 0; i < 9; i ++ ) {
  16462. this.coefficients[ i ].copy( coefficients[ i ] );
  16463. }
  16464. return this;
  16465. }
  16466. zero() {
  16467. for ( let i = 0; i < 9; i ++ ) {
  16468. this.coefficients[ i ].set( 0, 0, 0 );
  16469. }
  16470. return this;
  16471. }
  16472. // get the radiance in the direction of the normal
  16473. // target is a Vector3
  16474. getAt( normal, target ) {
  16475. // normal is assumed to be unit length
  16476. const x = normal.x, y = normal.y, z = normal.z;
  16477. const coeff = this.coefficients;
  16478. // band 0
  16479. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16480. // band 1
  16481. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16482. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16483. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16484. // band 2
  16485. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16486. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16487. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16488. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16489. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16490. return target;
  16491. }
  16492. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16493. // target is a Vector3
  16494. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16495. getIrradianceAt( normal, target ) {
  16496. // normal is assumed to be unit length
  16497. const x = normal.x, y = normal.y, z = normal.z;
  16498. const coeff = this.coefficients;
  16499. // band 0
  16500. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16501. // band 1
  16502. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16503. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16504. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16505. // band 2
  16506. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16507. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16508. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16509. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16510. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16511. return target;
  16512. }
  16513. add( sh ) {
  16514. for ( let i = 0; i < 9; i ++ ) {
  16515. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16516. }
  16517. return this;
  16518. }
  16519. addScaledSH( sh, s ) {
  16520. for ( let i = 0; i < 9; i ++ ) {
  16521. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16522. }
  16523. return this;
  16524. }
  16525. scale( s ) {
  16526. for ( let i = 0; i < 9; i ++ ) {
  16527. this.coefficients[ i ].multiplyScalar( s );
  16528. }
  16529. return this;
  16530. }
  16531. lerp( sh, alpha ) {
  16532. for ( let i = 0; i < 9; i ++ ) {
  16533. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16534. }
  16535. return this;
  16536. }
  16537. equals( sh ) {
  16538. for ( let i = 0; i < 9; i ++ ) {
  16539. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16540. return false;
  16541. }
  16542. }
  16543. return true;
  16544. }
  16545. copy( sh ) {
  16546. return this.set( sh.coefficients );
  16547. }
  16548. clone() {
  16549. return new this.constructor().copy( this );
  16550. }
  16551. fromArray( array, offset = 0 ) {
  16552. const coefficients = this.coefficients;
  16553. for ( let i = 0; i < 9; i ++ ) {
  16554. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16555. }
  16556. return this;
  16557. }
  16558. toArray( array = [], offset = 0 ) {
  16559. const coefficients = this.coefficients;
  16560. for ( let i = 0; i < 9; i ++ ) {
  16561. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16562. }
  16563. return array;
  16564. }
  16565. // evaluate the basis functions
  16566. // shBasis is an Array[ 9 ]
  16567. static getBasisAt( normal, shBasis ) {
  16568. // normal is assumed to be unit length
  16569. const x = normal.x, y = normal.y, z = normal.z;
  16570. // band 0
  16571. shBasis[ 0 ] = 0.282095;
  16572. // band 1
  16573. shBasis[ 1 ] = 0.488603 * y;
  16574. shBasis[ 2 ] = 0.488603 * z;
  16575. shBasis[ 3 ] = 0.488603 * x;
  16576. // band 2
  16577. shBasis[ 4 ] = 1.092548 * x * y;
  16578. shBasis[ 5 ] = 1.092548 * y * z;
  16579. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16580. shBasis[ 7 ] = 1.092548 * x * z;
  16581. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16582. }
  16583. }
  16584. class LightProbe extends Light {
  16585. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16586. super( undefined, intensity );
  16587. this.isLightProbe = true;
  16588. this.sh = sh;
  16589. }
  16590. copy( source ) {
  16591. super.copy( source );
  16592. this.sh.copy( source.sh );
  16593. return this;
  16594. }
  16595. fromJSON( json ) {
  16596. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16597. this.sh.fromArray( json.sh );
  16598. return this;
  16599. }
  16600. toJSON( meta ) {
  16601. const data = super.toJSON( meta );
  16602. data.object.sh = this.sh.toArray();
  16603. return data;
  16604. }
  16605. }
  16606. class MaterialLoader extends Loader {
  16607. constructor( manager ) {
  16608. super( manager );
  16609. this.textures = {};
  16610. }
  16611. load( url, onLoad, onProgress, onError ) {
  16612. const scope = this;
  16613. const loader = new FileLoader( scope.manager );
  16614. loader.setPath( scope.path );
  16615. loader.setRequestHeader( scope.requestHeader );
  16616. loader.setWithCredentials( scope.withCredentials );
  16617. loader.load( url, function ( text ) {
  16618. try {
  16619. onLoad( scope.parse( JSON.parse( text ) ) );
  16620. } catch ( e ) {
  16621. if ( onError ) {
  16622. onError( e );
  16623. } else {
  16624. console.error( e );
  16625. }
  16626. scope.manager.itemError( url );
  16627. }
  16628. }, onProgress, onError );
  16629. }
  16630. parse( json ) {
  16631. const textures = this.textures;
  16632. function getTexture( name ) {
  16633. if ( textures[ name ] === undefined ) {
  16634. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16635. }
  16636. return textures[ name ];
  16637. }
  16638. const material = MaterialLoader.createMaterialFromType( json.type );
  16639. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16640. if ( json.name !== undefined ) material.name = json.name;
  16641. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16642. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16643. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16644. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16645. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16646. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16647. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16648. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16649. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16650. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16651. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16652. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16653. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16654. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16655. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16656. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16657. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16658. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16659. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16660. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16661. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16662. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16663. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16664. if ( json.fog !== undefined ) material.fog = json.fog;
  16665. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16666. if ( json.blending !== undefined ) material.blending = json.blending;
  16667. if ( json.combine !== undefined ) material.combine = json.combine;
  16668. if ( json.side !== undefined ) material.side = json.side;
  16669. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16670. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16671. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16672. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16673. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16674. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16675. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16676. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16677. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16678. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16679. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16680. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16681. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16682. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16683. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16684. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16685. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16686. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16687. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16688. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16689. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16690. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16691. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16692. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16693. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16694. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16695. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16696. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16697. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16698. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16699. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16700. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16701. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16702. if ( json.scale !== undefined ) material.scale = json.scale;
  16703. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16704. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16705. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16706. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16707. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16708. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16709. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16710. if ( json.visible !== undefined ) material.visible = json.visible;
  16711. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16712. if ( json.userData !== undefined ) material.userData = json.userData;
  16713. if ( json.vertexColors !== undefined ) {
  16714. if ( typeof json.vertexColors === 'number' ) {
  16715. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16716. } else {
  16717. material.vertexColors = json.vertexColors;
  16718. }
  16719. }
  16720. // Shader Material
  16721. if ( json.uniforms !== undefined ) {
  16722. for ( const name in json.uniforms ) {
  16723. const uniform = json.uniforms[ name ];
  16724. material.uniforms[ name ] = {};
  16725. switch ( uniform.type ) {
  16726. case 't':
  16727. material.uniforms[ name ].value = getTexture( uniform.value );
  16728. break;
  16729. case 'c':
  16730. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16731. break;
  16732. case 'v2':
  16733. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16734. break;
  16735. case 'v3':
  16736. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16737. break;
  16738. case 'v4':
  16739. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  16740. break;
  16741. case 'm3':
  16742. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  16743. break;
  16744. case 'm4':
  16745. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  16746. break;
  16747. default:
  16748. material.uniforms[ name ].value = uniform.value;
  16749. }
  16750. }
  16751. }
  16752. if ( json.defines !== undefined ) material.defines = json.defines;
  16753. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16754. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16755. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  16756. if ( json.extensions !== undefined ) {
  16757. for ( const key in json.extensions ) {
  16758. material.extensions[ key ] = json.extensions[ key ];
  16759. }
  16760. }
  16761. if ( json.lights !== undefined ) material.lights = json.lights;
  16762. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  16763. // for PointsMaterial
  16764. if ( json.size !== undefined ) material.size = json.size;
  16765. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16766. // maps
  16767. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16768. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  16769. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  16770. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16771. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16772. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16773. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  16774. if ( json.normalScale !== undefined ) {
  16775. let normalScale = json.normalScale;
  16776. if ( Array.isArray( normalScale ) === false ) {
  16777. // Blender exporter used to export a scalar. See #7459
  16778. normalScale = [ normalScale, normalScale ];
  16779. }
  16780. material.normalScale = new Vector2().fromArray( normalScale );
  16781. }
  16782. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16783. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16784. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16785. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16786. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16787. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16788. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16789. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16790. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  16791. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  16792. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16793. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  16794. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  16795. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16796. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  16797. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16798. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16799. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16800. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16801. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  16802. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  16803. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  16804. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  16805. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16806. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  16807. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  16808. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  16809. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  16810. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  16811. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  16812. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  16813. return material;
  16814. }
  16815. setTextures( value ) {
  16816. this.textures = value;
  16817. return this;
  16818. }
  16819. static createMaterialFromType( type ) {
  16820. const materialLib = {
  16821. ShadowMaterial,
  16822. SpriteMaterial,
  16823. RawShaderMaterial,
  16824. ShaderMaterial,
  16825. PointsMaterial,
  16826. MeshPhysicalMaterial,
  16827. MeshStandardMaterial,
  16828. MeshPhongMaterial,
  16829. MeshToonMaterial,
  16830. MeshNormalMaterial,
  16831. MeshLambertMaterial,
  16832. MeshDepthMaterial,
  16833. MeshDistanceMaterial,
  16834. MeshBasicMaterial,
  16835. MeshMatcapMaterial,
  16836. LineDashedMaterial,
  16837. LineBasicMaterial,
  16838. Material
  16839. };
  16840. return new materialLib[ type ]();
  16841. }
  16842. }
  16843. class LoaderUtils {
  16844. static decodeText( array ) { // @deprecated, r165
  16845. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  16846. if ( typeof TextDecoder !== 'undefined' ) {
  16847. return new TextDecoder().decode( array );
  16848. }
  16849. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  16850. // throws a "maximum call stack size exceeded" error for large arrays.
  16851. let s = '';
  16852. for ( let i = 0, il = array.length; i < il; i ++ ) {
  16853. // Implicitly assumes little-endian.
  16854. s += String.fromCharCode( array[ i ] );
  16855. }
  16856. try {
  16857. // merges multi-byte utf-8 characters.
  16858. return decodeURIComponent( escape( s ) );
  16859. } catch ( e ) { // see #16358
  16860. return s;
  16861. }
  16862. }
  16863. static extractUrlBase( url ) {
  16864. const index = url.lastIndexOf( '/' );
  16865. if ( index === - 1 ) return './';
  16866. return url.slice( 0, index + 1 );
  16867. }
  16868. static resolveURL( url, path ) {
  16869. // Invalid URL
  16870. if ( typeof url !== 'string' || url === '' ) return '';
  16871. // Host Relative URL
  16872. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  16873. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  16874. }
  16875. // Absolute URL http://,https://,//
  16876. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  16877. // Data URI
  16878. if ( /^data:.*,.*$/i.test( url ) ) return url;
  16879. // Blob URL
  16880. if ( /^blob:.*$/i.test( url ) ) return url;
  16881. // Relative URL
  16882. return path + url;
  16883. }
  16884. }
  16885. class InstancedBufferGeometry extends BufferGeometry {
  16886. constructor() {
  16887. super();
  16888. this.isInstancedBufferGeometry = true;
  16889. this.type = 'InstancedBufferGeometry';
  16890. this.instanceCount = Infinity;
  16891. }
  16892. copy( source ) {
  16893. super.copy( source );
  16894. this.instanceCount = source.instanceCount;
  16895. return this;
  16896. }
  16897. toJSON() {
  16898. const data = super.toJSON();
  16899. data.instanceCount = this.instanceCount;
  16900. data.isInstancedBufferGeometry = true;
  16901. return data;
  16902. }
  16903. }
  16904. class BufferGeometryLoader extends Loader {
  16905. constructor( manager ) {
  16906. super( manager );
  16907. }
  16908. load( url, onLoad, onProgress, onError ) {
  16909. const scope = this;
  16910. const loader = new FileLoader( scope.manager );
  16911. loader.setPath( scope.path );
  16912. loader.setRequestHeader( scope.requestHeader );
  16913. loader.setWithCredentials( scope.withCredentials );
  16914. loader.load( url, function ( text ) {
  16915. try {
  16916. onLoad( scope.parse( JSON.parse( text ) ) );
  16917. } catch ( e ) {
  16918. if ( onError ) {
  16919. onError( e );
  16920. } else {
  16921. console.error( e );
  16922. }
  16923. scope.manager.itemError( url );
  16924. }
  16925. }, onProgress, onError );
  16926. }
  16927. parse( json ) {
  16928. const interleavedBufferMap = {};
  16929. const arrayBufferMap = {};
  16930. function getInterleavedBuffer( json, uuid ) {
  16931. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  16932. const interleavedBuffers = json.interleavedBuffers;
  16933. const interleavedBuffer = interleavedBuffers[ uuid ];
  16934. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  16935. const array = getTypedArray( interleavedBuffer.type, buffer );
  16936. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  16937. ib.uuid = interleavedBuffer.uuid;
  16938. interleavedBufferMap[ uuid ] = ib;
  16939. return ib;
  16940. }
  16941. function getArrayBuffer( json, uuid ) {
  16942. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  16943. const arrayBuffers = json.arrayBuffers;
  16944. const arrayBuffer = arrayBuffers[ uuid ];
  16945. const ab = new Uint32Array( arrayBuffer ).buffer;
  16946. arrayBufferMap[ uuid ] = ab;
  16947. return ab;
  16948. }
  16949. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  16950. const index = json.data.index;
  16951. if ( index !== undefined ) {
  16952. const typedArray = getTypedArray( index.type, index.array );
  16953. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16954. }
  16955. const attributes = json.data.attributes;
  16956. for ( const key in attributes ) {
  16957. const attribute = attributes[ key ];
  16958. let bufferAttribute;
  16959. if ( attribute.isInterleavedBufferAttribute ) {
  16960. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16961. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16962. } else {
  16963. const typedArray = getTypedArray( attribute.type, attribute.array );
  16964. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  16965. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  16966. }
  16967. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16968. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  16969. geometry.setAttribute( key, bufferAttribute );
  16970. }
  16971. const morphAttributes = json.data.morphAttributes;
  16972. if ( morphAttributes ) {
  16973. for ( const key in morphAttributes ) {
  16974. const attributeArray = morphAttributes[ key ];
  16975. const array = [];
  16976. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  16977. const attribute = attributeArray[ i ];
  16978. let bufferAttribute;
  16979. if ( attribute.isInterleavedBufferAttribute ) {
  16980. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16981. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16982. } else {
  16983. const typedArray = getTypedArray( attribute.type, attribute.array );
  16984. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  16985. }
  16986. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16987. array.push( bufferAttribute );
  16988. }
  16989. geometry.morphAttributes[ key ] = array;
  16990. }
  16991. }
  16992. const morphTargetsRelative = json.data.morphTargetsRelative;
  16993. if ( morphTargetsRelative ) {
  16994. geometry.morphTargetsRelative = true;
  16995. }
  16996. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  16997. if ( groups !== undefined ) {
  16998. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  16999. const group = groups[ i ];
  17000. geometry.addGroup( group.start, group.count, group.materialIndex );
  17001. }
  17002. }
  17003. const boundingSphere = json.data.boundingSphere;
  17004. if ( boundingSphere !== undefined ) {
  17005. const center = new Vector3();
  17006. if ( boundingSphere.center !== undefined ) {
  17007. center.fromArray( boundingSphere.center );
  17008. }
  17009. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17010. }
  17011. if ( json.name ) geometry.name = json.name;
  17012. if ( json.userData ) geometry.userData = json.userData;
  17013. return geometry;
  17014. }
  17015. }
  17016. class ObjectLoader extends Loader {
  17017. constructor( manager ) {
  17018. super( manager );
  17019. }
  17020. load( url, onLoad, onProgress, onError ) {
  17021. const scope = this;
  17022. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17023. this.resourcePath = this.resourcePath || path;
  17024. const loader = new FileLoader( this.manager );
  17025. loader.setPath( this.path );
  17026. loader.setRequestHeader( this.requestHeader );
  17027. loader.setWithCredentials( this.withCredentials );
  17028. loader.load( url, function ( text ) {
  17029. let json = null;
  17030. try {
  17031. json = JSON.parse( text );
  17032. } catch ( error ) {
  17033. if ( onError !== undefined ) onError( error );
  17034. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17035. return;
  17036. }
  17037. const metadata = json.metadata;
  17038. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17039. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17040. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17041. return;
  17042. }
  17043. scope.parse( json, onLoad );
  17044. }, onProgress, onError );
  17045. }
  17046. async loadAsync( url, onProgress ) {
  17047. const scope = this;
  17048. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17049. this.resourcePath = this.resourcePath || path;
  17050. const loader = new FileLoader( this.manager );
  17051. loader.setPath( this.path );
  17052. loader.setRequestHeader( this.requestHeader );
  17053. loader.setWithCredentials( this.withCredentials );
  17054. const text = await loader.loadAsync( url, onProgress );
  17055. const json = JSON.parse( text );
  17056. const metadata = json.metadata;
  17057. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17058. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17059. }
  17060. return await scope.parseAsync( json );
  17061. }
  17062. parse( json, onLoad ) {
  17063. const animations = this.parseAnimations( json.animations );
  17064. const shapes = this.parseShapes( json.shapes );
  17065. const geometries = this.parseGeometries( json.geometries, shapes );
  17066. const images = this.parseImages( json.images, function () {
  17067. if ( onLoad !== undefined ) onLoad( object );
  17068. } );
  17069. const textures = this.parseTextures( json.textures, images );
  17070. const materials = this.parseMaterials( json.materials, textures );
  17071. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17072. const skeletons = this.parseSkeletons( json.skeletons, object );
  17073. this.bindSkeletons( object, skeletons );
  17074. this.bindLightTargets( object );
  17075. //
  17076. if ( onLoad !== undefined ) {
  17077. let hasImages = false;
  17078. for ( const uuid in images ) {
  17079. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17080. hasImages = true;
  17081. break;
  17082. }
  17083. }
  17084. if ( hasImages === false ) onLoad( object );
  17085. }
  17086. return object;
  17087. }
  17088. async parseAsync( json ) {
  17089. const animations = this.parseAnimations( json.animations );
  17090. const shapes = this.parseShapes( json.shapes );
  17091. const geometries = this.parseGeometries( json.geometries, shapes );
  17092. const images = await this.parseImagesAsync( json.images );
  17093. const textures = this.parseTextures( json.textures, images );
  17094. const materials = this.parseMaterials( json.materials, textures );
  17095. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17096. const skeletons = this.parseSkeletons( json.skeletons, object );
  17097. this.bindSkeletons( object, skeletons );
  17098. this.bindLightTargets( object );
  17099. return object;
  17100. }
  17101. parseShapes( json ) {
  17102. const shapes = {};
  17103. if ( json !== undefined ) {
  17104. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17105. const shape = new Shape().fromJSON( json[ i ] );
  17106. shapes[ shape.uuid ] = shape;
  17107. }
  17108. }
  17109. return shapes;
  17110. }
  17111. parseSkeletons( json, object ) {
  17112. const skeletons = {};
  17113. const bones = {};
  17114. // generate bone lookup table
  17115. object.traverse( function ( child ) {
  17116. if ( child.isBone ) bones[ child.uuid ] = child;
  17117. } );
  17118. // create skeletons
  17119. if ( json !== undefined ) {
  17120. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17121. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17122. skeletons[ skeleton.uuid ] = skeleton;
  17123. }
  17124. }
  17125. return skeletons;
  17126. }
  17127. parseGeometries( json, shapes ) {
  17128. const geometries = {};
  17129. if ( json !== undefined ) {
  17130. const bufferGeometryLoader = new BufferGeometryLoader();
  17131. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17132. let geometry;
  17133. const data = json[ i ];
  17134. switch ( data.type ) {
  17135. case 'BufferGeometry':
  17136. case 'InstancedBufferGeometry':
  17137. geometry = bufferGeometryLoader.parse( data );
  17138. break;
  17139. default:
  17140. if ( data.type in Geometries$1 ) {
  17141. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17142. } else {
  17143. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17144. }
  17145. }
  17146. geometry.uuid = data.uuid;
  17147. if ( data.name !== undefined ) geometry.name = data.name;
  17148. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17149. geometries[ data.uuid ] = geometry;
  17150. }
  17151. }
  17152. return geometries;
  17153. }
  17154. parseMaterials( json, textures ) {
  17155. const cache = {}; // MultiMaterial
  17156. const materials = {};
  17157. if ( json !== undefined ) {
  17158. const loader = new MaterialLoader();
  17159. loader.setTextures( textures );
  17160. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17161. const data = json[ i ];
  17162. if ( cache[ data.uuid ] === undefined ) {
  17163. cache[ data.uuid ] = loader.parse( data );
  17164. }
  17165. materials[ data.uuid ] = cache[ data.uuid ];
  17166. }
  17167. }
  17168. return materials;
  17169. }
  17170. parseAnimations( json ) {
  17171. const animations = {};
  17172. if ( json !== undefined ) {
  17173. for ( let i = 0; i < json.length; i ++ ) {
  17174. const data = json[ i ];
  17175. const clip = AnimationClip.parse( data );
  17176. animations[ clip.uuid ] = clip;
  17177. }
  17178. }
  17179. return animations;
  17180. }
  17181. parseImages( json, onLoad ) {
  17182. const scope = this;
  17183. const images = {};
  17184. let loader;
  17185. function loadImage( url ) {
  17186. scope.manager.itemStart( url );
  17187. return loader.load( url, function () {
  17188. scope.manager.itemEnd( url );
  17189. }, undefined, function () {
  17190. scope.manager.itemError( url );
  17191. scope.manager.itemEnd( url );
  17192. } );
  17193. }
  17194. function deserializeImage( image ) {
  17195. if ( typeof image === 'string' ) {
  17196. const url = image;
  17197. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17198. return loadImage( path );
  17199. } else {
  17200. if ( image.data ) {
  17201. return {
  17202. data: getTypedArray( image.type, image.data ),
  17203. width: image.width,
  17204. height: image.height
  17205. };
  17206. } else {
  17207. return null;
  17208. }
  17209. }
  17210. }
  17211. if ( json !== undefined && json.length > 0 ) {
  17212. const manager = new LoadingManager( onLoad );
  17213. loader = new ImageLoader( manager );
  17214. loader.setCrossOrigin( this.crossOrigin );
  17215. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17216. const image = json[ i ];
  17217. const url = image.url;
  17218. if ( Array.isArray( url ) ) {
  17219. // load array of images e.g CubeTexture
  17220. const imageArray = [];
  17221. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17222. const currentUrl = url[ j ];
  17223. const deserializedImage = deserializeImage( currentUrl );
  17224. if ( deserializedImage !== null ) {
  17225. if ( deserializedImage instanceof HTMLImageElement ) {
  17226. imageArray.push( deserializedImage );
  17227. } else {
  17228. // special case: handle array of data textures for cube textures
  17229. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17230. }
  17231. }
  17232. }
  17233. images[ image.uuid ] = new Source( imageArray );
  17234. } else {
  17235. // load single image
  17236. const deserializedImage = deserializeImage( image.url );
  17237. images[ image.uuid ] = new Source( deserializedImage );
  17238. }
  17239. }
  17240. }
  17241. return images;
  17242. }
  17243. async parseImagesAsync( json ) {
  17244. const scope = this;
  17245. const images = {};
  17246. let loader;
  17247. async function deserializeImage( image ) {
  17248. if ( typeof image === 'string' ) {
  17249. const url = image;
  17250. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17251. return await loader.loadAsync( path );
  17252. } else {
  17253. if ( image.data ) {
  17254. return {
  17255. data: getTypedArray( image.type, image.data ),
  17256. width: image.width,
  17257. height: image.height
  17258. };
  17259. } else {
  17260. return null;
  17261. }
  17262. }
  17263. }
  17264. if ( json !== undefined && json.length > 0 ) {
  17265. loader = new ImageLoader( this.manager );
  17266. loader.setCrossOrigin( this.crossOrigin );
  17267. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17268. const image = json[ i ];
  17269. const url = image.url;
  17270. if ( Array.isArray( url ) ) {
  17271. // load array of images e.g CubeTexture
  17272. const imageArray = [];
  17273. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17274. const currentUrl = url[ j ];
  17275. const deserializedImage = await deserializeImage( currentUrl );
  17276. if ( deserializedImage !== null ) {
  17277. if ( deserializedImage instanceof HTMLImageElement ) {
  17278. imageArray.push( deserializedImage );
  17279. } else {
  17280. // special case: handle array of data textures for cube textures
  17281. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17282. }
  17283. }
  17284. }
  17285. images[ image.uuid ] = new Source( imageArray );
  17286. } else {
  17287. // load single image
  17288. const deserializedImage = await deserializeImage( image.url );
  17289. images[ image.uuid ] = new Source( deserializedImage );
  17290. }
  17291. }
  17292. }
  17293. return images;
  17294. }
  17295. parseTextures( json, images ) {
  17296. function parseConstant( value, type ) {
  17297. if ( typeof value === 'number' ) return value;
  17298. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17299. return type[ value ];
  17300. }
  17301. const textures = {};
  17302. if ( json !== undefined ) {
  17303. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17304. const data = json[ i ];
  17305. if ( data.image === undefined ) {
  17306. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17307. }
  17308. if ( images[ data.image ] === undefined ) {
  17309. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17310. }
  17311. const source = images[ data.image ];
  17312. const image = source.data;
  17313. let texture;
  17314. if ( Array.isArray( image ) ) {
  17315. texture = new CubeTexture();
  17316. if ( image.length === 6 ) texture.needsUpdate = true;
  17317. } else {
  17318. if ( image && image.data ) {
  17319. texture = new DataTexture();
  17320. } else {
  17321. texture = new Texture();
  17322. }
  17323. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17324. }
  17325. texture.source = source;
  17326. texture.uuid = data.uuid;
  17327. if ( data.name !== undefined ) texture.name = data.name;
  17328. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17329. if ( data.channel !== undefined ) texture.channel = data.channel;
  17330. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17331. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17332. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17333. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17334. if ( data.wrap !== undefined ) {
  17335. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17336. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17337. }
  17338. if ( data.format !== undefined ) texture.format = data.format;
  17339. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17340. if ( data.type !== undefined ) texture.type = data.type;
  17341. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17342. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17343. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17344. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17345. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17346. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17347. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17348. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17349. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17350. if ( data.userData !== undefined ) texture.userData = data.userData;
  17351. textures[ data.uuid ] = texture;
  17352. }
  17353. }
  17354. return textures;
  17355. }
  17356. parseObject( data, geometries, materials, textures, animations ) {
  17357. let object;
  17358. function getGeometry( name ) {
  17359. if ( geometries[ name ] === undefined ) {
  17360. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17361. }
  17362. return geometries[ name ];
  17363. }
  17364. function getMaterial( name ) {
  17365. if ( name === undefined ) return undefined;
  17366. if ( Array.isArray( name ) ) {
  17367. const array = [];
  17368. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17369. const uuid = name[ i ];
  17370. if ( materials[ uuid ] === undefined ) {
  17371. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17372. }
  17373. array.push( materials[ uuid ] );
  17374. }
  17375. return array;
  17376. }
  17377. if ( materials[ name ] === undefined ) {
  17378. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17379. }
  17380. return materials[ name ];
  17381. }
  17382. function getTexture( uuid ) {
  17383. if ( textures[ uuid ] === undefined ) {
  17384. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17385. }
  17386. return textures[ uuid ];
  17387. }
  17388. let geometry, material;
  17389. switch ( data.type ) {
  17390. case 'Scene':
  17391. object = new Scene();
  17392. if ( data.background !== undefined ) {
  17393. if ( Number.isInteger( data.background ) ) {
  17394. object.background = new Color( data.background );
  17395. } else {
  17396. object.background = getTexture( data.background );
  17397. }
  17398. }
  17399. if ( data.environment !== undefined ) {
  17400. object.environment = getTexture( data.environment );
  17401. }
  17402. if ( data.fog !== undefined ) {
  17403. if ( data.fog.type === 'Fog' ) {
  17404. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17405. } else if ( data.fog.type === 'FogExp2' ) {
  17406. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17407. }
  17408. if ( data.fog.name !== '' ) {
  17409. object.fog.name = data.fog.name;
  17410. }
  17411. }
  17412. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17413. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17414. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17415. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17416. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17417. break;
  17418. case 'PerspectiveCamera':
  17419. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17420. if ( data.focus !== undefined ) object.focus = data.focus;
  17421. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17422. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17423. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17424. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17425. break;
  17426. case 'OrthographicCamera':
  17427. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17428. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17429. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17430. break;
  17431. case 'AmbientLight':
  17432. object = new AmbientLight( data.color, data.intensity );
  17433. break;
  17434. case 'DirectionalLight':
  17435. object = new DirectionalLight( data.color, data.intensity );
  17436. object.target = data.target || '';
  17437. break;
  17438. case 'PointLight':
  17439. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17440. break;
  17441. case 'RectAreaLight':
  17442. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17443. break;
  17444. case 'SpotLight':
  17445. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17446. object.target = data.target || '';
  17447. break;
  17448. case 'HemisphereLight':
  17449. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17450. break;
  17451. case 'LightProbe':
  17452. object = new LightProbe().fromJSON( data );
  17453. break;
  17454. case 'SkinnedMesh':
  17455. geometry = getGeometry( data.geometry );
  17456. material = getMaterial( data.material );
  17457. object = new SkinnedMesh( geometry, material );
  17458. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17459. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17460. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17461. break;
  17462. case 'Mesh':
  17463. geometry = getGeometry( data.geometry );
  17464. material = getMaterial( data.material );
  17465. object = new Mesh( geometry, material );
  17466. break;
  17467. case 'InstancedMesh':
  17468. geometry = getGeometry( data.geometry );
  17469. material = getMaterial( data.material );
  17470. const count = data.count;
  17471. const instanceMatrix = data.instanceMatrix;
  17472. const instanceColor = data.instanceColor;
  17473. object = new InstancedMesh( geometry, material, count );
  17474. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17475. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17476. break;
  17477. case 'BatchedMesh':
  17478. geometry = getGeometry( data.geometry );
  17479. material = getMaterial( data.material );
  17480. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17481. object.geometry = geometry;
  17482. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17483. object.sortObjects = data.sortObjects;
  17484. object._drawRanges = data.drawRanges;
  17485. object._reservedRanges = data.reservedRanges;
  17486. object._visibility = data.visibility;
  17487. object._active = data.active;
  17488. object._bounds = data.bounds.map( bound => {
  17489. const box = new Box3();
  17490. box.min.fromArray( bound.boxMin );
  17491. box.max.fromArray( bound.boxMax );
  17492. const sphere = new Sphere();
  17493. sphere.radius = bound.sphereRadius;
  17494. sphere.center.fromArray( bound.sphereCenter );
  17495. return {
  17496. boxInitialized: bound.boxInitialized,
  17497. box: box,
  17498. sphereInitialized: bound.sphereInitialized,
  17499. sphere: sphere
  17500. };
  17501. } );
  17502. object._maxInstanceCount = data.maxInstanceCount;
  17503. object._maxVertexCount = data.maxVertexCount;
  17504. object._maxIndexCount = data.maxIndexCount;
  17505. object._geometryInitialized = data.geometryInitialized;
  17506. object._geometryCount = data.geometryCount;
  17507. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17508. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17509. break;
  17510. case 'LOD':
  17511. object = new LOD();
  17512. break;
  17513. case 'Line':
  17514. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17515. break;
  17516. case 'LineLoop':
  17517. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17518. break;
  17519. case 'LineSegments':
  17520. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17521. break;
  17522. case 'PointCloud':
  17523. case 'Points':
  17524. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17525. break;
  17526. case 'Sprite':
  17527. object = new Sprite( getMaterial( data.material ) );
  17528. break;
  17529. case 'Group':
  17530. object = new Group();
  17531. break;
  17532. case 'Bone':
  17533. object = new Bone();
  17534. break;
  17535. default:
  17536. object = new Object3D();
  17537. }
  17538. object.uuid = data.uuid;
  17539. if ( data.name !== undefined ) object.name = data.name;
  17540. if ( data.matrix !== undefined ) {
  17541. object.matrix.fromArray( data.matrix );
  17542. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17543. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17544. } else {
  17545. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17546. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17547. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17548. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17549. }
  17550. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17551. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17552. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17553. if ( data.shadow ) {
  17554. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17555. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17556. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17557. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17558. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17559. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17560. }
  17561. if ( data.visible !== undefined ) object.visible = data.visible;
  17562. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17563. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17564. if ( data.userData !== undefined ) object.userData = data.userData;
  17565. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17566. if ( data.children !== undefined ) {
  17567. const children = data.children;
  17568. for ( let i = 0; i < children.length; i ++ ) {
  17569. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17570. }
  17571. }
  17572. if ( data.animations !== undefined ) {
  17573. const objectAnimations = data.animations;
  17574. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17575. const uuid = objectAnimations[ i ];
  17576. object.animations.push( animations[ uuid ] );
  17577. }
  17578. }
  17579. if ( data.type === 'LOD' ) {
  17580. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17581. const levels = data.levels;
  17582. for ( let l = 0; l < levels.length; l ++ ) {
  17583. const level = levels[ l ];
  17584. const child = object.getObjectByProperty( 'uuid', level.object );
  17585. if ( child !== undefined ) {
  17586. object.addLevel( child, level.distance, level.hysteresis );
  17587. }
  17588. }
  17589. }
  17590. return object;
  17591. }
  17592. bindSkeletons( object, skeletons ) {
  17593. if ( Object.keys( skeletons ).length === 0 ) return;
  17594. object.traverse( function ( child ) {
  17595. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17596. const skeleton = skeletons[ child.skeleton ];
  17597. if ( skeleton === undefined ) {
  17598. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17599. } else {
  17600. child.bind( skeleton, child.bindMatrix );
  17601. }
  17602. }
  17603. } );
  17604. }
  17605. bindLightTargets( object ) {
  17606. object.traverse( function ( child ) {
  17607. if ( child.isDirectionalLight || child.isSpotLight ) {
  17608. const uuid = child.target;
  17609. const target = object.getObjectByProperty( 'uuid', uuid );
  17610. if ( target !== undefined ) {
  17611. child.target = target;
  17612. } else {
  17613. child.target = new Object3D();
  17614. }
  17615. }
  17616. } );
  17617. }
  17618. }
  17619. const TEXTURE_MAPPING = {
  17620. UVMapping: UVMapping,
  17621. CubeReflectionMapping: CubeReflectionMapping,
  17622. CubeRefractionMapping: CubeRefractionMapping,
  17623. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17624. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17625. CubeUVReflectionMapping: CubeUVReflectionMapping
  17626. };
  17627. const TEXTURE_WRAPPING = {
  17628. RepeatWrapping: RepeatWrapping,
  17629. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17630. MirroredRepeatWrapping: MirroredRepeatWrapping
  17631. };
  17632. const TEXTURE_FILTER = {
  17633. NearestFilter: NearestFilter,
  17634. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17635. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17636. LinearFilter: LinearFilter,
  17637. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17638. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17639. };
  17640. class ImageBitmapLoader extends Loader {
  17641. constructor( manager ) {
  17642. super( manager );
  17643. this.isImageBitmapLoader = true;
  17644. if ( typeof createImageBitmap === 'undefined' ) {
  17645. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17646. }
  17647. if ( typeof fetch === 'undefined' ) {
  17648. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17649. }
  17650. this.options = { premultiplyAlpha: 'none' };
  17651. }
  17652. setOptions( options ) {
  17653. this.options = options;
  17654. return this;
  17655. }
  17656. load( url, onLoad, onProgress, onError ) {
  17657. if ( url === undefined ) url = '';
  17658. if ( this.path !== undefined ) url = this.path + url;
  17659. url = this.manager.resolveURL( url );
  17660. const scope = this;
  17661. const cached = Cache.get( url );
  17662. if ( cached !== undefined ) {
  17663. scope.manager.itemStart( url );
  17664. // If cached is a promise, wait for it to resolve
  17665. if ( cached.then ) {
  17666. cached.then( imageBitmap => {
  17667. if ( onLoad ) onLoad( imageBitmap );
  17668. scope.manager.itemEnd( url );
  17669. } ).catch( e => {
  17670. if ( onError ) onError( e );
  17671. } );
  17672. return;
  17673. }
  17674. // If cached is not a promise (i.e., it's already an imageBitmap)
  17675. setTimeout( function () {
  17676. if ( onLoad ) onLoad( cached );
  17677. scope.manager.itemEnd( url );
  17678. }, 0 );
  17679. return cached;
  17680. }
  17681. const fetchOptions = {};
  17682. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17683. fetchOptions.headers = this.requestHeader;
  17684. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17685. return res.blob();
  17686. } ).then( function ( blob ) {
  17687. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17688. } ).then( function ( imageBitmap ) {
  17689. Cache.add( url, imageBitmap );
  17690. if ( onLoad ) onLoad( imageBitmap );
  17691. scope.manager.itemEnd( url );
  17692. return imageBitmap;
  17693. } ).catch( function ( e ) {
  17694. if ( onError ) onError( e );
  17695. Cache.remove( url );
  17696. scope.manager.itemError( url );
  17697. scope.manager.itemEnd( url );
  17698. } );
  17699. Cache.add( url, promise );
  17700. scope.manager.itemStart( url );
  17701. }
  17702. }
  17703. let _context;
  17704. class AudioContext {
  17705. static getContext() {
  17706. if ( _context === undefined ) {
  17707. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17708. }
  17709. return _context;
  17710. }
  17711. static setContext( value ) {
  17712. _context = value;
  17713. }
  17714. }
  17715. class AudioLoader extends Loader {
  17716. constructor( manager ) {
  17717. super( manager );
  17718. }
  17719. load( url, onLoad, onProgress, onError ) {
  17720. const scope = this;
  17721. const loader = new FileLoader( this.manager );
  17722. loader.setResponseType( 'arraybuffer' );
  17723. loader.setPath( this.path );
  17724. loader.setRequestHeader( this.requestHeader );
  17725. loader.setWithCredentials( this.withCredentials );
  17726. loader.load( url, function ( buffer ) {
  17727. try {
  17728. // Create a copy of the buffer. The `decodeAudioData` method
  17729. // detaches the buffer when complete, preventing reuse.
  17730. const bufferCopy = buffer.slice( 0 );
  17731. const context = AudioContext.getContext();
  17732. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17733. onLoad( audioBuffer );
  17734. } ).catch( handleError );
  17735. } catch ( e ) {
  17736. handleError( e );
  17737. }
  17738. }, onProgress, onError );
  17739. function handleError( e ) {
  17740. if ( onError ) {
  17741. onError( e );
  17742. } else {
  17743. console.error( e );
  17744. }
  17745. scope.manager.itemError( url );
  17746. }
  17747. }
  17748. }
  17749. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17750. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17751. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17752. class StereoCamera {
  17753. constructor() {
  17754. this.type = 'StereoCamera';
  17755. this.aspect = 1;
  17756. this.eyeSep = 0.064;
  17757. this.cameraL = new PerspectiveCamera();
  17758. this.cameraL.layers.enable( 1 );
  17759. this.cameraL.matrixAutoUpdate = false;
  17760. this.cameraR = new PerspectiveCamera();
  17761. this.cameraR.layers.enable( 2 );
  17762. this.cameraR.matrixAutoUpdate = false;
  17763. this._cache = {
  17764. focus: null,
  17765. fov: null,
  17766. aspect: null,
  17767. near: null,
  17768. far: null,
  17769. zoom: null,
  17770. eyeSep: null
  17771. };
  17772. }
  17773. update( camera ) {
  17774. const cache = this._cache;
  17775. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17776. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17777. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17778. if ( needsUpdate ) {
  17779. cache.focus = camera.focus;
  17780. cache.fov = camera.fov;
  17781. cache.aspect = camera.aspect * this.aspect;
  17782. cache.near = camera.near;
  17783. cache.far = camera.far;
  17784. cache.zoom = camera.zoom;
  17785. cache.eyeSep = this.eyeSep;
  17786. // Off-axis stereoscopic effect based on
  17787. // http://paulbourke.net/stereographics/stereorender/
  17788. _projectionMatrix.copy( camera.projectionMatrix );
  17789. const eyeSepHalf = cache.eyeSep / 2;
  17790. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17791. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  17792. let xmin, xmax;
  17793. // translate xOffset
  17794. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  17795. _eyeRight.elements[ 12 ] = eyeSepHalf;
  17796. // for left eye
  17797. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  17798. xmax = ymax * cache.aspect + eyeSepOnProjection;
  17799. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17800. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17801. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  17802. // for right eye
  17803. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  17804. xmax = ymax * cache.aspect - eyeSepOnProjection;
  17805. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17806. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17807. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  17808. }
  17809. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  17810. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  17811. }
  17812. }
  17813. class ArrayCamera extends PerspectiveCamera {
  17814. constructor( array = [] ) {
  17815. super();
  17816. this.isArrayCamera = true;
  17817. this.cameras = array;
  17818. }
  17819. }
  17820. class Clock {
  17821. constructor( autoStart = true ) {
  17822. this.autoStart = autoStart;
  17823. this.startTime = 0;
  17824. this.oldTime = 0;
  17825. this.elapsedTime = 0;
  17826. this.running = false;
  17827. }
  17828. start() {
  17829. this.startTime = now();
  17830. this.oldTime = this.startTime;
  17831. this.elapsedTime = 0;
  17832. this.running = true;
  17833. }
  17834. stop() {
  17835. this.getElapsedTime();
  17836. this.running = false;
  17837. this.autoStart = false;
  17838. }
  17839. getElapsedTime() {
  17840. this.getDelta();
  17841. return this.elapsedTime;
  17842. }
  17843. getDelta() {
  17844. let diff = 0;
  17845. if ( this.autoStart && ! this.running ) {
  17846. this.start();
  17847. return 0;
  17848. }
  17849. if ( this.running ) {
  17850. const newTime = now();
  17851. diff = ( newTime - this.oldTime ) / 1000;
  17852. this.oldTime = newTime;
  17853. this.elapsedTime += diff;
  17854. }
  17855. return diff;
  17856. }
  17857. }
  17858. function now() {
  17859. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  17860. }
  17861. const _position$1 = /*@__PURE__*/ new Vector3();
  17862. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  17863. const _scale$1 = /*@__PURE__*/ new Vector3();
  17864. const _orientation$1 = /*@__PURE__*/ new Vector3();
  17865. class AudioListener extends Object3D {
  17866. constructor() {
  17867. super();
  17868. this.type = 'AudioListener';
  17869. this.context = AudioContext.getContext();
  17870. this.gain = this.context.createGain();
  17871. this.gain.connect( this.context.destination );
  17872. this.filter = null;
  17873. this.timeDelta = 0;
  17874. // private
  17875. this._clock = new Clock();
  17876. }
  17877. getInput() {
  17878. return this.gain;
  17879. }
  17880. removeFilter() {
  17881. if ( this.filter !== null ) {
  17882. this.gain.disconnect( this.filter );
  17883. this.filter.disconnect( this.context.destination );
  17884. this.gain.connect( this.context.destination );
  17885. this.filter = null;
  17886. }
  17887. return this;
  17888. }
  17889. getFilter() {
  17890. return this.filter;
  17891. }
  17892. setFilter( value ) {
  17893. if ( this.filter !== null ) {
  17894. this.gain.disconnect( this.filter );
  17895. this.filter.disconnect( this.context.destination );
  17896. } else {
  17897. this.gain.disconnect( this.context.destination );
  17898. }
  17899. this.filter = value;
  17900. this.gain.connect( this.filter );
  17901. this.filter.connect( this.context.destination );
  17902. return this;
  17903. }
  17904. getMasterVolume() {
  17905. return this.gain.gain.value;
  17906. }
  17907. setMasterVolume( value ) {
  17908. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  17909. return this;
  17910. }
  17911. updateMatrixWorld( force ) {
  17912. super.updateMatrixWorld( force );
  17913. const listener = this.context.listener;
  17914. const up = this.up;
  17915. this.timeDelta = this._clock.getDelta();
  17916. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  17917. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  17918. if ( listener.positionX ) {
  17919. // code path for Chrome (see #14393)
  17920. const endTime = this.context.currentTime + this.timeDelta;
  17921. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  17922. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  17923. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  17924. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  17925. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  17926. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  17927. listener.upX.linearRampToValueAtTime( up.x, endTime );
  17928. listener.upY.linearRampToValueAtTime( up.y, endTime );
  17929. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  17930. } else {
  17931. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  17932. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  17933. }
  17934. }
  17935. }
  17936. class Audio extends Object3D {
  17937. constructor( listener ) {
  17938. super();
  17939. this.type = 'Audio';
  17940. this.listener = listener;
  17941. this.context = listener.context;
  17942. this.gain = this.context.createGain();
  17943. this.gain.connect( listener.getInput() );
  17944. this.autoplay = false;
  17945. this.buffer = null;
  17946. this.detune = 0;
  17947. this.loop = false;
  17948. this.loopStart = 0;
  17949. this.loopEnd = 0;
  17950. this.offset = 0;
  17951. this.duration = undefined;
  17952. this.playbackRate = 1;
  17953. this.isPlaying = false;
  17954. this.hasPlaybackControl = true;
  17955. this.source = null;
  17956. this.sourceType = 'empty';
  17957. this._startedAt = 0;
  17958. this._progress = 0;
  17959. this._connected = false;
  17960. this.filters = [];
  17961. }
  17962. getOutput() {
  17963. return this.gain;
  17964. }
  17965. setNodeSource( audioNode ) {
  17966. this.hasPlaybackControl = false;
  17967. this.sourceType = 'audioNode';
  17968. this.source = audioNode;
  17969. this.connect();
  17970. return this;
  17971. }
  17972. setMediaElementSource( mediaElement ) {
  17973. this.hasPlaybackControl = false;
  17974. this.sourceType = 'mediaNode';
  17975. this.source = this.context.createMediaElementSource( mediaElement );
  17976. this.connect();
  17977. return this;
  17978. }
  17979. setMediaStreamSource( mediaStream ) {
  17980. this.hasPlaybackControl = false;
  17981. this.sourceType = 'mediaStreamNode';
  17982. this.source = this.context.createMediaStreamSource( mediaStream );
  17983. this.connect();
  17984. return this;
  17985. }
  17986. setBuffer( audioBuffer ) {
  17987. this.buffer = audioBuffer;
  17988. this.sourceType = 'buffer';
  17989. if ( this.autoplay ) this.play();
  17990. return this;
  17991. }
  17992. play( delay = 0 ) {
  17993. if ( this.isPlaying === true ) {
  17994. console.warn( 'THREE.Audio: Audio is already playing.' );
  17995. return;
  17996. }
  17997. if ( this.hasPlaybackControl === false ) {
  17998. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  17999. return;
  18000. }
  18001. this._startedAt = this.context.currentTime + delay;
  18002. const source = this.context.createBufferSource();
  18003. source.buffer = this.buffer;
  18004. source.loop = this.loop;
  18005. source.loopStart = this.loopStart;
  18006. source.loopEnd = this.loopEnd;
  18007. source.onended = this.onEnded.bind( this );
  18008. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18009. this.isPlaying = true;
  18010. this.source = source;
  18011. this.setDetune( this.detune );
  18012. this.setPlaybackRate( this.playbackRate );
  18013. return this.connect();
  18014. }
  18015. pause() {
  18016. if ( this.hasPlaybackControl === false ) {
  18017. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18018. return;
  18019. }
  18020. if ( this.isPlaying === true ) {
  18021. // update current progress
  18022. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18023. if ( this.loop === true ) {
  18024. // ensure _progress does not exceed duration with looped audios
  18025. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18026. }
  18027. this.source.stop();
  18028. this.source.onended = null;
  18029. this.isPlaying = false;
  18030. }
  18031. return this;
  18032. }
  18033. stop() {
  18034. if ( this.hasPlaybackControl === false ) {
  18035. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18036. return;
  18037. }
  18038. this._progress = 0;
  18039. if ( this.source !== null ) {
  18040. this.source.stop();
  18041. this.source.onended = null;
  18042. }
  18043. this.isPlaying = false;
  18044. return this;
  18045. }
  18046. connect() {
  18047. if ( this.filters.length > 0 ) {
  18048. this.source.connect( this.filters[ 0 ] );
  18049. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18050. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18051. }
  18052. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18053. } else {
  18054. this.source.connect( this.getOutput() );
  18055. }
  18056. this._connected = true;
  18057. return this;
  18058. }
  18059. disconnect() {
  18060. if ( this._connected === false ) {
  18061. return;
  18062. }
  18063. if ( this.filters.length > 0 ) {
  18064. this.source.disconnect( this.filters[ 0 ] );
  18065. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18066. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18067. }
  18068. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18069. } else {
  18070. this.source.disconnect( this.getOutput() );
  18071. }
  18072. this._connected = false;
  18073. return this;
  18074. }
  18075. getFilters() {
  18076. return this.filters;
  18077. }
  18078. setFilters( value ) {
  18079. if ( ! value ) value = [];
  18080. if ( this._connected === true ) {
  18081. this.disconnect();
  18082. this.filters = value.slice();
  18083. this.connect();
  18084. } else {
  18085. this.filters = value.slice();
  18086. }
  18087. return this;
  18088. }
  18089. setDetune( value ) {
  18090. this.detune = value;
  18091. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18092. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18093. }
  18094. return this;
  18095. }
  18096. getDetune() {
  18097. return this.detune;
  18098. }
  18099. getFilter() {
  18100. return this.getFilters()[ 0 ];
  18101. }
  18102. setFilter( filter ) {
  18103. return this.setFilters( filter ? [ filter ] : [] );
  18104. }
  18105. setPlaybackRate( value ) {
  18106. if ( this.hasPlaybackControl === false ) {
  18107. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18108. return;
  18109. }
  18110. this.playbackRate = value;
  18111. if ( this.isPlaying === true ) {
  18112. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18113. }
  18114. return this;
  18115. }
  18116. getPlaybackRate() {
  18117. return this.playbackRate;
  18118. }
  18119. onEnded() {
  18120. this.isPlaying = false;
  18121. }
  18122. getLoop() {
  18123. if ( this.hasPlaybackControl === false ) {
  18124. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18125. return false;
  18126. }
  18127. return this.loop;
  18128. }
  18129. setLoop( value ) {
  18130. if ( this.hasPlaybackControl === false ) {
  18131. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18132. return;
  18133. }
  18134. this.loop = value;
  18135. if ( this.isPlaying === true ) {
  18136. this.source.loop = this.loop;
  18137. }
  18138. return this;
  18139. }
  18140. setLoopStart( value ) {
  18141. this.loopStart = value;
  18142. return this;
  18143. }
  18144. setLoopEnd( value ) {
  18145. this.loopEnd = value;
  18146. return this;
  18147. }
  18148. getVolume() {
  18149. return this.gain.gain.value;
  18150. }
  18151. setVolume( value ) {
  18152. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18153. return this;
  18154. }
  18155. }
  18156. const _position = /*@__PURE__*/ new Vector3();
  18157. const _quaternion = /*@__PURE__*/ new Quaternion();
  18158. const _scale = /*@__PURE__*/ new Vector3();
  18159. const _orientation = /*@__PURE__*/ new Vector3();
  18160. class PositionalAudio extends Audio {
  18161. constructor( listener ) {
  18162. super( listener );
  18163. this.panner = this.context.createPanner();
  18164. this.panner.panningModel = 'HRTF';
  18165. this.panner.connect( this.gain );
  18166. }
  18167. connect() {
  18168. super.connect();
  18169. this.panner.connect( this.gain );
  18170. }
  18171. disconnect() {
  18172. super.disconnect();
  18173. this.panner.disconnect( this.gain );
  18174. }
  18175. getOutput() {
  18176. return this.panner;
  18177. }
  18178. getRefDistance() {
  18179. return this.panner.refDistance;
  18180. }
  18181. setRefDistance( value ) {
  18182. this.panner.refDistance = value;
  18183. return this;
  18184. }
  18185. getRolloffFactor() {
  18186. return this.panner.rolloffFactor;
  18187. }
  18188. setRolloffFactor( value ) {
  18189. this.panner.rolloffFactor = value;
  18190. return this;
  18191. }
  18192. getDistanceModel() {
  18193. return this.panner.distanceModel;
  18194. }
  18195. setDistanceModel( value ) {
  18196. this.panner.distanceModel = value;
  18197. return this;
  18198. }
  18199. getMaxDistance() {
  18200. return this.panner.maxDistance;
  18201. }
  18202. setMaxDistance( value ) {
  18203. this.panner.maxDistance = value;
  18204. return this;
  18205. }
  18206. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18207. this.panner.coneInnerAngle = coneInnerAngle;
  18208. this.panner.coneOuterAngle = coneOuterAngle;
  18209. this.panner.coneOuterGain = coneOuterGain;
  18210. return this;
  18211. }
  18212. updateMatrixWorld( force ) {
  18213. super.updateMatrixWorld( force );
  18214. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18215. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18216. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18217. const panner = this.panner;
  18218. if ( panner.positionX ) {
  18219. // code path for Chrome and Firefox (see #14393)
  18220. const endTime = this.context.currentTime + this.listener.timeDelta;
  18221. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18222. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18223. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18224. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18225. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18226. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18227. } else {
  18228. panner.setPosition( _position.x, _position.y, _position.z );
  18229. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18230. }
  18231. }
  18232. }
  18233. class AudioAnalyser {
  18234. constructor( audio, fftSize = 2048 ) {
  18235. this.analyser = audio.context.createAnalyser();
  18236. this.analyser.fftSize = fftSize;
  18237. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18238. audio.getOutput().connect( this.analyser );
  18239. }
  18240. getFrequencyData() {
  18241. this.analyser.getByteFrequencyData( this.data );
  18242. return this.data;
  18243. }
  18244. getAverageFrequency() {
  18245. let value = 0;
  18246. const data = this.getFrequencyData();
  18247. for ( let i = 0; i < data.length; i ++ ) {
  18248. value += data[ i ];
  18249. }
  18250. return value / data.length;
  18251. }
  18252. }
  18253. class PropertyMixer {
  18254. constructor( binding, typeName, valueSize ) {
  18255. this.binding = binding;
  18256. this.valueSize = valueSize;
  18257. let mixFunction,
  18258. mixFunctionAdditive,
  18259. setIdentity;
  18260. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18261. //
  18262. // interpolators can use .buffer as their .result
  18263. // the data then goes to 'incoming'
  18264. //
  18265. // 'accu0' and 'accu1' are used frame-interleaved for
  18266. // the cumulative result and are compared to detect
  18267. // changes
  18268. //
  18269. // 'orig' stores the original state of the property
  18270. //
  18271. // 'add' is used for additive cumulative results
  18272. //
  18273. // 'work' is optional and is only present for quaternion types. It is used
  18274. // to store intermediate quaternion multiplication results
  18275. switch ( typeName ) {
  18276. case 'quaternion':
  18277. mixFunction = this._slerp;
  18278. mixFunctionAdditive = this._slerpAdditive;
  18279. setIdentity = this._setAdditiveIdentityQuaternion;
  18280. this.buffer = new Float64Array( valueSize * 6 );
  18281. this._workIndex = 5;
  18282. break;
  18283. case 'string':
  18284. case 'bool':
  18285. mixFunction = this._select;
  18286. // Use the regular mix function and for additive on these types,
  18287. // additive is not relevant for non-numeric types
  18288. mixFunctionAdditive = this._select;
  18289. setIdentity = this._setAdditiveIdentityOther;
  18290. this.buffer = new Array( valueSize * 5 );
  18291. break;
  18292. default:
  18293. mixFunction = this._lerp;
  18294. mixFunctionAdditive = this._lerpAdditive;
  18295. setIdentity = this._setAdditiveIdentityNumeric;
  18296. this.buffer = new Float64Array( valueSize * 5 );
  18297. }
  18298. this._mixBufferRegion = mixFunction;
  18299. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18300. this._setIdentity = setIdentity;
  18301. this._origIndex = 3;
  18302. this._addIndex = 4;
  18303. this.cumulativeWeight = 0;
  18304. this.cumulativeWeightAdditive = 0;
  18305. this.useCount = 0;
  18306. this.referenceCount = 0;
  18307. }
  18308. // accumulate data in the 'incoming' region into 'accu<i>'
  18309. accumulate( accuIndex, weight ) {
  18310. // note: happily accumulating nothing when weight = 0, the caller knows
  18311. // the weight and shouldn't have made the call in the first place
  18312. const buffer = this.buffer,
  18313. stride = this.valueSize,
  18314. offset = accuIndex * stride + stride;
  18315. let currentWeight = this.cumulativeWeight;
  18316. if ( currentWeight === 0 ) {
  18317. // accuN := incoming * weight
  18318. for ( let i = 0; i !== stride; ++ i ) {
  18319. buffer[ offset + i ] = buffer[ i ];
  18320. }
  18321. currentWeight = weight;
  18322. } else {
  18323. // accuN := accuN + incoming * weight
  18324. currentWeight += weight;
  18325. const mix = weight / currentWeight;
  18326. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18327. }
  18328. this.cumulativeWeight = currentWeight;
  18329. }
  18330. // accumulate data in the 'incoming' region into 'add'
  18331. accumulateAdditive( weight ) {
  18332. const buffer = this.buffer,
  18333. stride = this.valueSize,
  18334. offset = stride * this._addIndex;
  18335. if ( this.cumulativeWeightAdditive === 0 ) {
  18336. // add = identity
  18337. this._setIdentity();
  18338. }
  18339. // add := add + incoming * weight
  18340. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18341. this.cumulativeWeightAdditive += weight;
  18342. }
  18343. // apply the state of 'accu<i>' to the binding when accus differ
  18344. apply( accuIndex ) {
  18345. const stride = this.valueSize,
  18346. buffer = this.buffer,
  18347. offset = accuIndex * stride + stride,
  18348. weight = this.cumulativeWeight,
  18349. weightAdditive = this.cumulativeWeightAdditive,
  18350. binding = this.binding;
  18351. this.cumulativeWeight = 0;
  18352. this.cumulativeWeightAdditive = 0;
  18353. if ( weight < 1 ) {
  18354. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18355. const originalValueOffset = stride * this._origIndex;
  18356. this._mixBufferRegion(
  18357. buffer, offset, originalValueOffset, 1 - weight, stride );
  18358. }
  18359. if ( weightAdditive > 0 ) {
  18360. // accuN := accuN + additive accuN
  18361. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18362. }
  18363. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18364. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18365. // value has changed -> update scene graph
  18366. binding.setValue( buffer, offset );
  18367. break;
  18368. }
  18369. }
  18370. }
  18371. // remember the state of the bound property and copy it to both accus
  18372. saveOriginalState() {
  18373. const binding = this.binding;
  18374. const buffer = this.buffer,
  18375. stride = this.valueSize,
  18376. originalValueOffset = stride * this._origIndex;
  18377. binding.getValue( buffer, originalValueOffset );
  18378. // accu[0..1] := orig -- initially detect changes against the original
  18379. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18380. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18381. }
  18382. // Add to identity for additive
  18383. this._setIdentity();
  18384. this.cumulativeWeight = 0;
  18385. this.cumulativeWeightAdditive = 0;
  18386. }
  18387. // apply the state previously taken via 'saveOriginalState' to the binding
  18388. restoreOriginalState() {
  18389. const originalValueOffset = this.valueSize * 3;
  18390. this.binding.setValue( this.buffer, originalValueOffset );
  18391. }
  18392. _setAdditiveIdentityNumeric() {
  18393. const startIndex = this._addIndex * this.valueSize;
  18394. const endIndex = startIndex + this.valueSize;
  18395. for ( let i = startIndex; i < endIndex; i ++ ) {
  18396. this.buffer[ i ] = 0;
  18397. }
  18398. }
  18399. _setAdditiveIdentityQuaternion() {
  18400. this._setAdditiveIdentityNumeric();
  18401. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18402. }
  18403. _setAdditiveIdentityOther() {
  18404. const startIndex = this._origIndex * this.valueSize;
  18405. const targetIndex = this._addIndex * this.valueSize;
  18406. for ( let i = 0; i < this.valueSize; i ++ ) {
  18407. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18408. }
  18409. }
  18410. // mix functions
  18411. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18412. if ( t >= 0.5 ) {
  18413. for ( let i = 0; i !== stride; ++ i ) {
  18414. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18415. }
  18416. }
  18417. }
  18418. _slerp( buffer, dstOffset, srcOffset, t ) {
  18419. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18420. }
  18421. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18422. const workOffset = this._workIndex * stride;
  18423. // Store result in intermediate buffer offset
  18424. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18425. // Slerp to the intermediate result
  18426. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18427. }
  18428. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18429. const s = 1 - t;
  18430. for ( let i = 0; i !== stride; ++ i ) {
  18431. const j = dstOffset + i;
  18432. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18433. }
  18434. }
  18435. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18436. for ( let i = 0; i !== stride; ++ i ) {
  18437. const j = dstOffset + i;
  18438. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18439. }
  18440. }
  18441. }
  18442. // Characters [].:/ are reserved for track binding syntax.
  18443. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18444. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18445. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18446. // only latin characters, and the unicode \p{L} is not yet supported. So
  18447. // instead, we exclude reserved characters and match everything else.
  18448. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18449. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18450. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18451. // be matched to parse the rest of the track name.
  18452. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18453. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18454. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18455. // Object on target node, and accessor. May not contain reserved
  18456. // characters. Accessor may contain any character except closing bracket.
  18457. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18458. // Property and accessor. May not contain reserved characters. Accessor may
  18459. // contain any non-bracket characters.
  18460. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18461. const _trackRe = new RegExp( ''
  18462. + '^'
  18463. + _directoryRe
  18464. + _nodeRe
  18465. + _objectRe
  18466. + _propertyRe
  18467. + '$'
  18468. );
  18469. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18470. class Composite {
  18471. constructor( targetGroup, path, optionalParsedPath ) {
  18472. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18473. this._targetGroup = targetGroup;
  18474. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18475. }
  18476. getValue( array, offset ) {
  18477. this.bind(); // bind all binding
  18478. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18479. binding = this._bindings[ firstValidIndex ];
  18480. // and only call .getValue on the first
  18481. if ( binding !== undefined ) binding.getValue( array, offset );
  18482. }
  18483. setValue( array, offset ) {
  18484. const bindings = this._bindings;
  18485. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18486. bindings[ i ].setValue( array, offset );
  18487. }
  18488. }
  18489. bind() {
  18490. const bindings = this._bindings;
  18491. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18492. bindings[ i ].bind();
  18493. }
  18494. }
  18495. unbind() {
  18496. const bindings = this._bindings;
  18497. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18498. bindings[ i ].unbind();
  18499. }
  18500. }
  18501. }
  18502. // Note: This class uses a State pattern on a per-method basis:
  18503. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18504. // prototype version of these methods with one that represents
  18505. // the bound state. When the property is not found, the methods
  18506. // become no-ops.
  18507. class PropertyBinding {
  18508. constructor( rootNode, path, parsedPath ) {
  18509. this.path = path;
  18510. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18511. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18512. this.rootNode = rootNode;
  18513. // initial state of these methods that calls 'bind'
  18514. this.getValue = this._getValue_unbound;
  18515. this.setValue = this._setValue_unbound;
  18516. }
  18517. static create( root, path, parsedPath ) {
  18518. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18519. return new PropertyBinding( root, path, parsedPath );
  18520. } else {
  18521. return new PropertyBinding.Composite( root, path, parsedPath );
  18522. }
  18523. }
  18524. /**
  18525. * Replaces spaces with underscores and removes unsupported characters from
  18526. * node names, to ensure compatibility with parseTrackName().
  18527. *
  18528. * @param {string} name Node name to be sanitized.
  18529. * @return {string}
  18530. */
  18531. static sanitizeNodeName( name ) {
  18532. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18533. }
  18534. static parseTrackName( trackName ) {
  18535. const matches = _trackRe.exec( trackName );
  18536. if ( matches === null ) {
  18537. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18538. }
  18539. const results = {
  18540. // directoryName: matches[ 1 ], // (tschw) currently unused
  18541. nodeName: matches[ 2 ],
  18542. objectName: matches[ 3 ],
  18543. objectIndex: matches[ 4 ],
  18544. propertyName: matches[ 5 ], // required
  18545. propertyIndex: matches[ 6 ]
  18546. };
  18547. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18548. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18549. const objectName = results.nodeName.substring( lastDot + 1 );
  18550. // Object names must be checked against an allowlist. Otherwise, there
  18551. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18552. // 'bar' could be the objectName, or part of a nodeName (which can
  18553. // include '.' characters).
  18554. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18555. results.nodeName = results.nodeName.substring( 0, lastDot );
  18556. results.objectName = objectName;
  18557. }
  18558. }
  18559. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18560. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18561. }
  18562. return results;
  18563. }
  18564. static findNode( root, nodeName ) {
  18565. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18566. return root;
  18567. }
  18568. // search into skeleton bones.
  18569. if ( root.skeleton ) {
  18570. const bone = root.skeleton.getBoneByName( nodeName );
  18571. if ( bone !== undefined ) {
  18572. return bone;
  18573. }
  18574. }
  18575. // search into node subtree.
  18576. if ( root.children ) {
  18577. const searchNodeSubtree = function ( children ) {
  18578. for ( let i = 0; i < children.length; i ++ ) {
  18579. const childNode = children[ i ];
  18580. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18581. return childNode;
  18582. }
  18583. const result = searchNodeSubtree( childNode.children );
  18584. if ( result ) return result;
  18585. }
  18586. return null;
  18587. };
  18588. const subTreeNode = searchNodeSubtree( root.children );
  18589. if ( subTreeNode ) {
  18590. return subTreeNode;
  18591. }
  18592. }
  18593. return null;
  18594. }
  18595. // these are used to "bind" a nonexistent property
  18596. _getValue_unavailable() {}
  18597. _setValue_unavailable() {}
  18598. // Getters
  18599. _getValue_direct( buffer, offset ) {
  18600. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18601. }
  18602. _getValue_array( buffer, offset ) {
  18603. const source = this.resolvedProperty;
  18604. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18605. buffer[ offset ++ ] = source[ i ];
  18606. }
  18607. }
  18608. _getValue_arrayElement( buffer, offset ) {
  18609. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18610. }
  18611. _getValue_toArray( buffer, offset ) {
  18612. this.resolvedProperty.toArray( buffer, offset );
  18613. }
  18614. // Direct
  18615. _setValue_direct( buffer, offset ) {
  18616. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18617. }
  18618. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18619. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18620. this.targetObject.needsUpdate = true;
  18621. }
  18622. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18623. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18624. this.targetObject.matrixWorldNeedsUpdate = true;
  18625. }
  18626. // EntireArray
  18627. _setValue_array( buffer, offset ) {
  18628. const dest = this.resolvedProperty;
  18629. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18630. dest[ i ] = buffer[ offset ++ ];
  18631. }
  18632. }
  18633. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18634. const dest = this.resolvedProperty;
  18635. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18636. dest[ i ] = buffer[ offset ++ ];
  18637. }
  18638. this.targetObject.needsUpdate = true;
  18639. }
  18640. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18641. const dest = this.resolvedProperty;
  18642. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18643. dest[ i ] = buffer[ offset ++ ];
  18644. }
  18645. this.targetObject.matrixWorldNeedsUpdate = true;
  18646. }
  18647. // ArrayElement
  18648. _setValue_arrayElement( buffer, offset ) {
  18649. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18650. }
  18651. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18652. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18653. this.targetObject.needsUpdate = true;
  18654. }
  18655. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18656. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18657. this.targetObject.matrixWorldNeedsUpdate = true;
  18658. }
  18659. // HasToFromArray
  18660. _setValue_fromArray( buffer, offset ) {
  18661. this.resolvedProperty.fromArray( buffer, offset );
  18662. }
  18663. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18664. this.resolvedProperty.fromArray( buffer, offset );
  18665. this.targetObject.needsUpdate = true;
  18666. }
  18667. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18668. this.resolvedProperty.fromArray( buffer, offset );
  18669. this.targetObject.matrixWorldNeedsUpdate = true;
  18670. }
  18671. _getValue_unbound( targetArray, offset ) {
  18672. this.bind();
  18673. this.getValue( targetArray, offset );
  18674. }
  18675. _setValue_unbound( sourceArray, offset ) {
  18676. this.bind();
  18677. this.setValue( sourceArray, offset );
  18678. }
  18679. // create getter / setter pair for a property in the scene graph
  18680. bind() {
  18681. let targetObject = this.node;
  18682. const parsedPath = this.parsedPath;
  18683. const objectName = parsedPath.objectName;
  18684. const propertyName = parsedPath.propertyName;
  18685. let propertyIndex = parsedPath.propertyIndex;
  18686. if ( ! targetObject ) {
  18687. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18688. this.node = targetObject;
  18689. }
  18690. // set fail state so we can just 'return' on error
  18691. this.getValue = this._getValue_unavailable;
  18692. this.setValue = this._setValue_unavailable;
  18693. // ensure there is a value node
  18694. if ( ! targetObject ) {
  18695. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18696. return;
  18697. }
  18698. if ( objectName ) {
  18699. let objectIndex = parsedPath.objectIndex;
  18700. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18701. switch ( objectName ) {
  18702. case 'materials':
  18703. if ( ! targetObject.material ) {
  18704. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18705. return;
  18706. }
  18707. if ( ! targetObject.material.materials ) {
  18708. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18709. return;
  18710. }
  18711. targetObject = targetObject.material.materials;
  18712. break;
  18713. case 'bones':
  18714. if ( ! targetObject.skeleton ) {
  18715. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18716. return;
  18717. }
  18718. // potential future optimization: skip this if propertyIndex is already an integer
  18719. // and convert the integer string to a true integer.
  18720. targetObject = targetObject.skeleton.bones;
  18721. // support resolving morphTarget names into indices.
  18722. for ( let i = 0; i < targetObject.length; i ++ ) {
  18723. if ( targetObject[ i ].name === objectIndex ) {
  18724. objectIndex = i;
  18725. break;
  18726. }
  18727. }
  18728. break;
  18729. case 'map':
  18730. if ( 'map' in targetObject ) {
  18731. targetObject = targetObject.map;
  18732. break;
  18733. }
  18734. if ( ! targetObject.material ) {
  18735. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18736. return;
  18737. }
  18738. if ( ! targetObject.material.map ) {
  18739. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18740. return;
  18741. }
  18742. targetObject = targetObject.material.map;
  18743. break;
  18744. default:
  18745. if ( targetObject[ objectName ] === undefined ) {
  18746. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18747. return;
  18748. }
  18749. targetObject = targetObject[ objectName ];
  18750. }
  18751. if ( objectIndex !== undefined ) {
  18752. if ( targetObject[ objectIndex ] === undefined ) {
  18753. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18754. return;
  18755. }
  18756. targetObject = targetObject[ objectIndex ];
  18757. }
  18758. }
  18759. // resolve property
  18760. const nodeProperty = targetObject[ propertyName ];
  18761. if ( nodeProperty === undefined ) {
  18762. const nodeName = parsedPath.nodeName;
  18763. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18764. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18765. return;
  18766. }
  18767. // determine versioning scheme
  18768. let versioning = this.Versioning.None;
  18769. this.targetObject = targetObject;
  18770. if ( targetObject.needsUpdate !== undefined ) { // material
  18771. versioning = this.Versioning.NeedsUpdate;
  18772. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18773. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18774. }
  18775. // determine how the property gets bound
  18776. let bindingType = this.BindingType.Direct;
  18777. if ( propertyIndex !== undefined ) {
  18778. // access a sub element of the property array (only primitives are supported right now)
  18779. if ( propertyName === 'morphTargetInfluences' ) {
  18780. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18781. // support resolving morphTarget names into indices.
  18782. if ( ! targetObject.geometry ) {
  18783. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18784. return;
  18785. }
  18786. if ( ! targetObject.geometry.morphAttributes ) {
  18787. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18788. return;
  18789. }
  18790. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18791. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  18792. }
  18793. }
  18794. bindingType = this.BindingType.ArrayElement;
  18795. this.resolvedProperty = nodeProperty;
  18796. this.propertyIndex = propertyIndex;
  18797. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  18798. // must use copy for Object3D.Euler/Quaternion
  18799. bindingType = this.BindingType.HasFromToArray;
  18800. this.resolvedProperty = nodeProperty;
  18801. } else if ( Array.isArray( nodeProperty ) ) {
  18802. bindingType = this.BindingType.EntireArray;
  18803. this.resolvedProperty = nodeProperty;
  18804. } else {
  18805. this.propertyName = propertyName;
  18806. }
  18807. // select getter / setter
  18808. this.getValue = this.GetterByBindingType[ bindingType ];
  18809. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  18810. }
  18811. unbind() {
  18812. this.node = null;
  18813. // back to the prototype version of getValue / setValue
  18814. // note: avoiding to mutate the shape of 'this' via 'delete'
  18815. this.getValue = this._getValue_unbound;
  18816. this.setValue = this._setValue_unbound;
  18817. }
  18818. }
  18819. PropertyBinding.Composite = Composite;
  18820. PropertyBinding.prototype.BindingType = {
  18821. Direct: 0,
  18822. EntireArray: 1,
  18823. ArrayElement: 2,
  18824. HasFromToArray: 3
  18825. };
  18826. PropertyBinding.prototype.Versioning = {
  18827. None: 0,
  18828. NeedsUpdate: 1,
  18829. MatrixWorldNeedsUpdate: 2
  18830. };
  18831. PropertyBinding.prototype.GetterByBindingType = [
  18832. PropertyBinding.prototype._getValue_direct,
  18833. PropertyBinding.prototype._getValue_array,
  18834. PropertyBinding.prototype._getValue_arrayElement,
  18835. PropertyBinding.prototype._getValue_toArray,
  18836. ];
  18837. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  18838. [
  18839. // Direct
  18840. PropertyBinding.prototype._setValue_direct,
  18841. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  18842. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  18843. ], [
  18844. // EntireArray
  18845. PropertyBinding.prototype._setValue_array,
  18846. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  18847. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  18848. ], [
  18849. // ArrayElement
  18850. PropertyBinding.prototype._setValue_arrayElement,
  18851. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  18852. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  18853. ], [
  18854. // HasToFromArray
  18855. PropertyBinding.prototype._setValue_fromArray,
  18856. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  18857. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  18858. ]
  18859. ];
  18860. /**
  18861. *
  18862. * A group of objects that receives a shared animation state.
  18863. *
  18864. * Usage:
  18865. *
  18866. * - Add objects you would otherwise pass as 'root' to the
  18867. * constructor or the .clipAction method of AnimationMixer.
  18868. *
  18869. * - Instead pass this object as 'root'.
  18870. *
  18871. * - You can also add and remove objects later when the mixer
  18872. * is running.
  18873. *
  18874. * Note:
  18875. *
  18876. * Objects of this class appear as one object to the mixer,
  18877. * so cache control of the individual objects must be done
  18878. * on the group.
  18879. *
  18880. * Limitation:
  18881. *
  18882. * - The animated properties must be compatible among the
  18883. * all objects in the group.
  18884. *
  18885. * - A single property can either be controlled through a
  18886. * target group or directly, but not both.
  18887. */
  18888. class AnimationObjectGroup {
  18889. constructor() {
  18890. this.isAnimationObjectGroup = true;
  18891. this.uuid = generateUUID();
  18892. // cached objects followed by the active ones
  18893. this._objects = Array.prototype.slice.call( arguments );
  18894. this.nCachedObjects_ = 0; // threshold
  18895. // note: read by PropertyBinding.Composite
  18896. const indices = {};
  18897. this._indicesByUUID = indices; // for bookkeeping
  18898. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18899. indices[ arguments[ i ].uuid ] = i;
  18900. }
  18901. this._paths = []; // inside: string
  18902. this._parsedPaths = []; // inside: { we don't care, here }
  18903. this._bindings = []; // inside: Array< PropertyBinding >
  18904. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  18905. const scope = this;
  18906. this.stats = {
  18907. objects: {
  18908. get total() {
  18909. return scope._objects.length;
  18910. },
  18911. get inUse() {
  18912. return this.total - scope.nCachedObjects_;
  18913. }
  18914. },
  18915. get bindingsPerObject() {
  18916. return scope._bindings.length;
  18917. }
  18918. };
  18919. }
  18920. add() {
  18921. const objects = this._objects,
  18922. indicesByUUID = this._indicesByUUID,
  18923. paths = this._paths,
  18924. parsedPaths = this._parsedPaths,
  18925. bindings = this._bindings,
  18926. nBindings = bindings.length;
  18927. let knownObject = undefined,
  18928. nObjects = objects.length,
  18929. nCachedObjects = this.nCachedObjects_;
  18930. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18931. const object = arguments[ i ],
  18932. uuid = object.uuid;
  18933. let index = indicesByUUID[ uuid ];
  18934. if ( index === undefined ) {
  18935. // unknown object -> add it to the ACTIVE region
  18936. index = nObjects ++;
  18937. indicesByUUID[ uuid ] = index;
  18938. objects.push( object );
  18939. // accounting is done, now do the same for all bindings
  18940. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18941. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  18942. }
  18943. } else if ( index < nCachedObjects ) {
  18944. knownObject = objects[ index ];
  18945. // move existing object to the ACTIVE region
  18946. const firstActiveIndex = -- nCachedObjects,
  18947. lastCachedObject = objects[ firstActiveIndex ];
  18948. indicesByUUID[ lastCachedObject.uuid ] = index;
  18949. objects[ index ] = lastCachedObject;
  18950. indicesByUUID[ uuid ] = firstActiveIndex;
  18951. objects[ firstActiveIndex ] = object;
  18952. // accounting is done, now do the same for all bindings
  18953. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18954. const bindingsForPath = bindings[ j ],
  18955. lastCached = bindingsForPath[ firstActiveIndex ];
  18956. let binding = bindingsForPath[ index ];
  18957. bindingsForPath[ index ] = lastCached;
  18958. if ( binding === undefined ) {
  18959. // since we do not bother to create new bindings
  18960. // for objects that are cached, the binding may
  18961. // or may not exist
  18962. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  18963. }
  18964. bindingsForPath[ firstActiveIndex ] = binding;
  18965. }
  18966. } else if ( objects[ index ] !== knownObject ) {
  18967. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  18968. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  18969. } // else the object is already where we want it to be
  18970. } // for arguments
  18971. this.nCachedObjects_ = nCachedObjects;
  18972. }
  18973. remove() {
  18974. const objects = this._objects,
  18975. indicesByUUID = this._indicesByUUID,
  18976. bindings = this._bindings,
  18977. nBindings = bindings.length;
  18978. let nCachedObjects = this.nCachedObjects_;
  18979. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18980. const object = arguments[ i ],
  18981. uuid = object.uuid,
  18982. index = indicesByUUID[ uuid ];
  18983. if ( index !== undefined && index >= nCachedObjects ) {
  18984. // move existing object into the CACHED region
  18985. const lastCachedIndex = nCachedObjects ++,
  18986. firstActiveObject = objects[ lastCachedIndex ];
  18987. indicesByUUID[ firstActiveObject.uuid ] = index;
  18988. objects[ index ] = firstActiveObject;
  18989. indicesByUUID[ uuid ] = lastCachedIndex;
  18990. objects[ lastCachedIndex ] = object;
  18991. // accounting is done, now do the same for all bindings
  18992. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18993. const bindingsForPath = bindings[ j ],
  18994. firstActive = bindingsForPath[ lastCachedIndex ],
  18995. binding = bindingsForPath[ index ];
  18996. bindingsForPath[ index ] = firstActive;
  18997. bindingsForPath[ lastCachedIndex ] = binding;
  18998. }
  18999. }
  19000. } // for arguments
  19001. this.nCachedObjects_ = nCachedObjects;
  19002. }
  19003. // remove & forget
  19004. uncache() {
  19005. const objects = this._objects,
  19006. indicesByUUID = this._indicesByUUID,
  19007. bindings = this._bindings,
  19008. nBindings = bindings.length;
  19009. let nCachedObjects = this.nCachedObjects_,
  19010. nObjects = objects.length;
  19011. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19012. const object = arguments[ i ],
  19013. uuid = object.uuid,
  19014. index = indicesByUUID[ uuid ];
  19015. if ( index !== undefined ) {
  19016. delete indicesByUUID[ uuid ];
  19017. if ( index < nCachedObjects ) {
  19018. // object is cached, shrink the CACHED region
  19019. const firstActiveIndex = -- nCachedObjects,
  19020. lastCachedObject = objects[ firstActiveIndex ],
  19021. lastIndex = -- nObjects,
  19022. lastObject = objects[ lastIndex ];
  19023. // last cached object takes this object's place
  19024. indicesByUUID[ lastCachedObject.uuid ] = index;
  19025. objects[ index ] = lastCachedObject;
  19026. // last object goes to the activated slot and pop
  19027. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19028. objects[ firstActiveIndex ] = lastObject;
  19029. objects.pop();
  19030. // accounting is done, now do the same for all bindings
  19031. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19032. const bindingsForPath = bindings[ j ],
  19033. lastCached = bindingsForPath[ firstActiveIndex ],
  19034. last = bindingsForPath[ lastIndex ];
  19035. bindingsForPath[ index ] = lastCached;
  19036. bindingsForPath[ firstActiveIndex ] = last;
  19037. bindingsForPath.pop();
  19038. }
  19039. } else {
  19040. // object is active, just swap with the last and pop
  19041. const lastIndex = -- nObjects,
  19042. lastObject = objects[ lastIndex ];
  19043. if ( lastIndex > 0 ) {
  19044. indicesByUUID[ lastObject.uuid ] = index;
  19045. }
  19046. objects[ index ] = lastObject;
  19047. objects.pop();
  19048. // accounting is done, now do the same for all bindings
  19049. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19050. const bindingsForPath = bindings[ j ];
  19051. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19052. bindingsForPath.pop();
  19053. }
  19054. } // cached or active
  19055. } // if object is known
  19056. } // for arguments
  19057. this.nCachedObjects_ = nCachedObjects;
  19058. }
  19059. // Internal interface used by befriended PropertyBinding.Composite:
  19060. subscribe_( path, parsedPath ) {
  19061. // returns an array of bindings for the given path that is changed
  19062. // according to the contained objects in the group
  19063. const indicesByPath = this._bindingsIndicesByPath;
  19064. let index = indicesByPath[ path ];
  19065. const bindings = this._bindings;
  19066. if ( index !== undefined ) return bindings[ index ];
  19067. const paths = this._paths,
  19068. parsedPaths = this._parsedPaths,
  19069. objects = this._objects,
  19070. nObjects = objects.length,
  19071. nCachedObjects = this.nCachedObjects_,
  19072. bindingsForPath = new Array( nObjects );
  19073. index = bindings.length;
  19074. indicesByPath[ path ] = index;
  19075. paths.push( path );
  19076. parsedPaths.push( parsedPath );
  19077. bindings.push( bindingsForPath );
  19078. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19079. const object = objects[ i ];
  19080. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19081. }
  19082. return bindingsForPath;
  19083. }
  19084. unsubscribe_( path ) {
  19085. // tells the group to forget about a property path and no longer
  19086. // update the array previously obtained with 'subscribe_'
  19087. const indicesByPath = this._bindingsIndicesByPath,
  19088. index = indicesByPath[ path ];
  19089. if ( index !== undefined ) {
  19090. const paths = this._paths,
  19091. parsedPaths = this._parsedPaths,
  19092. bindings = this._bindings,
  19093. lastBindingsIndex = bindings.length - 1,
  19094. lastBindings = bindings[ lastBindingsIndex ],
  19095. lastBindingsPath = path[ lastBindingsIndex ];
  19096. indicesByPath[ lastBindingsPath ] = index;
  19097. bindings[ index ] = lastBindings;
  19098. bindings.pop();
  19099. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19100. parsedPaths.pop();
  19101. paths[ index ] = paths[ lastBindingsIndex ];
  19102. paths.pop();
  19103. }
  19104. }
  19105. }
  19106. class AnimationAction {
  19107. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19108. this._mixer = mixer;
  19109. this._clip = clip;
  19110. this._localRoot = localRoot;
  19111. this.blendMode = blendMode;
  19112. const tracks = clip.tracks,
  19113. nTracks = tracks.length,
  19114. interpolants = new Array( nTracks );
  19115. const interpolantSettings = {
  19116. endingStart: ZeroCurvatureEnding,
  19117. endingEnd: ZeroCurvatureEnding
  19118. };
  19119. for ( let i = 0; i !== nTracks; ++ i ) {
  19120. const interpolant = tracks[ i ].createInterpolant( null );
  19121. interpolants[ i ] = interpolant;
  19122. interpolant.settings = interpolantSettings;
  19123. }
  19124. this._interpolantSettings = interpolantSettings;
  19125. this._interpolants = interpolants; // bound by the mixer
  19126. // inside: PropertyMixer (managed by the mixer)
  19127. this._propertyBindings = new Array( nTracks );
  19128. this._cacheIndex = null; // for the memory manager
  19129. this._byClipCacheIndex = null; // for the memory manager
  19130. this._timeScaleInterpolant = null;
  19131. this._weightInterpolant = null;
  19132. this.loop = LoopRepeat;
  19133. this._loopCount = - 1;
  19134. // global mixer time when the action is to be started
  19135. // it's set back to 'null' upon start of the action
  19136. this._startTime = null;
  19137. // scaled local time of the action
  19138. // gets clamped or wrapped to 0..clip.duration according to loop
  19139. this.time = 0;
  19140. this.timeScale = 1;
  19141. this._effectiveTimeScale = 1;
  19142. this.weight = 1;
  19143. this._effectiveWeight = 1;
  19144. this.repetitions = Infinity; // no. of repetitions when looping
  19145. this.paused = false; // true -> zero effective time scale
  19146. this.enabled = true; // false -> zero effective weight
  19147. this.clampWhenFinished = false;// keep feeding the last frame?
  19148. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19149. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19150. }
  19151. // State & Scheduling
  19152. play() {
  19153. this._mixer._activateAction( this );
  19154. return this;
  19155. }
  19156. stop() {
  19157. this._mixer._deactivateAction( this );
  19158. return this.reset();
  19159. }
  19160. reset() {
  19161. this.paused = false;
  19162. this.enabled = true;
  19163. this.time = 0; // restart clip
  19164. this._loopCount = - 1;// forget previous loops
  19165. this._startTime = null;// forget scheduling
  19166. return this.stopFading().stopWarping();
  19167. }
  19168. isRunning() {
  19169. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19170. this._startTime === null && this._mixer._isActiveAction( this );
  19171. }
  19172. // return true when play has been called
  19173. isScheduled() {
  19174. return this._mixer._isActiveAction( this );
  19175. }
  19176. startAt( time ) {
  19177. this._startTime = time;
  19178. return this;
  19179. }
  19180. setLoop( mode, repetitions ) {
  19181. this.loop = mode;
  19182. this.repetitions = repetitions;
  19183. return this;
  19184. }
  19185. // Weight
  19186. // set the weight stopping any scheduled fading
  19187. // although .enabled = false yields an effective weight of zero, this
  19188. // method does *not* change .enabled, because it would be confusing
  19189. setEffectiveWeight( weight ) {
  19190. this.weight = weight;
  19191. // note: same logic as when updated at runtime
  19192. this._effectiveWeight = this.enabled ? weight : 0;
  19193. return this.stopFading();
  19194. }
  19195. // return the weight considering fading and .enabled
  19196. getEffectiveWeight() {
  19197. return this._effectiveWeight;
  19198. }
  19199. fadeIn( duration ) {
  19200. return this._scheduleFading( duration, 0, 1 );
  19201. }
  19202. fadeOut( duration ) {
  19203. return this._scheduleFading( duration, 1, 0 );
  19204. }
  19205. crossFadeFrom( fadeOutAction, duration, warp ) {
  19206. fadeOutAction.fadeOut( duration );
  19207. this.fadeIn( duration );
  19208. if ( warp ) {
  19209. const fadeInDuration = this._clip.duration,
  19210. fadeOutDuration = fadeOutAction._clip.duration,
  19211. startEndRatio = fadeOutDuration / fadeInDuration,
  19212. endStartRatio = fadeInDuration / fadeOutDuration;
  19213. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19214. this.warp( endStartRatio, 1.0, duration );
  19215. }
  19216. return this;
  19217. }
  19218. crossFadeTo( fadeInAction, duration, warp ) {
  19219. return fadeInAction.crossFadeFrom( this, duration, warp );
  19220. }
  19221. stopFading() {
  19222. const weightInterpolant = this._weightInterpolant;
  19223. if ( weightInterpolant !== null ) {
  19224. this._weightInterpolant = null;
  19225. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19226. }
  19227. return this;
  19228. }
  19229. // Time Scale Control
  19230. // set the time scale stopping any scheduled warping
  19231. // although .paused = true yields an effective time scale of zero, this
  19232. // method does *not* change .paused, because it would be confusing
  19233. setEffectiveTimeScale( timeScale ) {
  19234. this.timeScale = timeScale;
  19235. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19236. return this.stopWarping();
  19237. }
  19238. // return the time scale considering warping and .paused
  19239. getEffectiveTimeScale() {
  19240. return this._effectiveTimeScale;
  19241. }
  19242. setDuration( duration ) {
  19243. this.timeScale = this._clip.duration / duration;
  19244. return this.stopWarping();
  19245. }
  19246. syncWith( action ) {
  19247. this.time = action.time;
  19248. this.timeScale = action.timeScale;
  19249. return this.stopWarping();
  19250. }
  19251. halt( duration ) {
  19252. return this.warp( this._effectiveTimeScale, 0, duration );
  19253. }
  19254. warp( startTimeScale, endTimeScale, duration ) {
  19255. const mixer = this._mixer,
  19256. now = mixer.time,
  19257. timeScale = this.timeScale;
  19258. let interpolant = this._timeScaleInterpolant;
  19259. if ( interpolant === null ) {
  19260. interpolant = mixer._lendControlInterpolant();
  19261. this._timeScaleInterpolant = interpolant;
  19262. }
  19263. const times = interpolant.parameterPositions,
  19264. values = interpolant.sampleValues;
  19265. times[ 0 ] = now;
  19266. times[ 1 ] = now + duration;
  19267. values[ 0 ] = startTimeScale / timeScale;
  19268. values[ 1 ] = endTimeScale / timeScale;
  19269. return this;
  19270. }
  19271. stopWarping() {
  19272. const timeScaleInterpolant = this._timeScaleInterpolant;
  19273. if ( timeScaleInterpolant !== null ) {
  19274. this._timeScaleInterpolant = null;
  19275. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19276. }
  19277. return this;
  19278. }
  19279. // Object Accessors
  19280. getMixer() {
  19281. return this._mixer;
  19282. }
  19283. getClip() {
  19284. return this._clip;
  19285. }
  19286. getRoot() {
  19287. return this._localRoot || this._mixer._root;
  19288. }
  19289. // Interna
  19290. _update( time, deltaTime, timeDirection, accuIndex ) {
  19291. // called by the mixer
  19292. if ( ! this.enabled ) {
  19293. // call ._updateWeight() to update ._effectiveWeight
  19294. this._updateWeight( time );
  19295. return;
  19296. }
  19297. const startTime = this._startTime;
  19298. if ( startTime !== null ) {
  19299. // check for scheduled start of action
  19300. const timeRunning = ( time - startTime ) * timeDirection;
  19301. if ( timeRunning < 0 || timeDirection === 0 ) {
  19302. deltaTime = 0;
  19303. } else {
  19304. this._startTime = null; // unschedule
  19305. deltaTime = timeDirection * timeRunning;
  19306. }
  19307. }
  19308. // apply time scale and advance time
  19309. deltaTime *= this._updateTimeScale( time );
  19310. const clipTime = this._updateTime( deltaTime );
  19311. // note: _updateTime may disable the action resulting in
  19312. // an effective weight of 0
  19313. const weight = this._updateWeight( time );
  19314. if ( weight > 0 ) {
  19315. const interpolants = this._interpolants;
  19316. const propertyMixers = this._propertyBindings;
  19317. switch ( this.blendMode ) {
  19318. case AdditiveAnimationBlendMode:
  19319. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19320. interpolants[ j ].evaluate( clipTime );
  19321. propertyMixers[ j ].accumulateAdditive( weight );
  19322. }
  19323. break;
  19324. case NormalAnimationBlendMode:
  19325. default:
  19326. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19327. interpolants[ j ].evaluate( clipTime );
  19328. propertyMixers[ j ].accumulate( accuIndex, weight );
  19329. }
  19330. }
  19331. }
  19332. }
  19333. _updateWeight( time ) {
  19334. let weight = 0;
  19335. if ( this.enabled ) {
  19336. weight = this.weight;
  19337. const interpolant = this._weightInterpolant;
  19338. if ( interpolant !== null ) {
  19339. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19340. weight *= interpolantValue;
  19341. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19342. this.stopFading();
  19343. if ( interpolantValue === 0 ) {
  19344. // faded out, disable
  19345. this.enabled = false;
  19346. }
  19347. }
  19348. }
  19349. }
  19350. this._effectiveWeight = weight;
  19351. return weight;
  19352. }
  19353. _updateTimeScale( time ) {
  19354. let timeScale = 0;
  19355. if ( ! this.paused ) {
  19356. timeScale = this.timeScale;
  19357. const interpolant = this._timeScaleInterpolant;
  19358. if ( interpolant !== null ) {
  19359. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19360. timeScale *= interpolantValue;
  19361. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19362. this.stopWarping();
  19363. if ( timeScale === 0 ) {
  19364. // motion has halted, pause
  19365. this.paused = true;
  19366. } else {
  19367. // warp done - apply final time scale
  19368. this.timeScale = timeScale;
  19369. }
  19370. }
  19371. }
  19372. }
  19373. this._effectiveTimeScale = timeScale;
  19374. return timeScale;
  19375. }
  19376. _updateTime( deltaTime ) {
  19377. const duration = this._clip.duration;
  19378. const loop = this.loop;
  19379. let time = this.time + deltaTime;
  19380. let loopCount = this._loopCount;
  19381. const pingPong = ( loop === LoopPingPong );
  19382. if ( deltaTime === 0 ) {
  19383. if ( loopCount === - 1 ) return time;
  19384. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19385. }
  19386. if ( loop === LoopOnce ) {
  19387. if ( loopCount === - 1 ) {
  19388. // just started
  19389. this._loopCount = 0;
  19390. this._setEndings( true, true, false );
  19391. }
  19392. handle_stop: {
  19393. if ( time >= duration ) {
  19394. time = duration;
  19395. } else if ( time < 0 ) {
  19396. time = 0;
  19397. } else {
  19398. this.time = time;
  19399. break handle_stop;
  19400. }
  19401. if ( this.clampWhenFinished ) this.paused = true;
  19402. else this.enabled = false;
  19403. this.time = time;
  19404. this._mixer.dispatchEvent( {
  19405. type: 'finished', action: this,
  19406. direction: deltaTime < 0 ? - 1 : 1
  19407. } );
  19408. }
  19409. } else { // repetitive Repeat or PingPong
  19410. if ( loopCount === - 1 ) {
  19411. // just started
  19412. if ( deltaTime >= 0 ) {
  19413. loopCount = 0;
  19414. this._setEndings( true, this.repetitions === 0, pingPong );
  19415. } else {
  19416. // when looping in reverse direction, the initial
  19417. // transition through zero counts as a repetition,
  19418. // so leave loopCount at -1
  19419. this._setEndings( this.repetitions === 0, true, pingPong );
  19420. }
  19421. }
  19422. if ( time >= duration || time < 0 ) {
  19423. // wrap around
  19424. const loopDelta = Math.floor( time / duration ); // signed
  19425. time -= duration * loopDelta;
  19426. loopCount += Math.abs( loopDelta );
  19427. const pending = this.repetitions - loopCount;
  19428. if ( pending <= 0 ) {
  19429. // have to stop (switch state, clamp time, fire event)
  19430. if ( this.clampWhenFinished ) this.paused = true;
  19431. else this.enabled = false;
  19432. time = deltaTime > 0 ? duration : 0;
  19433. this.time = time;
  19434. this._mixer.dispatchEvent( {
  19435. type: 'finished', action: this,
  19436. direction: deltaTime > 0 ? 1 : - 1
  19437. } );
  19438. } else {
  19439. // keep running
  19440. if ( pending === 1 ) {
  19441. // entering the last round
  19442. const atStart = deltaTime < 0;
  19443. this._setEndings( atStart, ! atStart, pingPong );
  19444. } else {
  19445. this._setEndings( false, false, pingPong );
  19446. }
  19447. this._loopCount = loopCount;
  19448. this.time = time;
  19449. this._mixer.dispatchEvent( {
  19450. type: 'loop', action: this, loopDelta: loopDelta
  19451. } );
  19452. }
  19453. } else {
  19454. this.time = time;
  19455. }
  19456. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19457. // invert time for the "pong round"
  19458. return duration - time;
  19459. }
  19460. }
  19461. return time;
  19462. }
  19463. _setEndings( atStart, atEnd, pingPong ) {
  19464. const settings = this._interpolantSettings;
  19465. if ( pingPong ) {
  19466. settings.endingStart = ZeroSlopeEnding;
  19467. settings.endingEnd = ZeroSlopeEnding;
  19468. } else {
  19469. // assuming for LoopOnce atStart == atEnd == true
  19470. if ( atStart ) {
  19471. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19472. } else {
  19473. settings.endingStart = WrapAroundEnding;
  19474. }
  19475. if ( atEnd ) {
  19476. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19477. } else {
  19478. settings.endingEnd = WrapAroundEnding;
  19479. }
  19480. }
  19481. }
  19482. _scheduleFading( duration, weightNow, weightThen ) {
  19483. const mixer = this._mixer, now = mixer.time;
  19484. let interpolant = this._weightInterpolant;
  19485. if ( interpolant === null ) {
  19486. interpolant = mixer._lendControlInterpolant();
  19487. this._weightInterpolant = interpolant;
  19488. }
  19489. const times = interpolant.parameterPositions,
  19490. values = interpolant.sampleValues;
  19491. times[ 0 ] = now;
  19492. values[ 0 ] = weightNow;
  19493. times[ 1 ] = now + duration;
  19494. values[ 1 ] = weightThen;
  19495. return this;
  19496. }
  19497. }
  19498. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19499. class AnimationMixer extends EventDispatcher {
  19500. constructor( root ) {
  19501. super();
  19502. this._root = root;
  19503. this._initMemoryManager();
  19504. this._accuIndex = 0;
  19505. this.time = 0;
  19506. this.timeScale = 1.0;
  19507. }
  19508. _bindAction( action, prototypeAction ) {
  19509. const root = action._localRoot || this._root,
  19510. tracks = action._clip.tracks,
  19511. nTracks = tracks.length,
  19512. bindings = action._propertyBindings,
  19513. interpolants = action._interpolants,
  19514. rootUuid = root.uuid,
  19515. bindingsByRoot = this._bindingsByRootAndName;
  19516. let bindingsByName = bindingsByRoot[ rootUuid ];
  19517. if ( bindingsByName === undefined ) {
  19518. bindingsByName = {};
  19519. bindingsByRoot[ rootUuid ] = bindingsByName;
  19520. }
  19521. for ( let i = 0; i !== nTracks; ++ i ) {
  19522. const track = tracks[ i ],
  19523. trackName = track.name;
  19524. let binding = bindingsByName[ trackName ];
  19525. if ( binding !== undefined ) {
  19526. ++ binding.referenceCount;
  19527. bindings[ i ] = binding;
  19528. } else {
  19529. binding = bindings[ i ];
  19530. if ( binding !== undefined ) {
  19531. // existing binding, make sure the cache knows
  19532. if ( binding._cacheIndex === null ) {
  19533. ++ binding.referenceCount;
  19534. this._addInactiveBinding( binding, rootUuid, trackName );
  19535. }
  19536. continue;
  19537. }
  19538. const path = prototypeAction && prototypeAction.
  19539. _propertyBindings[ i ].binding.parsedPath;
  19540. binding = new PropertyMixer(
  19541. PropertyBinding.create( root, trackName, path ),
  19542. track.ValueTypeName, track.getValueSize() );
  19543. ++ binding.referenceCount;
  19544. this._addInactiveBinding( binding, rootUuid, trackName );
  19545. bindings[ i ] = binding;
  19546. }
  19547. interpolants[ i ].resultBuffer = binding.buffer;
  19548. }
  19549. }
  19550. _activateAction( action ) {
  19551. if ( ! this._isActiveAction( action ) ) {
  19552. if ( action._cacheIndex === null ) {
  19553. // this action has been forgotten by the cache, but the user
  19554. // appears to be still using it -> rebind
  19555. const rootUuid = ( action._localRoot || this._root ).uuid,
  19556. clipUuid = action._clip.uuid,
  19557. actionsForClip = this._actionsByClip[ clipUuid ];
  19558. this._bindAction( action,
  19559. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19560. this._addInactiveAction( action, clipUuid, rootUuid );
  19561. }
  19562. const bindings = action._propertyBindings;
  19563. // increment reference counts / sort out state
  19564. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19565. const binding = bindings[ i ];
  19566. if ( binding.useCount ++ === 0 ) {
  19567. this._lendBinding( binding );
  19568. binding.saveOriginalState();
  19569. }
  19570. }
  19571. this._lendAction( action );
  19572. }
  19573. }
  19574. _deactivateAction( action ) {
  19575. if ( this._isActiveAction( action ) ) {
  19576. const bindings = action._propertyBindings;
  19577. // decrement reference counts / sort out state
  19578. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19579. const binding = bindings[ i ];
  19580. if ( -- binding.useCount === 0 ) {
  19581. binding.restoreOriginalState();
  19582. this._takeBackBinding( binding );
  19583. }
  19584. }
  19585. this._takeBackAction( action );
  19586. }
  19587. }
  19588. // Memory manager
  19589. _initMemoryManager() {
  19590. this._actions = []; // 'nActiveActions' followed by inactive ones
  19591. this._nActiveActions = 0;
  19592. this._actionsByClip = {};
  19593. // inside:
  19594. // {
  19595. // knownActions: Array< AnimationAction > - used as prototypes
  19596. // actionByRoot: AnimationAction - lookup
  19597. // }
  19598. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19599. this._nActiveBindings = 0;
  19600. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19601. this._controlInterpolants = []; // same game as above
  19602. this._nActiveControlInterpolants = 0;
  19603. const scope = this;
  19604. this.stats = {
  19605. actions: {
  19606. get total() {
  19607. return scope._actions.length;
  19608. },
  19609. get inUse() {
  19610. return scope._nActiveActions;
  19611. }
  19612. },
  19613. bindings: {
  19614. get total() {
  19615. return scope._bindings.length;
  19616. },
  19617. get inUse() {
  19618. return scope._nActiveBindings;
  19619. }
  19620. },
  19621. controlInterpolants: {
  19622. get total() {
  19623. return scope._controlInterpolants.length;
  19624. },
  19625. get inUse() {
  19626. return scope._nActiveControlInterpolants;
  19627. }
  19628. }
  19629. };
  19630. }
  19631. // Memory management for AnimationAction objects
  19632. _isActiveAction( action ) {
  19633. const index = action._cacheIndex;
  19634. return index !== null && index < this._nActiveActions;
  19635. }
  19636. _addInactiveAction( action, clipUuid, rootUuid ) {
  19637. const actions = this._actions,
  19638. actionsByClip = this._actionsByClip;
  19639. let actionsForClip = actionsByClip[ clipUuid ];
  19640. if ( actionsForClip === undefined ) {
  19641. actionsForClip = {
  19642. knownActions: [ action ],
  19643. actionByRoot: {}
  19644. };
  19645. action._byClipCacheIndex = 0;
  19646. actionsByClip[ clipUuid ] = actionsForClip;
  19647. } else {
  19648. const knownActions = actionsForClip.knownActions;
  19649. action._byClipCacheIndex = knownActions.length;
  19650. knownActions.push( action );
  19651. }
  19652. action._cacheIndex = actions.length;
  19653. actions.push( action );
  19654. actionsForClip.actionByRoot[ rootUuid ] = action;
  19655. }
  19656. _removeInactiveAction( action ) {
  19657. const actions = this._actions,
  19658. lastInactiveAction = actions[ actions.length - 1 ],
  19659. cacheIndex = action._cacheIndex;
  19660. lastInactiveAction._cacheIndex = cacheIndex;
  19661. actions[ cacheIndex ] = lastInactiveAction;
  19662. actions.pop();
  19663. action._cacheIndex = null;
  19664. const clipUuid = action._clip.uuid,
  19665. actionsByClip = this._actionsByClip,
  19666. actionsForClip = actionsByClip[ clipUuid ],
  19667. knownActionsForClip = actionsForClip.knownActions,
  19668. lastKnownAction =
  19669. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19670. byClipCacheIndex = action._byClipCacheIndex;
  19671. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19672. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19673. knownActionsForClip.pop();
  19674. action._byClipCacheIndex = null;
  19675. const actionByRoot = actionsForClip.actionByRoot,
  19676. rootUuid = ( action._localRoot || this._root ).uuid;
  19677. delete actionByRoot[ rootUuid ];
  19678. if ( knownActionsForClip.length === 0 ) {
  19679. delete actionsByClip[ clipUuid ];
  19680. }
  19681. this._removeInactiveBindingsForAction( action );
  19682. }
  19683. _removeInactiveBindingsForAction( action ) {
  19684. const bindings = action._propertyBindings;
  19685. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19686. const binding = bindings[ i ];
  19687. if ( -- binding.referenceCount === 0 ) {
  19688. this._removeInactiveBinding( binding );
  19689. }
  19690. }
  19691. }
  19692. _lendAction( action ) {
  19693. // [ active actions | inactive actions ]
  19694. // [ active actions >| inactive actions ]
  19695. // s a
  19696. // <-swap->
  19697. // a s
  19698. const actions = this._actions,
  19699. prevIndex = action._cacheIndex,
  19700. lastActiveIndex = this._nActiveActions ++,
  19701. firstInactiveAction = actions[ lastActiveIndex ];
  19702. action._cacheIndex = lastActiveIndex;
  19703. actions[ lastActiveIndex ] = action;
  19704. firstInactiveAction._cacheIndex = prevIndex;
  19705. actions[ prevIndex ] = firstInactiveAction;
  19706. }
  19707. _takeBackAction( action ) {
  19708. // [ active actions | inactive actions ]
  19709. // [ active actions |< inactive actions ]
  19710. // a s
  19711. // <-swap->
  19712. // s a
  19713. const actions = this._actions,
  19714. prevIndex = action._cacheIndex,
  19715. firstInactiveIndex = -- this._nActiveActions,
  19716. lastActiveAction = actions[ firstInactiveIndex ];
  19717. action._cacheIndex = firstInactiveIndex;
  19718. actions[ firstInactiveIndex ] = action;
  19719. lastActiveAction._cacheIndex = prevIndex;
  19720. actions[ prevIndex ] = lastActiveAction;
  19721. }
  19722. // Memory management for PropertyMixer objects
  19723. _addInactiveBinding( binding, rootUuid, trackName ) {
  19724. const bindingsByRoot = this._bindingsByRootAndName,
  19725. bindings = this._bindings;
  19726. let bindingByName = bindingsByRoot[ rootUuid ];
  19727. if ( bindingByName === undefined ) {
  19728. bindingByName = {};
  19729. bindingsByRoot[ rootUuid ] = bindingByName;
  19730. }
  19731. bindingByName[ trackName ] = binding;
  19732. binding._cacheIndex = bindings.length;
  19733. bindings.push( binding );
  19734. }
  19735. _removeInactiveBinding( binding ) {
  19736. const bindings = this._bindings,
  19737. propBinding = binding.binding,
  19738. rootUuid = propBinding.rootNode.uuid,
  19739. trackName = propBinding.path,
  19740. bindingsByRoot = this._bindingsByRootAndName,
  19741. bindingByName = bindingsByRoot[ rootUuid ],
  19742. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19743. cacheIndex = binding._cacheIndex;
  19744. lastInactiveBinding._cacheIndex = cacheIndex;
  19745. bindings[ cacheIndex ] = lastInactiveBinding;
  19746. bindings.pop();
  19747. delete bindingByName[ trackName ];
  19748. if ( Object.keys( bindingByName ).length === 0 ) {
  19749. delete bindingsByRoot[ rootUuid ];
  19750. }
  19751. }
  19752. _lendBinding( binding ) {
  19753. const bindings = this._bindings,
  19754. prevIndex = binding._cacheIndex,
  19755. lastActiveIndex = this._nActiveBindings ++,
  19756. firstInactiveBinding = bindings[ lastActiveIndex ];
  19757. binding._cacheIndex = lastActiveIndex;
  19758. bindings[ lastActiveIndex ] = binding;
  19759. firstInactiveBinding._cacheIndex = prevIndex;
  19760. bindings[ prevIndex ] = firstInactiveBinding;
  19761. }
  19762. _takeBackBinding( binding ) {
  19763. const bindings = this._bindings,
  19764. prevIndex = binding._cacheIndex,
  19765. firstInactiveIndex = -- this._nActiveBindings,
  19766. lastActiveBinding = bindings[ firstInactiveIndex ];
  19767. binding._cacheIndex = firstInactiveIndex;
  19768. bindings[ firstInactiveIndex ] = binding;
  19769. lastActiveBinding._cacheIndex = prevIndex;
  19770. bindings[ prevIndex ] = lastActiveBinding;
  19771. }
  19772. // Memory management of Interpolants for weight and time scale
  19773. _lendControlInterpolant() {
  19774. const interpolants = this._controlInterpolants,
  19775. lastActiveIndex = this._nActiveControlInterpolants ++;
  19776. let interpolant = interpolants[ lastActiveIndex ];
  19777. if ( interpolant === undefined ) {
  19778. interpolant = new LinearInterpolant(
  19779. new Float32Array( 2 ), new Float32Array( 2 ),
  19780. 1, _controlInterpolantsResultBuffer );
  19781. interpolant.__cacheIndex = lastActiveIndex;
  19782. interpolants[ lastActiveIndex ] = interpolant;
  19783. }
  19784. return interpolant;
  19785. }
  19786. _takeBackControlInterpolant( interpolant ) {
  19787. const interpolants = this._controlInterpolants,
  19788. prevIndex = interpolant.__cacheIndex,
  19789. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19790. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19791. interpolant.__cacheIndex = firstInactiveIndex;
  19792. interpolants[ firstInactiveIndex ] = interpolant;
  19793. lastActiveInterpolant.__cacheIndex = prevIndex;
  19794. interpolants[ prevIndex ] = lastActiveInterpolant;
  19795. }
  19796. // return an action for a clip optionally using a custom root target
  19797. // object (this method allocates a lot of dynamic memory in case a
  19798. // previously unknown clip/root combination is specified)
  19799. clipAction( clip, optionalRoot, blendMode ) {
  19800. const root = optionalRoot || this._root,
  19801. rootUuid = root.uuid;
  19802. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  19803. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  19804. const actionsForClip = this._actionsByClip[ clipUuid ];
  19805. let prototypeAction = null;
  19806. if ( blendMode === undefined ) {
  19807. if ( clipObject !== null ) {
  19808. blendMode = clipObject.blendMode;
  19809. } else {
  19810. blendMode = NormalAnimationBlendMode;
  19811. }
  19812. }
  19813. if ( actionsForClip !== undefined ) {
  19814. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  19815. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  19816. return existingAction;
  19817. }
  19818. // we know the clip, so we don't have to parse all
  19819. // the bindings again but can just copy
  19820. prototypeAction = actionsForClip.knownActions[ 0 ];
  19821. // also, take the clip from the prototype action
  19822. if ( clipObject === null )
  19823. clipObject = prototypeAction._clip;
  19824. }
  19825. // clip must be known when specified via string
  19826. if ( clipObject === null ) return null;
  19827. // allocate all resources required to run it
  19828. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  19829. this._bindAction( newAction, prototypeAction );
  19830. // and make the action known to the memory manager
  19831. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19832. return newAction;
  19833. }
  19834. // get an existing action
  19835. existingAction( clip, optionalRoot ) {
  19836. const root = optionalRoot || this._root,
  19837. rootUuid = root.uuid,
  19838. clipObject = typeof clip === 'string' ?
  19839. AnimationClip.findByName( root, clip ) : clip,
  19840. clipUuid = clipObject ? clipObject.uuid : clip,
  19841. actionsForClip = this._actionsByClip[ clipUuid ];
  19842. if ( actionsForClip !== undefined ) {
  19843. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19844. }
  19845. return null;
  19846. }
  19847. // deactivates all previously scheduled actions
  19848. stopAllAction() {
  19849. const actions = this._actions,
  19850. nActions = this._nActiveActions;
  19851. for ( let i = nActions - 1; i >= 0; -- i ) {
  19852. actions[ i ].stop();
  19853. }
  19854. return this;
  19855. }
  19856. // advance the time and update apply the animation
  19857. update( deltaTime ) {
  19858. deltaTime *= this.timeScale;
  19859. const actions = this._actions,
  19860. nActions = this._nActiveActions,
  19861. time = this.time += deltaTime,
  19862. timeDirection = Math.sign( deltaTime ),
  19863. accuIndex = this._accuIndex ^= 1;
  19864. // run active actions
  19865. for ( let i = 0; i !== nActions; ++ i ) {
  19866. const action = actions[ i ];
  19867. action._update( time, deltaTime, timeDirection, accuIndex );
  19868. }
  19869. // update scene graph
  19870. const bindings = this._bindings,
  19871. nBindings = this._nActiveBindings;
  19872. for ( let i = 0; i !== nBindings; ++ i ) {
  19873. bindings[ i ].apply( accuIndex );
  19874. }
  19875. return this;
  19876. }
  19877. // Allows you to seek to a specific time in an animation.
  19878. setTime( timeInSeconds ) {
  19879. this.time = 0; // Zero out time attribute for AnimationMixer object;
  19880. for ( let i = 0; i < this._actions.length; i ++ ) {
  19881. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  19882. }
  19883. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  19884. }
  19885. // return this mixer's root target object
  19886. getRoot() {
  19887. return this._root;
  19888. }
  19889. // free all resources specific to a particular clip
  19890. uncacheClip( clip ) {
  19891. const actions = this._actions,
  19892. clipUuid = clip.uuid,
  19893. actionsByClip = this._actionsByClip,
  19894. actionsForClip = actionsByClip[ clipUuid ];
  19895. if ( actionsForClip !== undefined ) {
  19896. // note: just calling _removeInactiveAction would mess up the
  19897. // iteration state and also require updating the state we can
  19898. // just throw away
  19899. const actionsToRemove = actionsForClip.knownActions;
  19900. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19901. const action = actionsToRemove[ i ];
  19902. this._deactivateAction( action );
  19903. const cacheIndex = action._cacheIndex,
  19904. lastInactiveAction = actions[ actions.length - 1 ];
  19905. action._cacheIndex = null;
  19906. action._byClipCacheIndex = null;
  19907. lastInactiveAction._cacheIndex = cacheIndex;
  19908. actions[ cacheIndex ] = lastInactiveAction;
  19909. actions.pop();
  19910. this._removeInactiveBindingsForAction( action );
  19911. }
  19912. delete actionsByClip[ clipUuid ];
  19913. }
  19914. }
  19915. // free all resources specific to a particular root target object
  19916. uncacheRoot( root ) {
  19917. const rootUuid = root.uuid,
  19918. actionsByClip = this._actionsByClip;
  19919. for ( const clipUuid in actionsByClip ) {
  19920. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19921. action = actionByRoot[ rootUuid ];
  19922. if ( action !== undefined ) {
  19923. this._deactivateAction( action );
  19924. this._removeInactiveAction( action );
  19925. }
  19926. }
  19927. const bindingsByRoot = this._bindingsByRootAndName,
  19928. bindingByName = bindingsByRoot[ rootUuid ];
  19929. if ( bindingByName !== undefined ) {
  19930. for ( const trackName in bindingByName ) {
  19931. const binding = bindingByName[ trackName ];
  19932. binding.restoreOriginalState();
  19933. this._removeInactiveBinding( binding );
  19934. }
  19935. }
  19936. }
  19937. // remove a targeted clip from the cache
  19938. uncacheAction( clip, optionalRoot ) {
  19939. const action = this.existingAction( clip, optionalRoot );
  19940. if ( action !== null ) {
  19941. this._deactivateAction( action );
  19942. this._removeInactiveAction( action );
  19943. }
  19944. }
  19945. }
  19946. let Uniform$1 = class Uniform {
  19947. constructor( value ) {
  19948. this.value = value;
  19949. }
  19950. clone() {
  19951. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  19952. }
  19953. };
  19954. let _id$5 = 0;
  19955. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  19956. constructor() {
  19957. super();
  19958. this.isUniformsGroup = true;
  19959. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  19960. this.name = '';
  19961. this.usage = StaticDrawUsage;
  19962. this.uniforms = [];
  19963. }
  19964. add( uniform ) {
  19965. this.uniforms.push( uniform );
  19966. return this;
  19967. }
  19968. remove( uniform ) {
  19969. const index = this.uniforms.indexOf( uniform );
  19970. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  19971. return this;
  19972. }
  19973. setName( name ) {
  19974. this.name = name;
  19975. return this;
  19976. }
  19977. setUsage( value ) {
  19978. this.usage = value;
  19979. return this;
  19980. }
  19981. dispose() {
  19982. this.dispatchEvent( { type: 'dispose' } );
  19983. return this;
  19984. }
  19985. copy( source ) {
  19986. this.name = source.name;
  19987. this.usage = source.usage;
  19988. const uniformsSource = source.uniforms;
  19989. this.uniforms.length = 0;
  19990. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  19991. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  19992. for ( let j = 0; j < uniforms.length; j ++ ) {
  19993. this.uniforms.push( uniforms[ j ].clone() );
  19994. }
  19995. }
  19996. return this;
  19997. }
  19998. clone() {
  19999. return new this.constructor().copy( this );
  20000. }
  20001. };
  20002. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20003. constructor( array, stride, meshPerAttribute = 1 ) {
  20004. super( array, stride );
  20005. this.isInstancedInterleavedBuffer = true;
  20006. this.meshPerAttribute = meshPerAttribute;
  20007. }
  20008. copy( source ) {
  20009. super.copy( source );
  20010. this.meshPerAttribute = source.meshPerAttribute;
  20011. return this;
  20012. }
  20013. clone( data ) {
  20014. const ib = super.clone( data );
  20015. ib.meshPerAttribute = this.meshPerAttribute;
  20016. return ib;
  20017. }
  20018. toJSON( data ) {
  20019. const json = super.toJSON( data );
  20020. json.isInstancedInterleavedBuffer = true;
  20021. json.meshPerAttribute = this.meshPerAttribute;
  20022. return json;
  20023. }
  20024. }
  20025. class GLBufferAttribute {
  20026. constructor( buffer, type, itemSize, elementSize, count ) {
  20027. this.isGLBufferAttribute = true;
  20028. this.name = '';
  20029. this.buffer = buffer;
  20030. this.type = type;
  20031. this.itemSize = itemSize;
  20032. this.elementSize = elementSize;
  20033. this.count = count;
  20034. this.version = 0;
  20035. }
  20036. set needsUpdate( value ) {
  20037. if ( value === true ) this.version ++;
  20038. }
  20039. setBuffer( buffer ) {
  20040. this.buffer = buffer;
  20041. return this;
  20042. }
  20043. setType( type, elementSize ) {
  20044. this.type = type;
  20045. this.elementSize = elementSize;
  20046. return this;
  20047. }
  20048. setItemSize( itemSize ) {
  20049. this.itemSize = itemSize;
  20050. return this;
  20051. }
  20052. setCount( count ) {
  20053. this.count = count;
  20054. return this;
  20055. }
  20056. }
  20057. const _matrix = /*@__PURE__*/ new Matrix4();
  20058. class Raycaster {
  20059. constructor( origin, direction, near = 0, far = Infinity ) {
  20060. this.ray = new Ray( origin, direction );
  20061. // direction is assumed to be normalized (for accurate distance calculations)
  20062. this.near = near;
  20063. this.far = far;
  20064. this.camera = null;
  20065. this.layers = new Layers();
  20066. this.params = {
  20067. Mesh: {},
  20068. Line: { threshold: 1 },
  20069. LOD: {},
  20070. Points: { threshold: 1 },
  20071. Sprite: {}
  20072. };
  20073. }
  20074. set( origin, direction ) {
  20075. // direction is assumed to be normalized (for accurate distance calculations)
  20076. this.ray.set( origin, direction );
  20077. }
  20078. setFromCamera( coords, camera ) {
  20079. if ( camera.isPerspectiveCamera ) {
  20080. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20081. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20082. this.camera = camera;
  20083. } else if ( camera.isOrthographicCamera ) {
  20084. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20085. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20086. this.camera = camera;
  20087. } else {
  20088. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20089. }
  20090. }
  20091. setFromXRController( controller ) {
  20092. _matrix.identity().extractRotation( controller.matrixWorld );
  20093. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20094. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20095. return this;
  20096. }
  20097. intersectObject( object, recursive = true, intersects = [] ) {
  20098. intersect( object, this, intersects, recursive );
  20099. intersects.sort( ascSort );
  20100. return intersects;
  20101. }
  20102. intersectObjects( objects, recursive = true, intersects = [] ) {
  20103. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20104. intersect( objects[ i ], this, intersects, recursive );
  20105. }
  20106. intersects.sort( ascSort );
  20107. return intersects;
  20108. }
  20109. }
  20110. function ascSort( a, b ) {
  20111. return a.distance - b.distance;
  20112. }
  20113. function intersect( object, raycaster, intersects, recursive ) {
  20114. let propagate = true;
  20115. if ( object.layers.test( raycaster.layers ) ) {
  20116. const result = object.raycast( raycaster, intersects );
  20117. if ( result === false ) propagate = false;
  20118. }
  20119. if ( propagate === true && recursive === true ) {
  20120. const children = object.children;
  20121. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20122. intersect( children[ i ], raycaster, intersects, true );
  20123. }
  20124. }
  20125. }
  20126. /**
  20127. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20128. *
  20129. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20130. * theta (the azimuthal angle) is measured from the positive z-axis.
  20131. */
  20132. class Spherical {
  20133. constructor( radius = 1, phi = 0, theta = 0 ) {
  20134. this.radius = radius;
  20135. this.phi = phi; // polar angle
  20136. this.theta = theta; // azimuthal angle
  20137. return this;
  20138. }
  20139. set( radius, phi, theta ) {
  20140. this.radius = radius;
  20141. this.phi = phi;
  20142. this.theta = theta;
  20143. return this;
  20144. }
  20145. copy( other ) {
  20146. this.radius = other.radius;
  20147. this.phi = other.phi;
  20148. this.theta = other.theta;
  20149. return this;
  20150. }
  20151. // restrict phi to be between EPS and PI-EPS
  20152. makeSafe() {
  20153. const EPS = 0.000001;
  20154. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20155. return this;
  20156. }
  20157. setFromVector3( v ) {
  20158. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20159. }
  20160. setFromCartesianCoords( x, y, z ) {
  20161. this.radius = Math.sqrt( x * x + y * y + z * z );
  20162. if ( this.radius === 0 ) {
  20163. this.theta = 0;
  20164. this.phi = 0;
  20165. } else {
  20166. this.theta = Math.atan2( x, z );
  20167. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20168. }
  20169. return this;
  20170. }
  20171. clone() {
  20172. return new this.constructor().copy( this );
  20173. }
  20174. }
  20175. /**
  20176. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20177. */
  20178. class Cylindrical {
  20179. constructor( radius = 1, theta = 0, y = 0 ) {
  20180. this.radius = radius; // distance from the origin to a point in the x-z plane
  20181. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20182. this.y = y; // height above the x-z plane
  20183. return this;
  20184. }
  20185. set( radius, theta, y ) {
  20186. this.radius = radius;
  20187. this.theta = theta;
  20188. this.y = y;
  20189. return this;
  20190. }
  20191. copy( other ) {
  20192. this.radius = other.radius;
  20193. this.theta = other.theta;
  20194. this.y = other.y;
  20195. return this;
  20196. }
  20197. setFromVector3( v ) {
  20198. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20199. }
  20200. setFromCartesianCoords( x, y, z ) {
  20201. this.radius = Math.sqrt( x * x + z * z );
  20202. this.theta = Math.atan2( x, z );
  20203. this.y = y;
  20204. return this;
  20205. }
  20206. clone() {
  20207. return new this.constructor().copy( this );
  20208. }
  20209. }
  20210. const _vector$4 = /*@__PURE__*/ new Vector2();
  20211. class Box2 {
  20212. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20213. this.isBox2 = true;
  20214. this.min = min;
  20215. this.max = max;
  20216. }
  20217. set( min, max ) {
  20218. this.min.copy( min );
  20219. this.max.copy( max );
  20220. return this;
  20221. }
  20222. setFromPoints( points ) {
  20223. this.makeEmpty();
  20224. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20225. this.expandByPoint( points[ i ] );
  20226. }
  20227. return this;
  20228. }
  20229. setFromCenterAndSize( center, size ) {
  20230. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20231. this.min.copy( center ).sub( halfSize );
  20232. this.max.copy( center ).add( halfSize );
  20233. return this;
  20234. }
  20235. clone() {
  20236. return new this.constructor().copy( this );
  20237. }
  20238. copy( box ) {
  20239. this.min.copy( box.min );
  20240. this.max.copy( box.max );
  20241. return this;
  20242. }
  20243. makeEmpty() {
  20244. this.min.x = this.min.y = + Infinity;
  20245. this.max.x = this.max.y = - Infinity;
  20246. return this;
  20247. }
  20248. isEmpty() {
  20249. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20250. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20251. }
  20252. getCenter( target ) {
  20253. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20254. }
  20255. getSize( target ) {
  20256. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20257. }
  20258. expandByPoint( point ) {
  20259. this.min.min( point );
  20260. this.max.max( point );
  20261. return this;
  20262. }
  20263. expandByVector( vector ) {
  20264. this.min.sub( vector );
  20265. this.max.add( vector );
  20266. return this;
  20267. }
  20268. expandByScalar( scalar ) {
  20269. this.min.addScalar( - scalar );
  20270. this.max.addScalar( scalar );
  20271. return this;
  20272. }
  20273. containsPoint( point ) {
  20274. return point.x < this.min.x || point.x > this.max.x ||
  20275. point.y < this.min.y || point.y > this.max.y ? false : true;
  20276. }
  20277. containsBox( box ) {
  20278. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20279. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20280. }
  20281. getParameter( point, target ) {
  20282. // This can potentially have a divide by zero if the box
  20283. // has a size dimension of 0.
  20284. return target.set(
  20285. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20286. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20287. );
  20288. }
  20289. intersectsBox( box ) {
  20290. // using 4 splitting planes to rule out intersections
  20291. return box.max.x < this.min.x || box.min.x > this.max.x ||
  20292. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  20293. }
  20294. clampPoint( point, target ) {
  20295. return target.copy( point ).clamp( this.min, this.max );
  20296. }
  20297. distanceToPoint( point ) {
  20298. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20299. }
  20300. intersect( box ) {
  20301. this.min.max( box.min );
  20302. this.max.min( box.max );
  20303. if ( this.isEmpty() ) this.makeEmpty();
  20304. return this;
  20305. }
  20306. union( box ) {
  20307. this.min.min( box.min );
  20308. this.max.max( box.max );
  20309. return this;
  20310. }
  20311. translate( offset ) {
  20312. this.min.add( offset );
  20313. this.max.add( offset );
  20314. return this;
  20315. }
  20316. equals( box ) {
  20317. return box.min.equals( this.min ) && box.max.equals( this.max );
  20318. }
  20319. }
  20320. const _startP = /*@__PURE__*/ new Vector3();
  20321. const _startEnd = /*@__PURE__*/ new Vector3();
  20322. class Line3 {
  20323. constructor( start = new Vector3(), end = new Vector3() ) {
  20324. this.start = start;
  20325. this.end = end;
  20326. }
  20327. set( start, end ) {
  20328. this.start.copy( start );
  20329. this.end.copy( end );
  20330. return this;
  20331. }
  20332. copy( line ) {
  20333. this.start.copy( line.start );
  20334. this.end.copy( line.end );
  20335. return this;
  20336. }
  20337. getCenter( target ) {
  20338. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20339. }
  20340. delta( target ) {
  20341. return target.subVectors( this.end, this.start );
  20342. }
  20343. distanceSq() {
  20344. return this.start.distanceToSquared( this.end );
  20345. }
  20346. distance() {
  20347. return this.start.distanceTo( this.end );
  20348. }
  20349. at( t, target ) {
  20350. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20351. }
  20352. closestPointToPointParameter( point, clampToLine ) {
  20353. _startP.subVectors( point, this.start );
  20354. _startEnd.subVectors( this.end, this.start );
  20355. const startEnd2 = _startEnd.dot( _startEnd );
  20356. const startEnd_startP = _startEnd.dot( _startP );
  20357. let t = startEnd_startP / startEnd2;
  20358. if ( clampToLine ) {
  20359. t = clamp$1( t, 0, 1 );
  20360. }
  20361. return t;
  20362. }
  20363. closestPointToPoint( point, clampToLine, target ) {
  20364. const t = this.closestPointToPointParameter( point, clampToLine );
  20365. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20366. }
  20367. applyMatrix4( matrix ) {
  20368. this.start.applyMatrix4( matrix );
  20369. this.end.applyMatrix4( matrix );
  20370. return this;
  20371. }
  20372. equals( line ) {
  20373. return line.start.equals( this.start ) && line.end.equals( this.end );
  20374. }
  20375. clone() {
  20376. return new this.constructor().copy( this );
  20377. }
  20378. }
  20379. const _vector$3 = /*@__PURE__*/ new Vector3();
  20380. class SpotLightHelper extends Object3D {
  20381. constructor( light, color ) {
  20382. super();
  20383. this.light = light;
  20384. this.matrixAutoUpdate = false;
  20385. this.color = color;
  20386. this.type = 'SpotLightHelper';
  20387. const geometry = new BufferGeometry();
  20388. const positions = [
  20389. 0, 0, 0, 0, 0, 1,
  20390. 0, 0, 0, 1, 0, 1,
  20391. 0, 0, 0, - 1, 0, 1,
  20392. 0, 0, 0, 0, 1, 1,
  20393. 0, 0, 0, 0, - 1, 1
  20394. ];
  20395. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20396. const p1 = ( i / l ) * Math.PI * 2;
  20397. const p2 = ( j / l ) * Math.PI * 2;
  20398. positions.push(
  20399. Math.cos( p1 ), Math.sin( p1 ), 1,
  20400. Math.cos( p2 ), Math.sin( p2 ), 1
  20401. );
  20402. }
  20403. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20404. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20405. this.cone = new LineSegments( geometry, material );
  20406. this.add( this.cone );
  20407. this.update();
  20408. }
  20409. dispose() {
  20410. this.cone.geometry.dispose();
  20411. this.cone.material.dispose();
  20412. }
  20413. update() {
  20414. this.light.updateWorldMatrix( true, false );
  20415. this.light.target.updateWorldMatrix( true, false );
  20416. // update the local matrix based on the parent and light target transforms
  20417. if ( this.parent ) {
  20418. this.parent.updateWorldMatrix( true );
  20419. this.matrix
  20420. .copy( this.parent.matrixWorld )
  20421. .invert()
  20422. .multiply( this.light.matrixWorld );
  20423. } else {
  20424. this.matrix.copy( this.light.matrixWorld );
  20425. }
  20426. this.matrixWorld.copy( this.light.matrixWorld );
  20427. const coneLength = this.light.distance ? this.light.distance : 1000;
  20428. const coneWidth = coneLength * Math.tan( this.light.angle );
  20429. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20430. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20431. this.cone.lookAt( _vector$3 );
  20432. if ( this.color !== undefined ) {
  20433. this.cone.material.color.set( this.color );
  20434. } else {
  20435. this.cone.material.color.copy( this.light.color );
  20436. }
  20437. }
  20438. }
  20439. const _vector$2 = /*@__PURE__*/ new Vector3();
  20440. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20441. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20442. class SkeletonHelper extends LineSegments {
  20443. constructor( object ) {
  20444. const bones = getBoneList( object );
  20445. const geometry = new BufferGeometry();
  20446. const vertices = [];
  20447. const colors = [];
  20448. const color1 = new Color( 0, 0, 1 );
  20449. const color2 = new Color( 0, 1, 0 );
  20450. for ( let i = 0; i < bones.length; i ++ ) {
  20451. const bone = bones[ i ];
  20452. if ( bone.parent && bone.parent.isBone ) {
  20453. vertices.push( 0, 0, 0 );
  20454. vertices.push( 0, 0, 0 );
  20455. colors.push( color1.r, color1.g, color1.b );
  20456. colors.push( color2.r, color2.g, color2.b );
  20457. }
  20458. }
  20459. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20460. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20461. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20462. super( geometry, material );
  20463. this.isSkeletonHelper = true;
  20464. this.type = 'SkeletonHelper';
  20465. this.root = object;
  20466. this.bones = bones;
  20467. this.matrix = object.matrixWorld;
  20468. this.matrixAutoUpdate = false;
  20469. }
  20470. updateMatrixWorld( force ) {
  20471. const bones = this.bones;
  20472. const geometry = this.geometry;
  20473. const position = geometry.getAttribute( 'position' );
  20474. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20475. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20476. const bone = bones[ i ];
  20477. if ( bone.parent && bone.parent.isBone ) {
  20478. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20479. _vector$2.setFromMatrixPosition( _boneMatrix );
  20480. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20481. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20482. _vector$2.setFromMatrixPosition( _boneMatrix );
  20483. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20484. j += 2;
  20485. }
  20486. }
  20487. geometry.getAttribute( 'position' ).needsUpdate = true;
  20488. super.updateMatrixWorld( force );
  20489. }
  20490. dispose() {
  20491. this.geometry.dispose();
  20492. this.material.dispose();
  20493. }
  20494. }
  20495. function getBoneList( object ) {
  20496. const boneList = [];
  20497. if ( object.isBone === true ) {
  20498. boneList.push( object );
  20499. }
  20500. for ( let i = 0; i < object.children.length; i ++ ) {
  20501. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20502. }
  20503. return boneList;
  20504. }
  20505. class PointLightHelper extends Mesh {
  20506. constructor( light, sphereSize, color ) {
  20507. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20508. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20509. super( geometry, material );
  20510. this.light = light;
  20511. this.color = color;
  20512. this.type = 'PointLightHelper';
  20513. this.matrix = this.light.matrixWorld;
  20514. this.matrixAutoUpdate = false;
  20515. this.update();
  20516. /*
  20517. // TODO: delete this comment?
  20518. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20519. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20520. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20521. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20522. const d = light.distance;
  20523. if ( d === 0.0 ) {
  20524. this.lightDistance.visible = false;
  20525. } else {
  20526. this.lightDistance.scale.set( d, d, d );
  20527. }
  20528. this.add( this.lightDistance );
  20529. */
  20530. }
  20531. dispose() {
  20532. this.geometry.dispose();
  20533. this.material.dispose();
  20534. }
  20535. update() {
  20536. this.light.updateWorldMatrix( true, false );
  20537. if ( this.color !== undefined ) {
  20538. this.material.color.set( this.color );
  20539. } else {
  20540. this.material.color.copy( this.light.color );
  20541. }
  20542. /*
  20543. const d = this.light.distance;
  20544. if ( d === 0.0 ) {
  20545. this.lightDistance.visible = false;
  20546. } else {
  20547. this.lightDistance.visible = true;
  20548. this.lightDistance.scale.set( d, d, d );
  20549. }
  20550. */
  20551. }
  20552. }
  20553. const _vector$1 = /*@__PURE__*/ new Vector3();
  20554. const _color1 = /*@__PURE__*/ new Color();
  20555. const _color2 = /*@__PURE__*/ new Color();
  20556. class HemisphereLightHelper extends Object3D {
  20557. constructor( light, size, color ) {
  20558. super();
  20559. this.light = light;
  20560. this.matrix = light.matrixWorld;
  20561. this.matrixAutoUpdate = false;
  20562. this.color = color;
  20563. this.type = 'HemisphereLightHelper';
  20564. const geometry = new OctahedronGeometry( size );
  20565. geometry.rotateY( Math.PI * 0.5 );
  20566. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20567. if ( this.color === undefined ) this.material.vertexColors = true;
  20568. const position = geometry.getAttribute( 'position' );
  20569. const colors = new Float32Array( position.count * 3 );
  20570. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20571. this.add( new Mesh( geometry, this.material ) );
  20572. this.update();
  20573. }
  20574. dispose() {
  20575. this.children[ 0 ].geometry.dispose();
  20576. this.children[ 0 ].material.dispose();
  20577. }
  20578. update() {
  20579. const mesh = this.children[ 0 ];
  20580. if ( this.color !== undefined ) {
  20581. this.material.color.set( this.color );
  20582. } else {
  20583. const colors = mesh.geometry.getAttribute( 'color' );
  20584. _color1.copy( this.light.color );
  20585. _color2.copy( this.light.groundColor );
  20586. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20587. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20588. colors.setXYZ( i, color.r, color.g, color.b );
  20589. }
  20590. colors.needsUpdate = true;
  20591. }
  20592. this.light.updateWorldMatrix( true, false );
  20593. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20594. }
  20595. }
  20596. class GridHelper extends LineSegments {
  20597. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20598. color1 = new Color( color1 );
  20599. color2 = new Color( color2 );
  20600. const center = divisions / 2;
  20601. const step = size / divisions;
  20602. const halfSize = size / 2;
  20603. const vertices = [], colors = [];
  20604. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20605. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20606. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20607. const color = i === center ? color1 : color2;
  20608. color.toArray( colors, j ); j += 3;
  20609. color.toArray( colors, j ); j += 3;
  20610. color.toArray( colors, j ); j += 3;
  20611. color.toArray( colors, j ); j += 3;
  20612. }
  20613. const geometry = new BufferGeometry();
  20614. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20615. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20616. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20617. super( geometry, material );
  20618. this.type = 'GridHelper';
  20619. }
  20620. dispose() {
  20621. this.geometry.dispose();
  20622. this.material.dispose();
  20623. }
  20624. }
  20625. class PolarGridHelper extends LineSegments {
  20626. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20627. color1 = new Color( color1 );
  20628. color2 = new Color( color2 );
  20629. const vertices = [];
  20630. const colors = [];
  20631. // create the sectors
  20632. if ( sectors > 1 ) {
  20633. for ( let i = 0; i < sectors; i ++ ) {
  20634. const v = ( i / sectors ) * ( Math.PI * 2 );
  20635. const x = Math.sin( v ) * radius;
  20636. const z = Math.cos( v ) * radius;
  20637. vertices.push( 0, 0, 0 );
  20638. vertices.push( x, 0, z );
  20639. const color = ( i & 1 ) ? color1 : color2;
  20640. colors.push( color.r, color.g, color.b );
  20641. colors.push( color.r, color.g, color.b );
  20642. }
  20643. }
  20644. // create the rings
  20645. for ( let i = 0; i < rings; i ++ ) {
  20646. const color = ( i & 1 ) ? color1 : color2;
  20647. const r = radius - ( radius / rings * i );
  20648. for ( let j = 0; j < divisions; j ++ ) {
  20649. // first vertex
  20650. let v = ( j / divisions ) * ( Math.PI * 2 );
  20651. let x = Math.sin( v ) * r;
  20652. let z = Math.cos( v ) * r;
  20653. vertices.push( x, 0, z );
  20654. colors.push( color.r, color.g, color.b );
  20655. // second vertex
  20656. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20657. x = Math.sin( v ) * r;
  20658. z = Math.cos( v ) * r;
  20659. vertices.push( x, 0, z );
  20660. colors.push( color.r, color.g, color.b );
  20661. }
  20662. }
  20663. const geometry = new BufferGeometry();
  20664. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20665. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20666. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20667. super( geometry, material );
  20668. this.type = 'PolarGridHelper';
  20669. }
  20670. dispose() {
  20671. this.geometry.dispose();
  20672. this.material.dispose();
  20673. }
  20674. }
  20675. const _v1 = /*@__PURE__*/ new Vector3();
  20676. const _v2 = /*@__PURE__*/ new Vector3();
  20677. const _v3 = /*@__PURE__*/ new Vector3();
  20678. class DirectionalLightHelper extends Object3D {
  20679. constructor( light, size, color ) {
  20680. super();
  20681. this.light = light;
  20682. this.matrix = light.matrixWorld;
  20683. this.matrixAutoUpdate = false;
  20684. this.color = color;
  20685. this.type = 'DirectionalLightHelper';
  20686. if ( size === undefined ) size = 1;
  20687. let geometry = new BufferGeometry();
  20688. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20689. - size, size, 0,
  20690. size, size, 0,
  20691. size, - size, 0,
  20692. - size, - size, 0,
  20693. - size, size, 0
  20694. ], 3 ) );
  20695. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20696. this.lightPlane = new Line( geometry, material );
  20697. this.add( this.lightPlane );
  20698. geometry = new BufferGeometry();
  20699. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20700. this.targetLine = new Line( geometry, material );
  20701. this.add( this.targetLine );
  20702. this.update();
  20703. }
  20704. dispose() {
  20705. this.lightPlane.geometry.dispose();
  20706. this.lightPlane.material.dispose();
  20707. this.targetLine.geometry.dispose();
  20708. this.targetLine.material.dispose();
  20709. }
  20710. update() {
  20711. this.light.updateWorldMatrix( true, false );
  20712. this.light.target.updateWorldMatrix( true, false );
  20713. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20714. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20715. _v3.subVectors( _v2, _v1 );
  20716. this.lightPlane.lookAt( _v2 );
  20717. if ( this.color !== undefined ) {
  20718. this.lightPlane.material.color.set( this.color );
  20719. this.targetLine.material.color.set( this.color );
  20720. } else {
  20721. this.lightPlane.material.color.copy( this.light.color );
  20722. this.targetLine.material.color.copy( this.light.color );
  20723. }
  20724. this.targetLine.lookAt( _v2 );
  20725. this.targetLine.scale.z = _v3.length();
  20726. }
  20727. }
  20728. const _vector = /*@__PURE__*/ new Vector3();
  20729. const _camera$1 = /*@__PURE__*/ new Camera();
  20730. /**
  20731. * - shows frustum, line of sight and up of the camera
  20732. * - suitable for fast updates
  20733. * - based on frustum visualization in lightgl.js shadowmap example
  20734. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20735. */
  20736. class CameraHelper extends LineSegments {
  20737. constructor( camera ) {
  20738. const geometry = new BufferGeometry();
  20739. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20740. const vertices = [];
  20741. const colors = [];
  20742. const pointMap = {};
  20743. // near
  20744. addLine( 'n1', 'n2' );
  20745. addLine( 'n2', 'n4' );
  20746. addLine( 'n4', 'n3' );
  20747. addLine( 'n3', 'n1' );
  20748. // far
  20749. addLine( 'f1', 'f2' );
  20750. addLine( 'f2', 'f4' );
  20751. addLine( 'f4', 'f3' );
  20752. addLine( 'f3', 'f1' );
  20753. // sides
  20754. addLine( 'n1', 'f1' );
  20755. addLine( 'n2', 'f2' );
  20756. addLine( 'n3', 'f3' );
  20757. addLine( 'n4', 'f4' );
  20758. // cone
  20759. addLine( 'p', 'n1' );
  20760. addLine( 'p', 'n2' );
  20761. addLine( 'p', 'n3' );
  20762. addLine( 'p', 'n4' );
  20763. // up
  20764. addLine( 'u1', 'u2' );
  20765. addLine( 'u2', 'u3' );
  20766. addLine( 'u3', 'u1' );
  20767. // target
  20768. addLine( 'c', 't' );
  20769. addLine( 'p', 'c' );
  20770. // cross
  20771. addLine( 'cn1', 'cn2' );
  20772. addLine( 'cn3', 'cn4' );
  20773. addLine( 'cf1', 'cf2' );
  20774. addLine( 'cf3', 'cf4' );
  20775. function addLine( a, b ) {
  20776. addPoint( a );
  20777. addPoint( b );
  20778. }
  20779. function addPoint( id ) {
  20780. vertices.push( 0, 0, 0 );
  20781. colors.push( 0, 0, 0 );
  20782. if ( pointMap[ id ] === undefined ) {
  20783. pointMap[ id ] = [];
  20784. }
  20785. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  20786. }
  20787. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20788. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20789. super( geometry, material );
  20790. this.type = 'CameraHelper';
  20791. this.camera = camera;
  20792. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  20793. this.matrix = camera.matrixWorld;
  20794. this.matrixAutoUpdate = false;
  20795. this.pointMap = pointMap;
  20796. this.update();
  20797. // colors
  20798. const colorFrustum = new Color( 0xffaa00 );
  20799. const colorCone = new Color( 0xff0000 );
  20800. const colorUp = new Color( 0x00aaff );
  20801. const colorTarget = new Color( 0xffffff );
  20802. const colorCross = new Color( 0x333333 );
  20803. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  20804. }
  20805. setColors( frustum, cone, up, target, cross ) {
  20806. const geometry = this.geometry;
  20807. const colorAttribute = geometry.getAttribute( 'color' );
  20808. // near
  20809. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  20810. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  20811. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  20812. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  20813. // far
  20814. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  20815. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  20816. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  20817. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  20818. // sides
  20819. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  20820. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  20821. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  20822. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  20823. // cone
  20824. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  20825. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  20826. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  20827. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  20828. // up
  20829. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  20830. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  20831. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  20832. // target
  20833. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  20834. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  20835. // cross
  20836. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  20837. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  20838. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  20839. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  20840. colorAttribute.needsUpdate = true;
  20841. }
  20842. update() {
  20843. const geometry = this.geometry;
  20844. const pointMap = this.pointMap;
  20845. const w = 1, h = 1;
  20846. // we need just camera projection matrix inverse
  20847. // world matrix must be identity
  20848. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  20849. // center / target
  20850. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  20851. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  20852. // near
  20853. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  20854. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  20855. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  20856. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  20857. // far
  20858. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  20859. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  20860. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  20861. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  20862. // up
  20863. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  20864. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  20865. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  20866. // cross
  20867. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  20868. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  20869. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  20870. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  20871. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  20872. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  20873. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  20874. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  20875. geometry.getAttribute( 'position' ).needsUpdate = true;
  20876. }
  20877. dispose() {
  20878. this.geometry.dispose();
  20879. this.material.dispose();
  20880. }
  20881. }
  20882. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  20883. _vector.set( x, y, z ).unproject( camera );
  20884. const points = pointMap[ point ];
  20885. if ( points !== undefined ) {
  20886. const position = geometry.getAttribute( 'position' );
  20887. for ( let i = 0, l = points.length; i < l; i ++ ) {
  20888. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  20889. }
  20890. }
  20891. }
  20892. const _box = /*@__PURE__*/ new Box3();
  20893. class BoxHelper extends LineSegments {
  20894. constructor( object, color = 0xffff00 ) {
  20895. 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 ] );
  20896. const positions = new Float32Array( 8 * 3 );
  20897. const geometry = new BufferGeometry();
  20898. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20899. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  20900. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20901. this.object = object;
  20902. this.type = 'BoxHelper';
  20903. this.matrixAutoUpdate = false;
  20904. this.update();
  20905. }
  20906. update( object ) {
  20907. if ( object !== undefined ) {
  20908. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  20909. }
  20910. if ( this.object !== undefined ) {
  20911. _box.setFromObject( this.object );
  20912. }
  20913. if ( _box.isEmpty() ) return;
  20914. const min = _box.min;
  20915. const max = _box.max;
  20916. /*
  20917. 5____4
  20918. 1/___0/|
  20919. | 6__|_7
  20920. 2/___3/
  20921. 0: max.x, max.y, max.z
  20922. 1: min.x, max.y, max.z
  20923. 2: min.x, min.y, max.z
  20924. 3: max.x, min.y, max.z
  20925. 4: max.x, max.y, min.z
  20926. 5: min.x, max.y, min.z
  20927. 6: min.x, min.y, min.z
  20928. 7: max.x, min.y, min.z
  20929. */
  20930. const position = this.geometry.attributes.position;
  20931. const array = position.array;
  20932. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  20933. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  20934. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  20935. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  20936. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  20937. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  20938. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  20939. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  20940. position.needsUpdate = true;
  20941. this.geometry.computeBoundingSphere();
  20942. }
  20943. setFromObject( object ) {
  20944. this.object = object;
  20945. this.update();
  20946. return this;
  20947. }
  20948. copy( source, recursive ) {
  20949. super.copy( source, recursive );
  20950. this.object = source.object;
  20951. return this;
  20952. }
  20953. dispose() {
  20954. this.geometry.dispose();
  20955. this.material.dispose();
  20956. }
  20957. }
  20958. class Box3Helper extends LineSegments {
  20959. constructor( box, color = 0xffff00 ) {
  20960. 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 ] );
  20961. 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 ];
  20962. const geometry = new BufferGeometry();
  20963. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20964. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20965. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20966. this.box = box;
  20967. this.type = 'Box3Helper';
  20968. this.geometry.computeBoundingSphere();
  20969. }
  20970. updateMatrixWorld( force ) {
  20971. const box = this.box;
  20972. if ( box.isEmpty() ) return;
  20973. box.getCenter( this.position );
  20974. box.getSize( this.scale );
  20975. this.scale.multiplyScalar( 0.5 );
  20976. super.updateMatrixWorld( force );
  20977. }
  20978. dispose() {
  20979. this.geometry.dispose();
  20980. this.material.dispose();
  20981. }
  20982. }
  20983. class PlaneHelper extends Line {
  20984. constructor( plane, size = 1, hex = 0xffff00 ) {
  20985. const color = hex;
  20986. 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 ];
  20987. const geometry = new BufferGeometry();
  20988. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20989. geometry.computeBoundingSphere();
  20990. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20991. this.type = 'PlaneHelper';
  20992. this.plane = plane;
  20993. this.size = size;
  20994. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  20995. const geometry2 = new BufferGeometry();
  20996. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  20997. geometry2.computeBoundingSphere();
  20998. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  20999. }
  21000. updateMatrixWorld( force ) {
  21001. this.position.set( 0, 0, 0 );
  21002. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21003. this.lookAt( this.plane.normal );
  21004. this.translateZ( - this.plane.constant );
  21005. super.updateMatrixWorld( force );
  21006. }
  21007. dispose() {
  21008. this.geometry.dispose();
  21009. this.material.dispose();
  21010. this.children[ 0 ].geometry.dispose();
  21011. this.children[ 0 ].material.dispose();
  21012. }
  21013. }
  21014. const _axis = /*@__PURE__*/ new Vector3();
  21015. let _lineGeometry, _coneGeometry;
  21016. class ArrowHelper extends Object3D {
  21017. // dir is assumed to be normalized
  21018. 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 ) {
  21019. super();
  21020. this.type = 'ArrowHelper';
  21021. if ( _lineGeometry === undefined ) {
  21022. _lineGeometry = new BufferGeometry();
  21023. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21024. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21025. _coneGeometry.translate( 0, - 0.5, 0 );
  21026. }
  21027. this.position.copy( origin );
  21028. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21029. this.line.matrixAutoUpdate = false;
  21030. this.add( this.line );
  21031. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21032. this.cone.matrixAutoUpdate = false;
  21033. this.add( this.cone );
  21034. this.setDirection( dir );
  21035. this.setLength( length, headLength, headWidth );
  21036. }
  21037. setDirection( dir ) {
  21038. // dir is assumed to be normalized
  21039. if ( dir.y > 0.99999 ) {
  21040. this.quaternion.set( 0, 0, 0, 1 );
  21041. } else if ( dir.y < - 0.99999 ) {
  21042. this.quaternion.set( 1, 0, 0, 0 );
  21043. } else {
  21044. _axis.set( dir.z, 0, - dir.x ).normalize();
  21045. const radians = Math.acos( dir.y );
  21046. this.quaternion.setFromAxisAngle( _axis, radians );
  21047. }
  21048. }
  21049. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21050. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21051. this.line.updateMatrix();
  21052. this.cone.scale.set( headWidth, headLength, headWidth );
  21053. this.cone.position.y = length;
  21054. this.cone.updateMatrix();
  21055. }
  21056. setColor( color ) {
  21057. this.line.material.color.set( color );
  21058. this.cone.material.color.set( color );
  21059. }
  21060. copy( source ) {
  21061. super.copy( source, false );
  21062. this.line.copy( source.line );
  21063. this.cone.copy( source.cone );
  21064. return this;
  21065. }
  21066. dispose() {
  21067. this.line.geometry.dispose();
  21068. this.line.material.dispose();
  21069. this.cone.geometry.dispose();
  21070. this.cone.material.dispose();
  21071. }
  21072. }
  21073. class AxesHelper extends LineSegments {
  21074. constructor( size = 1 ) {
  21075. const vertices = [
  21076. 0, 0, 0, size, 0, 0,
  21077. 0, 0, 0, 0, size, 0,
  21078. 0, 0, 0, 0, 0, size
  21079. ];
  21080. const colors = [
  21081. 1, 0, 0, 1, 0.6, 0,
  21082. 0, 1, 0, 0.6, 1, 0,
  21083. 0, 0, 1, 0, 0.6, 1
  21084. ];
  21085. const geometry = new BufferGeometry();
  21086. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21087. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21088. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21089. super( geometry, material );
  21090. this.type = 'AxesHelper';
  21091. }
  21092. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21093. const color = new Color();
  21094. const array = this.geometry.attributes.color.array;
  21095. color.set( xAxisColor );
  21096. color.toArray( array, 0 );
  21097. color.toArray( array, 3 );
  21098. color.set( yAxisColor );
  21099. color.toArray( array, 6 );
  21100. color.toArray( array, 9 );
  21101. color.set( zAxisColor );
  21102. color.toArray( array, 12 );
  21103. color.toArray( array, 15 );
  21104. this.geometry.attributes.color.needsUpdate = true;
  21105. return this;
  21106. }
  21107. dispose() {
  21108. this.geometry.dispose();
  21109. this.material.dispose();
  21110. }
  21111. }
  21112. class ShapePath {
  21113. constructor() {
  21114. this.type = 'ShapePath';
  21115. this.color = new Color();
  21116. this.subPaths = [];
  21117. this.currentPath = null;
  21118. }
  21119. moveTo( x, y ) {
  21120. this.currentPath = new Path();
  21121. this.subPaths.push( this.currentPath );
  21122. this.currentPath.moveTo( x, y );
  21123. return this;
  21124. }
  21125. lineTo( x, y ) {
  21126. this.currentPath.lineTo( x, y );
  21127. return this;
  21128. }
  21129. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21130. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21131. return this;
  21132. }
  21133. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21134. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21135. return this;
  21136. }
  21137. splineThru( pts ) {
  21138. this.currentPath.splineThru( pts );
  21139. return this;
  21140. }
  21141. toShapes( isCCW ) {
  21142. function toShapesNoHoles( inSubpaths ) {
  21143. const shapes = [];
  21144. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21145. const tmpPath = inSubpaths[ i ];
  21146. const tmpShape = new Shape();
  21147. tmpShape.curves = tmpPath.curves;
  21148. shapes.push( tmpShape );
  21149. }
  21150. return shapes;
  21151. }
  21152. function isPointInsidePolygon( inPt, inPolygon ) {
  21153. const polyLen = inPolygon.length;
  21154. // inPt on polygon contour => immediate success or
  21155. // toggling of inside/outside at every single! intersection point of an edge
  21156. // with the horizontal line through inPt, left of inPt
  21157. // not counting lowerY endpoints of edges and whole edges on that line
  21158. let inside = false;
  21159. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21160. let edgeLowPt = inPolygon[ p ];
  21161. let edgeHighPt = inPolygon[ q ];
  21162. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21163. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21164. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21165. // not parallel
  21166. if ( edgeDy < 0 ) {
  21167. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21168. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21169. }
  21170. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21171. if ( inPt.y === edgeLowPt.y ) {
  21172. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21173. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21174. } else {
  21175. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21176. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21177. if ( perpEdge < 0 ) continue;
  21178. inside = ! inside; // true intersection left of inPt
  21179. }
  21180. } else {
  21181. // parallel or collinear
  21182. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21183. // edge lies on the same horizontal line as inPt
  21184. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21185. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21186. // continue;
  21187. }
  21188. }
  21189. return inside;
  21190. }
  21191. const isClockWise = ShapeUtils.isClockWise;
  21192. const subPaths = this.subPaths;
  21193. if ( subPaths.length === 0 ) return [];
  21194. let solid, tmpPath, tmpShape;
  21195. const shapes = [];
  21196. if ( subPaths.length === 1 ) {
  21197. tmpPath = subPaths[ 0 ];
  21198. tmpShape = new Shape();
  21199. tmpShape.curves = tmpPath.curves;
  21200. shapes.push( tmpShape );
  21201. return shapes;
  21202. }
  21203. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21204. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21205. // console.log("Holes first", holesFirst);
  21206. const betterShapeHoles = [];
  21207. const newShapes = [];
  21208. let newShapeHoles = [];
  21209. let mainIdx = 0;
  21210. let tmpPoints;
  21211. newShapes[ mainIdx ] = undefined;
  21212. newShapeHoles[ mainIdx ] = [];
  21213. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21214. tmpPath = subPaths[ i ];
  21215. tmpPoints = tmpPath.getPoints();
  21216. solid = isClockWise( tmpPoints );
  21217. solid = isCCW ? ! solid : solid;
  21218. if ( solid ) {
  21219. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21220. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21221. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21222. if ( holesFirst ) mainIdx ++;
  21223. newShapeHoles[ mainIdx ] = [];
  21224. //console.log('cw', i);
  21225. } else {
  21226. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21227. //console.log('ccw', i);
  21228. }
  21229. }
  21230. // only Holes? -> probably all Shapes with wrong orientation
  21231. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21232. if ( newShapes.length > 1 ) {
  21233. let ambiguous = false;
  21234. let toChange = 0;
  21235. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21236. betterShapeHoles[ sIdx ] = [];
  21237. }
  21238. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21239. const sho = newShapeHoles[ sIdx ];
  21240. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21241. const ho = sho[ hIdx ];
  21242. let hole_unassigned = true;
  21243. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21244. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21245. if ( sIdx !== s2Idx ) toChange ++;
  21246. if ( hole_unassigned ) {
  21247. hole_unassigned = false;
  21248. betterShapeHoles[ s2Idx ].push( ho );
  21249. } else {
  21250. ambiguous = true;
  21251. }
  21252. }
  21253. }
  21254. if ( hole_unassigned ) {
  21255. betterShapeHoles[ sIdx ].push( ho );
  21256. }
  21257. }
  21258. }
  21259. if ( toChange > 0 && ambiguous === false ) {
  21260. newShapeHoles = betterShapeHoles;
  21261. }
  21262. }
  21263. let tmpHoles;
  21264. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21265. tmpShape = newShapes[ i ].s;
  21266. shapes.push( tmpShape );
  21267. tmpHoles = newShapeHoles[ i ];
  21268. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21269. tmpShape.holes.push( tmpHoles[ j ].h );
  21270. }
  21271. }
  21272. //console.log("shape", shapes);
  21273. return shapes;
  21274. }
  21275. }
  21276. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21277. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21278. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21279. super( width, height, { ...options, count } );
  21280. this.isWebGLMultipleRenderTargets = true;
  21281. }
  21282. get texture() {
  21283. return this.textures;
  21284. }
  21285. }
  21286. if ( self.GPUShaderStage === undefined ) {
  21287. self.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  21288. }
  21289. // statics
  21290. let isAvailable = navigator.gpu !== undefined;
  21291. if ( typeof window !== 'undefined' && isAvailable ) {
  21292. isAvailable = await navigator.gpu.requestAdapter();
  21293. }
  21294. class WebGPU {
  21295. static isAvailable() {
  21296. return Boolean( isAvailable );
  21297. }
  21298. static getStaticAdapter() {
  21299. return isAvailable;
  21300. }
  21301. static getErrorMessage() {
  21302. const message = 'Your browser does not support <a href="https://gpuweb.github.io/gpuweb/" style="color:blue">WebGPU</a> yet';
  21303. const element = document.createElement( 'div' );
  21304. element.id = 'webgpumessage';
  21305. element.style.fontFamily = 'monospace';
  21306. element.style.fontSize = '13px';
  21307. element.style.fontWeight = 'normal';
  21308. element.style.textAlign = 'center';
  21309. element.style.background = '#fff';
  21310. element.style.color = '#000';
  21311. element.style.padding = '1.5em';
  21312. element.style.maxWidth = '400px';
  21313. element.style.margin = '5em auto 0';
  21314. element.innerHTML = message;
  21315. return element;
  21316. }
  21317. }
  21318. class Animation {
  21319. constructor( nodes, info ) {
  21320. this.nodes = nodes;
  21321. this.info = info;
  21322. this.animationLoop = null;
  21323. this.requestId = null;
  21324. this._init();
  21325. }
  21326. _init() {
  21327. const update = ( time, frame ) => {
  21328. this.requestId = self.requestAnimationFrame( update );
  21329. if ( this.info.autoReset === true ) this.info.reset();
  21330. this.nodes.nodeFrame.update();
  21331. this.info.frame = this.nodes.nodeFrame.frameId;
  21332. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  21333. };
  21334. update();
  21335. }
  21336. dispose() {
  21337. self.cancelAnimationFrame( this.requestId );
  21338. this.requestId = null;
  21339. }
  21340. setAnimationLoop( callback ) {
  21341. this.animationLoop = callback;
  21342. }
  21343. }
  21344. class ChainMap {
  21345. constructor() {
  21346. this.weakMap = new WeakMap();
  21347. }
  21348. get( keys ) {
  21349. let map = this.weakMap;
  21350. for ( let i = 0; i < keys.length; i ++ ) {
  21351. map = map.get( keys[ i ] );
  21352. if ( map === undefined ) return undefined;
  21353. }
  21354. return map.get( keys[ keys.length - 1 ] );
  21355. }
  21356. set( keys, value ) {
  21357. let map = this.weakMap;
  21358. for ( let i = 0; i < keys.length; i ++ ) {
  21359. const key = keys[ i ];
  21360. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  21361. map = map.get( key );
  21362. }
  21363. return map.set( keys[ keys.length - 1 ], value );
  21364. }
  21365. delete( keys ) {
  21366. let map = this.weakMap;
  21367. for ( let i = 0; i < keys.length; i ++ ) {
  21368. map = map.get( keys[ i ] );
  21369. if ( map === undefined ) return false;
  21370. }
  21371. return map.delete( keys[ keys.length - 1 ] );
  21372. }
  21373. }
  21374. const _plane = new Plane();
  21375. let _clippingContextVersion = 0;
  21376. class ClippingContext {
  21377. constructor() {
  21378. this.version = ++ _clippingContextVersion;
  21379. this.globalClippingCount = 0;
  21380. this.localClippingCount = 0;
  21381. this.localClippingEnabled = false;
  21382. this.localClipIntersection = false;
  21383. this.planes = [];
  21384. this.parentVersion = 0;
  21385. this.viewNormalMatrix = new Matrix3();
  21386. }
  21387. projectPlanes( source, offset ) {
  21388. const l = source.length;
  21389. const planes = this.planes;
  21390. for ( let i = 0; i < l; i ++ ) {
  21391. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  21392. const v = planes[ offset + i ];
  21393. const normal = _plane.normal;
  21394. v.x = - normal.x;
  21395. v.y = - normal.y;
  21396. v.z = - normal.z;
  21397. v.w = _plane.constant;
  21398. }
  21399. }
  21400. updateGlobal( renderer, camera ) {
  21401. const rendererClippingPlanes = renderer.clippingPlanes;
  21402. this.viewMatrix = camera.matrixWorldInverse;
  21403. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  21404. let update = false;
  21405. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  21406. const l = rendererClippingPlanes.length;
  21407. if ( l !== this.globalClippingCount ) {
  21408. const planes = [];
  21409. for ( let i = 0; i < l; i ++ ) {
  21410. planes.push( new Vector4() );
  21411. }
  21412. this.globalClippingCount = l;
  21413. this.planes = planes;
  21414. update = true;
  21415. }
  21416. this.projectPlanes( rendererClippingPlanes, 0 );
  21417. } else if ( this.globalClippingCount !== 0 ) {
  21418. this.globalClippingCount = 0;
  21419. this.planes = [];
  21420. update = true;
  21421. }
  21422. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  21423. this.localClippingEnabled = renderer.localClippingEnabled;
  21424. update = true;
  21425. }
  21426. if ( update ) this.version = _clippingContextVersion ++;
  21427. }
  21428. update( parent, material ) {
  21429. let update = false;
  21430. if ( this !== parent && parent.version !== this.parentVersion ) {
  21431. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  21432. this.localClippingEnabled = parent.localClippingEnabled;
  21433. this.planes = Array.from( parent.planes );
  21434. this.parentVersion = parent.version;
  21435. this.viewMatrix = parent.viewMatrix;
  21436. this.viewNormalMatrix = parent.viewNormalMatrix;
  21437. update = true;
  21438. }
  21439. if ( this.localClippingEnabled ) {
  21440. const localClippingPlanes = material.clippingPlanes;
  21441. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  21442. const l = localClippingPlanes.length;
  21443. const planes = this.planes;
  21444. const offset = this.globalClippingCount;
  21445. if ( update || l !== this.localClippingCount ) {
  21446. planes.length = offset + l;
  21447. for ( let i = 0; i < l; i ++ ) {
  21448. planes[ offset + i ] = new Vector4();
  21449. }
  21450. this.localClippingCount = l;
  21451. update = true;
  21452. }
  21453. this.projectPlanes( localClippingPlanes, offset );
  21454. } else if ( this.localClippingCount !== 0 ) {
  21455. this.localClippingCount = 0;
  21456. update = true;
  21457. }
  21458. if ( this.localClipIntersection !== material.clipIntersection ) {
  21459. this.localClipIntersection = material.clipIntersection;
  21460. update = true;
  21461. }
  21462. }
  21463. if ( update ) this.version = _clippingContextVersion ++;
  21464. }
  21465. }
  21466. let id$4 = 0;
  21467. function getKeys( obj ) {
  21468. const keys = Object.keys( obj );
  21469. let proto = Object.getPrototypeOf( obj );
  21470. while ( proto ) {
  21471. const descriptors = Object.getOwnPropertyDescriptors( proto );
  21472. for ( const key in descriptors ) {
  21473. if ( descriptors[ key ] !== undefined ) {
  21474. const descriptor = descriptors[ key ];
  21475. if ( descriptor && typeof descriptor.get === 'function' ) {
  21476. keys.push( key );
  21477. }
  21478. }
  21479. }
  21480. proto = Object.getPrototypeOf( proto );
  21481. }
  21482. return keys;
  21483. }
  21484. class RenderObject {
  21485. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  21486. this._nodes = nodes;
  21487. this._geometries = geometries;
  21488. this.id = id$4 ++;
  21489. this.renderer = renderer;
  21490. this.object = object;
  21491. this.material = material;
  21492. this.scene = scene;
  21493. this.camera = camera;
  21494. this.lightsNode = lightsNode;
  21495. this.context = renderContext;
  21496. this.geometry = object.geometry;
  21497. this.version = material.version;
  21498. this.drawRange = null;
  21499. this.attributes = null;
  21500. this.pipeline = null;
  21501. this.vertexBuffers = null;
  21502. this.updateClipping( renderContext.clippingContext );
  21503. this.clippingContextVersion = this.clippingContext.version;
  21504. this.initialNodesCacheKey = this.getNodesCacheKey();
  21505. this.initialCacheKey = this.getCacheKey();
  21506. this._nodeBuilderState = null;
  21507. this._bindings = null;
  21508. this.onDispose = null;
  21509. this.isRenderObject = true;
  21510. this.onMaterialDispose = () => {
  21511. this.dispose();
  21512. };
  21513. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  21514. }
  21515. updateClipping( parent ) {
  21516. const material = this.material;
  21517. let clippingContext = this.clippingContext;
  21518. if ( Array.isArray( material.clippingPlanes ) ) {
  21519. if ( clippingContext === parent || ! clippingContext ) {
  21520. clippingContext = new ClippingContext();
  21521. this.clippingContext = clippingContext;
  21522. }
  21523. clippingContext.update( parent, material );
  21524. } else if ( this.clippingContext !== parent ) {
  21525. this.clippingContext = parent;
  21526. }
  21527. }
  21528. get clippingNeedsUpdate() {
  21529. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  21530. this.clippingContextVersion = this.clippingContext.version;
  21531. return true;
  21532. }
  21533. getNodeBuilderState() {
  21534. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21535. }
  21536. getBindings() {
  21537. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21538. }
  21539. getIndex() {
  21540. return this._geometries.getIndex( this );
  21541. }
  21542. getChainArray() {
  21543. return [ this.object, this.material, this.context, this.lightsNode ];
  21544. }
  21545. getAttributes() {
  21546. if ( this.attributes !== null ) return this.attributes;
  21547. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21548. const geometry = this.geometry;
  21549. const attributes = [];
  21550. const vertexBuffers = new Set();
  21551. for ( const nodeAttribute of nodeAttributes ) {
  21552. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  21553. if ( attribute === undefined ) continue;
  21554. attributes.push( attribute );
  21555. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21556. vertexBuffers.add( bufferAttribute );
  21557. }
  21558. this.attributes = attributes;
  21559. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21560. return attributes;
  21561. }
  21562. getVertexBuffers() {
  21563. if ( this.vertexBuffers === null ) this.getAttributes();
  21564. return this.vertexBuffers;
  21565. }
  21566. getMaterialCacheKey() {
  21567. const { object, material } = this;
  21568. let cacheKey = material.customProgramCacheKey();
  21569. for ( const property of getKeys( material ) ) {
  21570. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21571. let value = material[ property ];
  21572. if ( value !== null ) {
  21573. const type = typeof value;
  21574. if ( type === 'number' ) value = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21575. else if ( type === 'object' ) value = '{}';
  21576. }
  21577. cacheKey += /*property + ':' +*/ value + ',';
  21578. }
  21579. cacheKey += this.clippingContextVersion + ',';
  21580. if ( object.skeleton ) {
  21581. cacheKey += object.skeleton.bones.length + ',';
  21582. }
  21583. if ( object.morphTargetInfluences ) {
  21584. cacheKey += object.morphTargetInfluences.length + ',';
  21585. }
  21586. if ( object.isBatchedMesh ) {
  21587. cacheKey += object._matricesTexture.uuid + ',';
  21588. if ( object._colorsTexture !== null ) {
  21589. cacheKey += object._colorsTexture.uuid + ',';
  21590. }
  21591. }
  21592. if ( object.count > 1 ) {
  21593. cacheKey += object.count + ',';
  21594. }
  21595. return cacheKey;
  21596. }
  21597. get needsUpdate() {
  21598. return this.initialNodesCacheKey !== this.getNodesCacheKey() || this.clippingNeedsUpdate;
  21599. }
  21600. getNodesCacheKey() {
  21601. // Environment Nodes Cache Key
  21602. return this._nodes.getCacheKey( this.scene, this.lightsNode );
  21603. }
  21604. getCacheKey() {
  21605. return this.getMaterialCacheKey() + ',' + this.getNodesCacheKey();
  21606. }
  21607. dispose() {
  21608. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21609. this.onDispose();
  21610. }
  21611. }
  21612. class RenderObjects {
  21613. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21614. this.renderer = renderer;
  21615. this.nodes = nodes;
  21616. this.geometries = geometries;
  21617. this.pipelines = pipelines;
  21618. this.bindings = bindings;
  21619. this.info = info;
  21620. this.chainMaps = {};
  21621. }
  21622. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  21623. const chainMap = this.getChainMap( passId );
  21624. const chainArray = [ object, material, renderContext, lightsNode ];
  21625. let renderObject = chainMap.get( chainArray );
  21626. if ( renderObject === undefined ) {
  21627. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  21628. chainMap.set( chainArray, renderObject );
  21629. } else {
  21630. renderObject.updateClipping( renderContext.clippingContext );
  21631. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21632. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21633. renderObject.dispose();
  21634. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  21635. } else {
  21636. renderObject.version = material.version;
  21637. }
  21638. }
  21639. }
  21640. return renderObject;
  21641. }
  21642. getChainMap( passId = 'default' ) {
  21643. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21644. }
  21645. dispose() {
  21646. this.chainMaps = {};
  21647. }
  21648. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  21649. const chainMap = this.getChainMap( passId );
  21650. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  21651. renderObject.onDispose = () => {
  21652. this.pipelines.delete( renderObject );
  21653. this.bindings.delete( renderObject );
  21654. this.nodes.delete( renderObject );
  21655. chainMap.delete( renderObject.getChainArray() );
  21656. };
  21657. return renderObject;
  21658. }
  21659. }
  21660. class DataMap {
  21661. constructor() {
  21662. this.data = new WeakMap();
  21663. }
  21664. get( object ) {
  21665. let map = this.data.get( object );
  21666. if ( map === undefined ) {
  21667. map = {};
  21668. this.data.set( object, map );
  21669. }
  21670. return map;
  21671. }
  21672. delete( object ) {
  21673. let map;
  21674. if ( this.data.has( object ) ) {
  21675. map = this.data.get( object );
  21676. this.data.delete( object );
  21677. }
  21678. return map;
  21679. }
  21680. has( object ) {
  21681. return this.data.has( object );
  21682. }
  21683. dispose() {
  21684. this.data = new WeakMap();
  21685. }
  21686. }
  21687. const AttributeType = {
  21688. VERTEX: 1,
  21689. INDEX: 2,
  21690. STORAGE: 4
  21691. };
  21692. // size of a chunk in bytes (STD140 layout)
  21693. const GPU_CHUNK_BYTES = 16;
  21694. // @TODO: Move to src/constants.js
  21695. const BlendColorFactor = 211;
  21696. const OneMinusBlendColorFactor = 212;
  21697. class Attributes extends DataMap {
  21698. constructor( backend ) {
  21699. super();
  21700. this.backend = backend;
  21701. }
  21702. delete( attribute ) {
  21703. const attributeData = super.delete( attribute );
  21704. if ( attributeData !== undefined ) {
  21705. this.backend.destroyAttribute( attribute );
  21706. }
  21707. return attributeData;
  21708. }
  21709. update( attribute, type ) {
  21710. const data = this.get( attribute );
  21711. if ( data.version === undefined ) {
  21712. if ( type === AttributeType.VERTEX ) {
  21713. this.backend.createAttribute( attribute );
  21714. } else if ( type === AttributeType.INDEX ) {
  21715. this.backend.createIndexAttribute( attribute );
  21716. } else if ( type === AttributeType.STORAGE ) {
  21717. this.backend.createStorageAttribute( attribute );
  21718. }
  21719. data.version = this._getBufferAttribute( attribute ).version;
  21720. } else {
  21721. const bufferAttribute = this._getBufferAttribute( attribute );
  21722. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21723. this.backend.updateAttribute( attribute );
  21724. data.version = bufferAttribute.version;
  21725. }
  21726. }
  21727. }
  21728. _getBufferAttribute( attribute ) {
  21729. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21730. return attribute;
  21731. }
  21732. }
  21733. function arrayNeedsUint32( array ) {
  21734. // assumes larger values usually on last
  21735. for ( let i = array.length - 1; i >= 0; -- i ) {
  21736. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  21737. }
  21738. return false;
  21739. }
  21740. function getWireframeVersion( geometry ) {
  21741. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21742. }
  21743. function getWireframeIndex( geometry ) {
  21744. const indices = [];
  21745. const geometryIndex = geometry.index;
  21746. const geometryPosition = geometry.attributes.position;
  21747. if ( geometryIndex !== null ) {
  21748. const array = geometryIndex.array;
  21749. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21750. const a = array[ i + 0 ];
  21751. const b = array[ i + 1 ];
  21752. const c = array[ i + 2 ];
  21753. indices.push( a, b, b, c, c, a );
  21754. }
  21755. } else {
  21756. const array = geometryPosition.array;
  21757. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21758. const a = i + 0;
  21759. const b = i + 1;
  21760. const c = i + 2;
  21761. indices.push( a, b, b, c, c, a );
  21762. }
  21763. }
  21764. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21765. attribute.version = getWireframeVersion( geometry );
  21766. return attribute;
  21767. }
  21768. class Geometries extends DataMap {
  21769. constructor( attributes, info ) {
  21770. super();
  21771. this.attributes = attributes;
  21772. this.info = info;
  21773. this.wireframes = new WeakMap();
  21774. this.attributeCall = new WeakMap();
  21775. }
  21776. has( renderObject ) {
  21777. const geometry = renderObject.geometry;
  21778. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21779. }
  21780. updateForRender( renderObject ) {
  21781. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21782. this.updateAttributes( renderObject );
  21783. }
  21784. initGeometry( renderObject ) {
  21785. const geometry = renderObject.geometry;
  21786. const geometryData = this.get( geometry );
  21787. geometryData.initialized = true;
  21788. this.info.memory.geometries ++;
  21789. const onDispose = () => {
  21790. this.info.memory.geometries --;
  21791. const index = geometry.index;
  21792. const geometryAttributes = renderObject.getAttributes();
  21793. if ( index !== null ) {
  21794. this.attributes.delete( index );
  21795. }
  21796. for ( const geometryAttribute of geometryAttributes ) {
  21797. this.attributes.delete( geometryAttribute );
  21798. }
  21799. const wireframeAttribute = this.wireframes.get( geometry );
  21800. if ( wireframeAttribute !== undefined ) {
  21801. this.attributes.delete( wireframeAttribute );
  21802. }
  21803. geometry.removeEventListener( 'dispose', onDispose );
  21804. };
  21805. geometry.addEventListener( 'dispose', onDispose );
  21806. }
  21807. updateAttributes( renderObject ) {
  21808. const attributes = renderObject.getAttributes();
  21809. for ( const attribute of attributes ) {
  21810. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21811. this.updateAttribute( attribute, AttributeType.STORAGE );
  21812. } else {
  21813. this.updateAttribute( attribute, AttributeType.VERTEX );
  21814. }
  21815. }
  21816. const index = this.getIndex( renderObject );
  21817. if ( index !== null ) {
  21818. this.updateAttribute( index, AttributeType.INDEX );
  21819. }
  21820. }
  21821. updateAttribute( attribute, type ) {
  21822. const callId = this.info.render.calls;
  21823. if ( ! attribute.isInterleavedBufferAttribute ) {
  21824. if ( this.attributeCall.get( attribute ) !== callId ) {
  21825. this.attributes.update( attribute, type );
  21826. this.attributeCall.set( attribute, callId );
  21827. }
  21828. } else {
  21829. if ( this.attributeCall.get( attribute ) === undefined ) {
  21830. this.attributes.update( attribute, type );
  21831. this.attributeCall.set( attribute, callId );
  21832. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21833. this.attributes.update( attribute, type );
  21834. this.attributeCall.set( attribute.data, callId );
  21835. this.attributeCall.set( attribute, callId );
  21836. }
  21837. }
  21838. }
  21839. getIndex( renderObject ) {
  21840. const { geometry, material } = renderObject;
  21841. let index = geometry.index;
  21842. if ( material.wireframe === true ) {
  21843. const wireframes = this.wireframes;
  21844. let wireframeAttribute = wireframes.get( geometry );
  21845. if ( wireframeAttribute === undefined ) {
  21846. wireframeAttribute = getWireframeIndex( geometry );
  21847. wireframes.set( geometry, wireframeAttribute );
  21848. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21849. this.attributes.delete( wireframeAttribute );
  21850. wireframeAttribute = getWireframeIndex( geometry );
  21851. wireframes.set( geometry, wireframeAttribute );
  21852. }
  21853. index = wireframeAttribute;
  21854. }
  21855. return index;
  21856. }
  21857. }
  21858. class Info {
  21859. constructor() {
  21860. this.autoReset = true;
  21861. this.frame = 0;
  21862. this.calls = 0;
  21863. this.render = {
  21864. calls: 0,
  21865. frameCalls: 0,
  21866. drawCalls: 0,
  21867. triangles: 0,
  21868. points: 0,
  21869. lines: 0,
  21870. timestamp: 0,
  21871. previousFrameCalls: 0,
  21872. timestampCalls: 0
  21873. };
  21874. this.compute = {
  21875. calls: 0,
  21876. frameCalls: 0,
  21877. timestamp: 0,
  21878. previousFrameCalls: 0,
  21879. timestampCalls: 0
  21880. };
  21881. this.memory = {
  21882. geometries: 0,
  21883. textures: 0
  21884. };
  21885. }
  21886. update( object, count, instanceCount ) {
  21887. this.render.drawCalls ++;
  21888. if ( object.isMesh || object.isSprite ) {
  21889. this.render.triangles += instanceCount * ( count / 3 );
  21890. } else if ( object.isPoints ) {
  21891. this.render.points += instanceCount * count;
  21892. } else if ( object.isLineSegments ) {
  21893. this.render.lines += instanceCount * ( count / 2 );
  21894. } else if ( object.isLine ) {
  21895. this.render.lines += instanceCount * ( count - 1 );
  21896. } else {
  21897. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  21898. }
  21899. }
  21900. updateTimestamp( type, time ) {
  21901. if ( this[ type ].timestampCalls === 0 ) {
  21902. this[ type ].timestamp = 0;
  21903. }
  21904. this[ type ].timestamp += time;
  21905. this[ type ].timestampCalls ++;
  21906. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  21907. this[ type ].timestampCalls = 0;
  21908. }
  21909. }
  21910. reset() {
  21911. const previousRenderFrameCalls = this.render.frameCalls;
  21912. this.render.previousFrameCalls = previousRenderFrameCalls;
  21913. const previousComputeFrameCalls = this.compute.frameCalls;
  21914. this.compute.previousFrameCalls = previousComputeFrameCalls;
  21915. this.render.drawCalls = 0;
  21916. this.render.frameCalls = 0;
  21917. this.compute.frameCalls = 0;
  21918. this.render.triangles = 0;
  21919. this.render.points = 0;
  21920. this.render.lines = 0;
  21921. }
  21922. dispose() {
  21923. this.reset();
  21924. this.calls = 0;
  21925. this.render.calls = 0;
  21926. this.compute.calls = 0;
  21927. this.render.timestamp = 0;
  21928. this.compute.timestamp = 0;
  21929. this.memory.geometries = 0;
  21930. this.memory.textures = 0;
  21931. }
  21932. }
  21933. class Pipeline {
  21934. constructor( cacheKey ) {
  21935. this.cacheKey = cacheKey;
  21936. this.usedTimes = 0;
  21937. }
  21938. }
  21939. class RenderPipeline extends Pipeline {
  21940. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21941. super( cacheKey );
  21942. this.vertexProgram = vertexProgram;
  21943. this.fragmentProgram = fragmentProgram;
  21944. }
  21945. }
  21946. class ComputePipeline extends Pipeline {
  21947. constructor( cacheKey, computeProgram ) {
  21948. super( cacheKey );
  21949. this.computeProgram = computeProgram;
  21950. this.isComputePipeline = true;
  21951. }
  21952. }
  21953. let _id$4 = 0;
  21954. class ProgrammableStage {
  21955. constructor( code, type, transforms = null, attributes = null ) {
  21956. this.id = _id$4 ++;
  21957. this.code = code;
  21958. this.stage = type;
  21959. this.transforms = transforms;
  21960. this.attributes = attributes;
  21961. this.usedTimes = 0;
  21962. }
  21963. }
  21964. class Pipelines extends DataMap {
  21965. constructor( backend, nodes ) {
  21966. super();
  21967. this.backend = backend;
  21968. this.nodes = nodes;
  21969. this.bindings = null; // set by the bindings
  21970. this.caches = new Map();
  21971. this.programs = {
  21972. vertex: new Map(),
  21973. fragment: new Map(),
  21974. compute: new Map()
  21975. };
  21976. }
  21977. getForCompute( computeNode, bindings ) {
  21978. const { backend } = this;
  21979. const data = this.get( computeNode );
  21980. if ( this._needsComputeUpdate( computeNode ) ) {
  21981. const previousPipeline = data.pipeline;
  21982. if ( previousPipeline ) {
  21983. previousPipeline.usedTimes --;
  21984. previousPipeline.computeProgram.usedTimes --;
  21985. }
  21986. // get shader
  21987. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21988. // programmable stage
  21989. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21990. if ( stageCompute === undefined ) {
  21991. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21992. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21993. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21994. backend.createProgram( stageCompute );
  21995. }
  21996. // determine compute pipeline
  21997. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21998. let pipeline = this.caches.get( cacheKey );
  21999. if ( pipeline === undefined ) {
  22000. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22001. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22002. }
  22003. // keep track of all used times
  22004. pipeline.usedTimes ++;
  22005. stageCompute.usedTimes ++;
  22006. //
  22007. data.version = computeNode.version;
  22008. data.pipeline = pipeline;
  22009. }
  22010. return data.pipeline;
  22011. }
  22012. getForRender( renderObject, promises = null ) {
  22013. const { backend } = this;
  22014. const data = this.get( renderObject );
  22015. if ( this._needsRenderUpdate( renderObject ) ) {
  22016. const previousPipeline = data.pipeline;
  22017. if ( previousPipeline ) {
  22018. previousPipeline.usedTimes --;
  22019. previousPipeline.vertexProgram.usedTimes --;
  22020. previousPipeline.fragmentProgram.usedTimes --;
  22021. }
  22022. // get shader
  22023. const nodeBuilderState = renderObject.getNodeBuilderState();
  22024. // programmable stages
  22025. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22026. if ( stageVertex === undefined ) {
  22027. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22028. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  22029. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22030. backend.createProgram( stageVertex );
  22031. }
  22032. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22033. if ( stageFragment === undefined ) {
  22034. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22035. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  22036. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22037. backend.createProgram( stageFragment );
  22038. }
  22039. // determine render pipeline
  22040. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22041. let pipeline = this.caches.get( cacheKey );
  22042. if ( pipeline === undefined ) {
  22043. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22044. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22045. } else {
  22046. renderObject.pipeline = pipeline;
  22047. }
  22048. // keep track of all used times
  22049. pipeline.usedTimes ++;
  22050. stageVertex.usedTimes ++;
  22051. stageFragment.usedTimes ++;
  22052. //
  22053. data.pipeline = pipeline;
  22054. }
  22055. return data.pipeline;
  22056. }
  22057. delete( object ) {
  22058. const pipeline = this.get( object ).pipeline;
  22059. if ( pipeline ) {
  22060. // pipeline
  22061. pipeline.usedTimes --;
  22062. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22063. // programs
  22064. if ( pipeline.isComputePipeline ) {
  22065. pipeline.computeProgram.usedTimes --;
  22066. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22067. } else {
  22068. pipeline.fragmentProgram.usedTimes --;
  22069. pipeline.vertexProgram.usedTimes --;
  22070. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22071. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22072. }
  22073. }
  22074. return super.delete( object );
  22075. }
  22076. dispose() {
  22077. super.dispose();
  22078. this.caches = new Map();
  22079. this.programs = {
  22080. vertex: new Map(),
  22081. fragment: new Map(),
  22082. compute: new Map()
  22083. };
  22084. }
  22085. updateForRender( renderObject ) {
  22086. this.getForRender( renderObject );
  22087. }
  22088. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22089. // check for existing pipeline
  22090. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22091. let pipeline = this.caches.get( cacheKey );
  22092. if ( pipeline === undefined ) {
  22093. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22094. this.caches.set( cacheKey, pipeline );
  22095. this.backend.createComputePipeline( pipeline, bindings );
  22096. }
  22097. return pipeline;
  22098. }
  22099. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22100. // check for existing pipeline
  22101. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22102. let pipeline = this.caches.get( cacheKey );
  22103. if ( pipeline === undefined ) {
  22104. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  22105. this.caches.set( cacheKey, pipeline );
  22106. renderObject.pipeline = pipeline;
  22107. this.backend.createRenderPipeline( renderObject, promises );
  22108. }
  22109. return pipeline;
  22110. }
  22111. _getComputeCacheKey( computeNode, stageCompute ) {
  22112. return computeNode.id + ',' + stageCompute.id;
  22113. }
  22114. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22115. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22116. }
  22117. _releasePipeline( pipeline ) {
  22118. this.caches.delete( pipeline.cacheKey );
  22119. }
  22120. _releaseProgram( program ) {
  22121. const code = program.code;
  22122. const stage = program.stage;
  22123. this.programs[ stage ].delete( code );
  22124. }
  22125. _needsComputeUpdate( computeNode ) {
  22126. const data = this.get( computeNode );
  22127. return data.pipeline === undefined || data.version !== computeNode.version;
  22128. }
  22129. _needsRenderUpdate( renderObject ) {
  22130. const data = this.get( renderObject );
  22131. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22132. }
  22133. }
  22134. class Bindings extends DataMap {
  22135. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22136. super();
  22137. this.backend = backend;
  22138. this.textures = textures;
  22139. this.pipelines = pipelines;
  22140. this.attributes = attributes;
  22141. this.nodes = nodes;
  22142. this.info = info;
  22143. this.pipelines.bindings = this; // assign bindings to pipelines
  22144. }
  22145. getForRender( renderObject ) {
  22146. const bindings = renderObject.getBindings();
  22147. for ( const bindGroup of bindings ) {
  22148. const groupData = this.get( bindGroup );
  22149. if ( groupData.bindGroup === undefined ) {
  22150. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22151. this._init( bindGroup );
  22152. this.backend.createBindings( bindGroup, bindings );
  22153. groupData.bindGroup = bindGroup;
  22154. }
  22155. }
  22156. return bindings;
  22157. }
  22158. getForCompute( computeNode ) {
  22159. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22160. for ( const bindGroup of bindings ) {
  22161. const groupData = this.get( bindGroup );
  22162. if ( groupData.bindGroup === undefined ) {
  22163. this._init( bindGroup );
  22164. this.backend.createBindings( bindGroup, bindings );
  22165. groupData.bindGroup = bindGroup;
  22166. }
  22167. }
  22168. return bindings;
  22169. }
  22170. updateForCompute( computeNode ) {
  22171. this._updateBindings( computeNode, this.getForCompute( computeNode ) );
  22172. }
  22173. updateForRender( renderObject ) {
  22174. this._updateBindings( renderObject, this.getForRender( renderObject ) );
  22175. }
  22176. _updateBindings( object, bindings ) {
  22177. for ( const bindGroup of bindings ) {
  22178. this._update( object, bindGroup, bindings );
  22179. }
  22180. }
  22181. _init( bindGroup ) {
  22182. for ( const binding of bindGroup.bindings ) {
  22183. if ( binding.isSampledTexture ) {
  22184. this.textures.updateTexture( binding.texture );
  22185. } else if ( binding.isStorageBuffer ) {
  22186. const attribute = binding.attribute;
  22187. this.attributes.update( attribute, AttributeType.STORAGE );
  22188. }
  22189. }
  22190. }
  22191. _update( object, bindGroup, bindings ) {
  22192. const { backend } = this;
  22193. let needsBindingsUpdate = false;
  22194. // iterate over all bindings and check if buffer updates or a new binding group is required
  22195. for ( const binding of bindGroup.bindings ) {
  22196. if ( binding.isNodeUniformsGroup ) {
  22197. const updated = this.nodes.updateGroup( binding );
  22198. if ( ! updated ) continue;
  22199. }
  22200. if ( binding.isUniformBuffer ) {
  22201. const updated = binding.update();
  22202. if ( updated ) {
  22203. backend.updateBinding( binding );
  22204. }
  22205. } else if ( binding.isSampler ) {
  22206. binding.update();
  22207. } else if ( binding.isSampledTexture ) {
  22208. const texture = binding.texture;
  22209. if ( binding.needsBindingsUpdate ) needsBindingsUpdate = true;
  22210. const updated = binding.update();
  22211. if ( updated ) {
  22212. this.textures.updateTexture( binding.texture );
  22213. }
  22214. const textureData = backend.get( binding.texture );
  22215. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  22216. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  22217. console.error( 'Bindings._update: binding should be available:', binding, updated, binding.texture, binding.textureNode.value );
  22218. this.textures.updateTexture( binding.texture );
  22219. needsBindingsUpdate = true;
  22220. }
  22221. if ( texture.isStorageTexture === true ) {
  22222. const textureData = this.get( texture );
  22223. if ( binding.store === true ) {
  22224. textureData.needsMipmap = true;
  22225. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22226. this.backend.generateMipmaps( texture );
  22227. textureData.needsMipmap = false;
  22228. }
  22229. }
  22230. }
  22231. }
  22232. if ( needsBindingsUpdate === true ) {
  22233. const pipeline = this.pipelines.getForRender( object );
  22234. this.backend.updateBindings( bindGroup, bindings, pipeline );
  22235. }
  22236. }
  22237. }
  22238. const NodeShaderStage = {
  22239. VERTEX: 'vertex',
  22240. FRAGMENT: 'fragment'
  22241. };
  22242. const NodeUpdateType = {
  22243. NONE: 'none',
  22244. FRAME: 'frame',
  22245. RENDER: 'render',
  22246. OBJECT: 'object'
  22247. };
  22248. const NodeType = {
  22249. BOOLEAN: 'bool',
  22250. INTEGER: 'int',
  22251. FLOAT: 'float',
  22252. VECTOR2: 'vec2',
  22253. VECTOR3: 'vec3',
  22254. VECTOR4: 'vec4',
  22255. MATRIX2: 'mat2',
  22256. MATRIX3: 'mat3',
  22257. MATRIX4: 'mat4'
  22258. };
  22259. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22260. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22261. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22262. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22263. function getCacheKey( object, force = false ) {
  22264. let cacheKey = '{';
  22265. if ( object.isNode === true ) {
  22266. cacheKey += object.id;
  22267. }
  22268. for ( const { property, childNode } of getNodeChildren( object ) ) {
  22269. cacheKey += ',' + property.slice( 0, - 4 ) + ':' + childNode.getCacheKey( force );
  22270. }
  22271. cacheKey += '}';
  22272. return cacheKey;
  22273. }
  22274. function* getNodeChildren( node, toJSON = false ) {
  22275. for ( const property in node ) {
  22276. // Ignore private properties.
  22277. if ( property.startsWith( '_' ) === true ) continue;
  22278. const object = node[ property ];
  22279. if ( Array.isArray( object ) === true ) {
  22280. for ( let i = 0; i < object.length; i ++ ) {
  22281. const child = object[ i ];
  22282. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22283. yield { property, index: i, childNode: child };
  22284. }
  22285. }
  22286. } else if ( object && object.isNode === true ) {
  22287. yield { property, childNode: object };
  22288. } else if ( typeof object === 'object' ) {
  22289. for ( const subProperty in object ) {
  22290. const child = object[ subProperty ];
  22291. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22292. yield { property, index: subProperty, childNode: child };
  22293. }
  22294. }
  22295. }
  22296. }
  22297. }
  22298. function getValueType( value ) {
  22299. if ( value === undefined || value === null ) return null;
  22300. const typeOf = typeof value;
  22301. if ( value.isNode === true ) {
  22302. return 'node';
  22303. } else if ( typeOf === 'number' ) {
  22304. return 'float';
  22305. } else if ( typeOf === 'boolean' ) {
  22306. return 'bool';
  22307. } else if ( typeOf === 'string' ) {
  22308. return 'string';
  22309. } else if ( typeOf === 'function' ) {
  22310. return 'shader';
  22311. } else if ( value.isVector2 === true ) {
  22312. return 'vec2';
  22313. } else if ( value.isVector3 === true ) {
  22314. return 'vec3';
  22315. } else if ( value.isVector4 === true ) {
  22316. return 'vec4';
  22317. } else if ( value.isMatrix3 === true ) {
  22318. return 'mat3';
  22319. } else if ( value.isMatrix4 === true ) {
  22320. return 'mat4';
  22321. } else if ( value.isColor === true ) {
  22322. return 'color';
  22323. } else if ( value instanceof ArrayBuffer ) {
  22324. return 'ArrayBuffer';
  22325. }
  22326. return null;
  22327. }
  22328. function getValueFromType( type, ...params ) {
  22329. const last4 = type ? type.slice( - 4 ) : undefined;
  22330. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  22331. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  22332. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  22333. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  22334. }
  22335. if ( type === 'color' ) {
  22336. return new Color( ...params );
  22337. } else if ( last4 === 'vec2' ) {
  22338. return new Vector2( ...params );
  22339. } else if ( last4 === 'vec3' ) {
  22340. return new Vector3( ...params );
  22341. } else if ( last4 === 'vec4' ) {
  22342. return new Vector4( ...params );
  22343. } else if ( last4 === 'mat3' ) {
  22344. return new Matrix3( ...params );
  22345. } else if ( last4 === 'mat4' ) {
  22346. return new Matrix4( ...params );
  22347. } else if ( type === 'bool' ) {
  22348. return params[ 0 ] || false;
  22349. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  22350. return params[ 0 ] || 0;
  22351. } else if ( type === 'string' ) {
  22352. return params[ 0 ] || '';
  22353. } else if ( type === 'ArrayBuffer' ) {
  22354. return base64ToArrayBuffer( params[ 0 ] );
  22355. }
  22356. return null;
  22357. }
  22358. function arrayBufferToBase64( arrayBuffer ) {
  22359. let chars = '';
  22360. const array = new Uint8Array( arrayBuffer );
  22361. for ( let i = 0; i < array.length; i ++ ) {
  22362. chars += String.fromCharCode( array[ i ] );
  22363. }
  22364. return btoa( chars );
  22365. }
  22366. function base64ToArrayBuffer( base64 ) {
  22367. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  22368. }
  22369. var NodeUtils = /*#__PURE__*/Object.freeze({
  22370. __proto__: null,
  22371. arrayBufferToBase64: arrayBufferToBase64,
  22372. base64ToArrayBuffer: base64ToArrayBuffer,
  22373. getCacheKey: getCacheKey,
  22374. getNodeChildren: getNodeChildren,
  22375. getValueFromType: getValueFromType,
  22376. getValueType: getValueType
  22377. });
  22378. const NodeClasses = new Map();
  22379. let _nodeId = 0;
  22380. class Node extends EventDispatcher {
  22381. constructor( nodeType = null ) {
  22382. super();
  22383. this.nodeType = nodeType;
  22384. this.updateType = NodeUpdateType.NONE;
  22385. this.updateBeforeType = NodeUpdateType.NONE;
  22386. this.updateAfterType = NodeUpdateType.NONE;
  22387. this.uuid = MathUtils.generateUUID();
  22388. this.version = 0;
  22389. this._cacheKey = null;
  22390. this._cacheKeyVersion = 0;
  22391. this.global = false;
  22392. this.isNode = true;
  22393. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22394. }
  22395. set needsUpdate( value ) {
  22396. if ( value === true ) {
  22397. this.version ++;
  22398. }
  22399. }
  22400. get type() {
  22401. return this.constructor.type;
  22402. }
  22403. onUpdate( callback, updateType ) {
  22404. this.updateType = updateType;
  22405. this.update = callback.bind( this.getSelf() );
  22406. return this;
  22407. }
  22408. onFrameUpdate( callback ) {
  22409. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22410. }
  22411. onRenderUpdate( callback ) {
  22412. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22413. }
  22414. onObjectUpdate( callback ) {
  22415. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22416. }
  22417. onReference( callback ) {
  22418. this.updateReference = callback.bind( this.getSelf() );
  22419. return this;
  22420. }
  22421. getSelf() {
  22422. // Returns non-node object.
  22423. return this.self || this;
  22424. }
  22425. updateReference( /*state*/ ) {
  22426. return this;
  22427. }
  22428. isGlobal( /*builder*/ ) {
  22429. return this.global;
  22430. }
  22431. * getChildren() {
  22432. for ( const { childNode } of getNodeChildren( this ) ) {
  22433. yield childNode;
  22434. }
  22435. }
  22436. dispose() {
  22437. this.dispatchEvent( { type: 'dispose' } );
  22438. }
  22439. traverse( callback ) {
  22440. callback( this );
  22441. for ( const childNode of this.getChildren() ) {
  22442. childNode.traverse( callback );
  22443. }
  22444. }
  22445. getCacheKey( force = false ) {
  22446. force = force || this.version !== this._cacheKeyVersion;
  22447. if ( force === true || this._cacheKey === null ) {
  22448. this._cacheKey = getCacheKey( this, force );
  22449. this._cacheKeyVersion = this.version;
  22450. }
  22451. return this._cacheKey;
  22452. }
  22453. getHash( /*builder*/ ) {
  22454. return this.uuid;
  22455. }
  22456. getUpdateType() {
  22457. return this.updateType;
  22458. }
  22459. getUpdateBeforeType() {
  22460. return this.updateBeforeType;
  22461. }
  22462. getUpdateAfterType() {
  22463. return this.updateAfterType;
  22464. }
  22465. getElementType( builder ) {
  22466. const type = this.getNodeType( builder );
  22467. const elementType = builder.getElementType( type );
  22468. return elementType;
  22469. }
  22470. getNodeType( builder ) {
  22471. const nodeProperties = builder.getNodeProperties( this );
  22472. if ( nodeProperties.outputNode ) {
  22473. return nodeProperties.outputNode.getNodeType( builder );
  22474. }
  22475. return this.nodeType;
  22476. }
  22477. getShared( builder ) {
  22478. const hash = this.getHash( builder );
  22479. const nodeFromHash = builder.getNodeFromHash( hash );
  22480. return nodeFromHash || this;
  22481. }
  22482. setup( builder ) {
  22483. const nodeProperties = builder.getNodeProperties( this );
  22484. let index = 0;
  22485. for ( const childNode of this.getChildren() ) {
  22486. nodeProperties[ 'node' + index ++ ] = childNode;
  22487. }
  22488. // return a outputNode if exists
  22489. return null;
  22490. }
  22491. construct( builder ) { // @deprecated, r157
  22492. console.warn( 'THREE.Node: construct() is deprecated. Use setup() instead.' );
  22493. return this.setup( builder );
  22494. }
  22495. increaseUsage( builder ) {
  22496. const nodeData = builder.getDataFromNode( this );
  22497. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  22498. return nodeData.usageCount;
  22499. }
  22500. analyze( builder ) {
  22501. const usageCount = this.increaseUsage( builder );
  22502. if ( usageCount === 1 ) {
  22503. // node flow children
  22504. const nodeProperties = builder.getNodeProperties( this );
  22505. for ( const childNode of Object.values( nodeProperties ) ) {
  22506. if ( childNode && childNode.isNode === true ) {
  22507. childNode.build( builder );
  22508. }
  22509. }
  22510. }
  22511. }
  22512. generate( builder, output ) {
  22513. const { outputNode } = builder.getNodeProperties( this );
  22514. if ( outputNode && outputNode.isNode === true ) {
  22515. return outputNode.build( builder, output );
  22516. }
  22517. }
  22518. updateBefore( /*frame*/ ) {
  22519. console.warn( 'Abstract function.' );
  22520. }
  22521. updateAfter( /*frame*/ ) {
  22522. console.warn( 'Abstract function.' );
  22523. }
  22524. update( /*frame*/ ) {
  22525. console.warn( 'Abstract function.' );
  22526. }
  22527. build( builder, output = null ) {
  22528. const refNode = this.getShared( builder );
  22529. if ( this !== refNode ) {
  22530. return refNode.build( builder, output );
  22531. }
  22532. builder.addNode( this );
  22533. builder.addChain( this );
  22534. /* Build stages expected results:
  22535. - "setup" -> Node
  22536. - "analyze" -> null
  22537. - "generate" -> String
  22538. */
  22539. let result = null;
  22540. const buildStage = builder.getBuildStage();
  22541. if ( buildStage === 'setup' ) {
  22542. this.updateReference( builder );
  22543. const properties = builder.getNodeProperties( this );
  22544. if ( properties.initialized !== true ) {
  22545. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22546. properties.initialized = true;
  22547. properties.outputNode = this.setup( builder );
  22548. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  22549. properties.outputNode = builder.stack;
  22550. }
  22551. for ( const childNode of Object.values( properties ) ) {
  22552. if ( childNode && childNode.isNode === true ) {
  22553. childNode.build( builder );
  22554. }
  22555. }
  22556. }
  22557. } else if ( buildStage === 'analyze' ) {
  22558. this.analyze( builder );
  22559. } else if ( buildStage === 'generate' ) {
  22560. const isGenerateOnce = this.generate.length === 1;
  22561. if ( isGenerateOnce ) {
  22562. const type = this.getNodeType( builder );
  22563. const nodeData = builder.getDataFromNode( this );
  22564. result = nodeData.snippet;
  22565. if ( result === undefined ) {
  22566. result = this.generate( builder ) || '';
  22567. nodeData.snippet = result;
  22568. }
  22569. result = builder.format( result, type, output );
  22570. } else {
  22571. result = this.generate( builder, output ) || '';
  22572. }
  22573. }
  22574. builder.removeChain( this );
  22575. return result;
  22576. }
  22577. getSerializeChildren() {
  22578. return getNodeChildren( this );
  22579. }
  22580. serialize( json ) {
  22581. const nodeChildren = this.getSerializeChildren();
  22582. const inputNodes = {};
  22583. for ( const { property, index, childNode } of nodeChildren ) {
  22584. if ( index !== undefined ) {
  22585. if ( inputNodes[ property ] === undefined ) {
  22586. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22587. }
  22588. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22589. } else {
  22590. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22591. }
  22592. }
  22593. if ( Object.keys( inputNodes ).length > 0 ) {
  22594. json.inputNodes = inputNodes;
  22595. }
  22596. }
  22597. deserialize( json ) {
  22598. if ( json.inputNodes !== undefined ) {
  22599. const nodes = json.meta.nodes;
  22600. for ( const property in json.inputNodes ) {
  22601. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22602. const inputArray = [];
  22603. for ( const uuid of json.inputNodes[ property ] ) {
  22604. inputArray.push( nodes[ uuid ] );
  22605. }
  22606. this[ property ] = inputArray;
  22607. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22608. const inputObject = {};
  22609. for ( const subProperty in json.inputNodes[ property ] ) {
  22610. const uuid = json.inputNodes[ property ][ subProperty ];
  22611. inputObject[ subProperty ] = nodes[ uuid ];
  22612. }
  22613. this[ property ] = inputObject;
  22614. } else {
  22615. const uuid = json.inputNodes[ property ];
  22616. this[ property ] = nodes[ uuid ];
  22617. }
  22618. }
  22619. }
  22620. }
  22621. toJSON( meta ) {
  22622. const { uuid, type } = this;
  22623. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22624. if ( isRoot ) {
  22625. meta = {
  22626. textures: {},
  22627. images: {},
  22628. nodes: {}
  22629. };
  22630. }
  22631. // serialize
  22632. let data = meta.nodes[ uuid ];
  22633. if ( data === undefined ) {
  22634. data = {
  22635. uuid,
  22636. type,
  22637. meta,
  22638. metadata: {
  22639. version: 4.6,
  22640. type: 'Node',
  22641. generator: 'Node.toJSON'
  22642. }
  22643. };
  22644. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22645. this.serialize( data );
  22646. delete data.meta;
  22647. }
  22648. // TODO: Copied from Object3D.toJSON
  22649. function extractFromCache( cache ) {
  22650. const values = [];
  22651. for ( const key in cache ) {
  22652. const data = cache[ key ];
  22653. delete data.metadata;
  22654. values.push( data );
  22655. }
  22656. return values;
  22657. }
  22658. if ( isRoot ) {
  22659. const textures = extractFromCache( meta.textures );
  22660. const images = extractFromCache( meta.images );
  22661. const nodes = extractFromCache( meta.nodes );
  22662. if ( textures.length > 0 ) data.textures = textures;
  22663. if ( images.length > 0 ) data.images = images;
  22664. if ( nodes.length > 0 ) data.nodes = nodes;
  22665. }
  22666. return data;
  22667. }
  22668. }
  22669. function addNodeClass( type, nodeClass ) {
  22670. if ( typeof nodeClass !== 'function' || ! type ) throw new Error( `Node class ${ type } is not a class` );
  22671. if ( NodeClasses.has( type ) ) {
  22672. console.warn( `Redefinition of node class ${ type }` );
  22673. return;
  22674. }
  22675. NodeClasses.set( type, nodeClass );
  22676. nodeClass.type = type;
  22677. }
  22678. function createNodeFromType( type ) {
  22679. const Class = NodeClasses.get( type );
  22680. if ( Class !== undefined ) {
  22681. return new Class();
  22682. }
  22683. }
  22684. class TempNode extends Node {
  22685. constructor( type ) {
  22686. super( type );
  22687. this.isTempNode = true;
  22688. }
  22689. hasDependencies( builder ) {
  22690. return builder.getDataFromNode( this ).usageCount > 1;
  22691. }
  22692. build( builder, output ) {
  22693. const buildStage = builder.getBuildStage();
  22694. if ( buildStage === 'generate' ) {
  22695. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22696. const nodeData = builder.getDataFromNode( this );
  22697. if ( nodeData.propertyName !== undefined ) {
  22698. return builder.format( nodeData.propertyName, type, output );
  22699. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22700. const snippet = super.build( builder, type );
  22701. const nodeVar = builder.getVarFromNode( this, null, type );
  22702. const propertyName = builder.getPropertyName( nodeVar );
  22703. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  22704. nodeData.snippet = snippet;
  22705. nodeData.propertyName = propertyName;
  22706. return builder.format( nodeData.propertyName, type, output );
  22707. }
  22708. }
  22709. return super.build( builder, output );
  22710. }
  22711. }
  22712. addNodeClass( 'TempNode', TempNode );
  22713. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  22714. constructor( node, indexNode ) {
  22715. super();
  22716. this.node = node;
  22717. this.indexNode = indexNode;
  22718. this.isArrayElementNode = true;
  22719. }
  22720. getNodeType( builder ) {
  22721. return this.node.getElementType( builder );
  22722. }
  22723. generate( builder ) {
  22724. const nodeSnippet = this.node.build( builder );
  22725. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22726. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22727. }
  22728. }
  22729. addNodeClass( 'ArrayElementNode', ArrayElementNode );
  22730. class ConvertNode extends Node {
  22731. constructor( node, convertTo ) {
  22732. super();
  22733. this.node = node;
  22734. this.convertTo = convertTo;
  22735. }
  22736. getNodeType( builder ) {
  22737. const requestType = this.node.getNodeType( builder );
  22738. let convertTo = null;
  22739. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22740. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22741. convertTo = overloadingType;
  22742. }
  22743. }
  22744. return convertTo;
  22745. }
  22746. serialize( data ) {
  22747. super.serialize( data );
  22748. data.convertTo = this.convertTo;
  22749. }
  22750. deserialize( data ) {
  22751. super.deserialize( data );
  22752. this.convertTo = data.convertTo;
  22753. }
  22754. generate( builder, output ) {
  22755. const node = this.node;
  22756. const type = this.getNodeType( builder );
  22757. const snippet = node.build( builder, type );
  22758. return builder.format( snippet, type, output );
  22759. }
  22760. }
  22761. addNodeClass( 'ConvertNode', ConvertNode );
  22762. class JoinNode extends TempNode {
  22763. constructor( nodes = [], nodeType = null ) {
  22764. super( nodeType );
  22765. this.nodes = nodes;
  22766. }
  22767. getNodeType( builder ) {
  22768. if ( this.nodeType !== null ) {
  22769. return builder.getVectorType( this.nodeType );
  22770. }
  22771. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22772. }
  22773. generate( builder, output ) {
  22774. const type = this.getNodeType( builder );
  22775. const nodes = this.nodes;
  22776. const primitiveType = builder.getComponentType( type );
  22777. const snippetValues = [];
  22778. for ( const input of nodes ) {
  22779. let inputSnippet = input.build( builder );
  22780. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22781. if ( inputPrimitiveType !== primitiveType ) {
  22782. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22783. }
  22784. snippetValues.push( inputSnippet );
  22785. }
  22786. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22787. return builder.format( snippet, type, output );
  22788. }
  22789. }
  22790. addNodeClass( 'JoinNode', JoinNode );
  22791. const stringVectorComponents = vectorComponents.join( '' );
  22792. class SplitNode extends Node {
  22793. constructor( node, components = 'x' ) {
  22794. super();
  22795. this.node = node;
  22796. this.components = components;
  22797. this.isSplitNode = true;
  22798. }
  22799. getVectorLength() {
  22800. let vectorLength = this.components.length;
  22801. for ( const c of this.components ) {
  22802. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22803. }
  22804. return vectorLength;
  22805. }
  22806. getComponentType( builder ) {
  22807. return builder.getComponentType( this.node.getNodeType( builder ) );
  22808. }
  22809. getNodeType( builder ) {
  22810. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22811. }
  22812. generate( builder, output ) {
  22813. const node = this.node;
  22814. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22815. let snippet = null;
  22816. if ( nodeTypeLength > 1 ) {
  22817. let type = null;
  22818. const componentsLength = this.getVectorLength();
  22819. if ( componentsLength >= nodeTypeLength ) {
  22820. // needed expand the input node
  22821. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22822. }
  22823. const nodeSnippet = node.build( builder, type );
  22824. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22825. // unnecessary swizzle
  22826. snippet = builder.format( nodeSnippet, type, output );
  22827. } else {
  22828. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22829. }
  22830. } else {
  22831. // ignore .components if .node returns float/integer
  22832. snippet = node.build( builder, output );
  22833. }
  22834. return snippet;
  22835. }
  22836. serialize( data ) {
  22837. super.serialize( data );
  22838. data.components = this.components;
  22839. }
  22840. deserialize( data ) {
  22841. super.deserialize( data );
  22842. this.components = data.components;
  22843. }
  22844. }
  22845. addNodeClass( 'SplitNode', SplitNode );
  22846. class SetNode extends TempNode {
  22847. constructor( sourceNode, components, targetNode ) {
  22848. super();
  22849. this.sourceNode = sourceNode;
  22850. this.components = components;
  22851. this.targetNode = targetNode;
  22852. }
  22853. getNodeType( builder ) {
  22854. return this.sourceNode.getNodeType( builder );
  22855. }
  22856. generate( builder ) {
  22857. const { sourceNode, components, targetNode } = this;
  22858. const sourceType = this.getNodeType( builder );
  22859. const targetType = builder.getTypeFromLength( components.length );
  22860. const targetSnippet = targetNode.build( builder, targetType );
  22861. const sourceSnippet = sourceNode.build( builder, sourceType );
  22862. const length = builder.getTypeLength( sourceType );
  22863. const snippetValues = [];
  22864. for ( let i = 0; i < length; i ++ ) {
  22865. const component = vectorComponents[ i ];
  22866. if ( component === components[ 0 ] ) {
  22867. snippetValues.push( targetSnippet );
  22868. i += components.length - 1;
  22869. } else {
  22870. snippetValues.push( sourceSnippet + '.' + component );
  22871. }
  22872. }
  22873. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22874. }
  22875. }
  22876. addNodeClass( 'SetNode', SetNode );
  22877. class InputNode extends Node {
  22878. constructor( value, nodeType = null ) {
  22879. super( nodeType );
  22880. this.isInputNode = true;
  22881. this.value = value;
  22882. this.precision = null;
  22883. }
  22884. getNodeType( /*builder*/ ) {
  22885. if ( this.nodeType === null ) {
  22886. return getValueType( this.value );
  22887. }
  22888. return this.nodeType;
  22889. }
  22890. getInputType( builder ) {
  22891. return this.getNodeType( builder );
  22892. }
  22893. setPrecision( precision ) {
  22894. this.precision = precision;
  22895. return this;
  22896. }
  22897. serialize( data ) {
  22898. super.serialize( data );
  22899. data.value = this.value;
  22900. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22901. data.valueType = getValueType( this.value );
  22902. data.nodeType = this.nodeType;
  22903. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22904. data.precision = this.precision;
  22905. }
  22906. deserialize( data ) {
  22907. super.deserialize( data );
  22908. this.nodeType = data.nodeType;
  22909. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22910. this.precision = data.precision || null;
  22911. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22912. }
  22913. generate( /*builder, output*/ ) {
  22914. console.warn( 'Abstract function.' );
  22915. }
  22916. }
  22917. addNodeClass( 'InputNode', InputNode );
  22918. class ConstNode extends InputNode {
  22919. constructor( value, nodeType = null ) {
  22920. super( value, nodeType );
  22921. this.isConstNode = true;
  22922. }
  22923. generateConst( builder ) {
  22924. return builder.generateConst( this.getNodeType( builder ), this.value );
  22925. }
  22926. generate( builder, output ) {
  22927. const type = this.getNodeType( builder );
  22928. return builder.format( this.generateConst( builder ), type, output );
  22929. }
  22930. }
  22931. addNodeClass( 'ConstNode', ConstNode );
  22932. //
  22933. let currentStack = null;
  22934. const NodeElements = new Map(); // @TODO: Currently only a few nodes are added, probably also add others
  22935. function addNodeElement( name, nodeElement ) {
  22936. if ( NodeElements.has( name ) ) {
  22937. console.warn( `Redefinition of node element ${ name }` );
  22938. return;
  22939. }
  22940. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22941. NodeElements.set( name, nodeElement );
  22942. }
  22943. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22944. const shaderNodeHandler = {
  22945. setup( NodeClosure, params ) {
  22946. const inputs = params.shift();
  22947. return NodeClosure( nodeObjects( inputs ), ...params );
  22948. },
  22949. get( node, prop, nodeObj ) {
  22950. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22951. if ( node.isStackNode !== true && prop === 'assign' ) {
  22952. return ( ...params ) => {
  22953. currentStack.assign( nodeObj, ...params );
  22954. return nodeObj;
  22955. };
  22956. } else if ( NodeElements.has( prop ) ) {
  22957. const nodeElement = NodeElements.get( prop );
  22958. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22959. } else if ( prop === 'self' ) {
  22960. return node;
  22961. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22962. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22963. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22964. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22965. // accessing properties ( swizzle )
  22966. prop = parseSwizzle( prop );
  22967. return nodeObject( new SplitNode( nodeObj, prop ) );
  22968. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22969. // set properties ( swizzle )
  22970. prop = parseSwizzle( prop.slice( 3 ).toLowerCase() );
  22971. // sort to xyzw sequence
  22972. prop = prop.split( '' ).sort().join( '' );
  22973. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22974. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22975. // accessing property
  22976. if ( prop === 'width' ) prop = 'x';
  22977. else if ( prop === 'height' ) prop = 'y';
  22978. else if ( prop === 'depth' ) prop = 'z';
  22979. return nodeObject( new SplitNode( node, prop ) );
  22980. } else if ( /^\d+$/.test( prop ) === true ) {
  22981. // accessing array
  22982. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22983. }
  22984. }
  22985. return Reflect.get( node, prop, nodeObj );
  22986. },
  22987. set( node, prop, value, nodeObj ) {
  22988. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22989. // setting properties
  22990. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22991. nodeObj[ prop ].assign( value );
  22992. return true;
  22993. }
  22994. }
  22995. return Reflect.set( node, prop, value, nodeObj );
  22996. }
  22997. };
  22998. const nodeObjectsCacheMap = new WeakMap();
  22999. const nodeBuilderFunctionsCacheMap = new WeakMap();
  23000. const ShaderNodeObject = function ( obj, altType = null ) {
  23001. const type = getValueType( obj );
  23002. if ( type === 'node' ) {
  23003. let nodeObject = nodeObjectsCacheMap.get( obj );
  23004. if ( nodeObject === undefined ) {
  23005. nodeObject = new Proxy( obj, shaderNodeHandler );
  23006. nodeObjectsCacheMap.set( obj, nodeObject );
  23007. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  23008. }
  23009. return nodeObject;
  23010. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  23011. return nodeObject( getConstNode( obj, altType ) );
  23012. } else if ( type === 'shader' ) {
  23013. return tslFn( obj );
  23014. }
  23015. return obj;
  23016. };
  23017. const ShaderNodeObjects = function ( objects, altType = null ) {
  23018. for ( const name in objects ) {
  23019. objects[ name ] = nodeObject( objects[ name ], altType );
  23020. }
  23021. return objects;
  23022. };
  23023. const ShaderNodeArray = function ( array, altType = null ) {
  23024. const len = array.length;
  23025. for ( let i = 0; i < len; i ++ ) {
  23026. array[ i ] = nodeObject( array[ i ], altType );
  23027. }
  23028. return array;
  23029. };
  23030. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  23031. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  23032. if ( scope === null ) {
  23033. return ( ...params ) => {
  23034. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  23035. };
  23036. } else if ( factor !== null ) {
  23037. factor = nodeObject( factor );
  23038. return ( ...params ) => {
  23039. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  23040. };
  23041. } else {
  23042. return ( ...params ) => {
  23043. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  23044. };
  23045. }
  23046. };
  23047. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  23048. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  23049. };
  23050. class ShaderCallNodeInternal extends Node {
  23051. constructor( shaderNode, inputNodes ) {
  23052. super();
  23053. this.shaderNode = shaderNode;
  23054. this.inputNodes = inputNodes;
  23055. }
  23056. getNodeType( builder ) {
  23057. const properties = builder.getNodeProperties( this );
  23058. if ( properties.outputNode === null ) {
  23059. properties.outputNode = this.setupOutput( builder );
  23060. }
  23061. return properties.outputNode.getNodeType( builder );
  23062. }
  23063. call( builder ) {
  23064. const { shaderNode, inputNodes } = this;
  23065. if ( shaderNode.layout ) {
  23066. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  23067. if ( functionNodesCacheMap === undefined ) {
  23068. functionNodesCacheMap = new WeakMap();
  23069. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  23070. }
  23071. let functionNode = functionNodesCacheMap.get( shaderNode );
  23072. if ( functionNode === undefined ) {
  23073. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  23074. functionNodesCacheMap.set( shaderNode, functionNode );
  23075. }
  23076. if ( builder.currentFunctionNode !== null ) {
  23077. builder.currentFunctionNode.includes.push( functionNode );
  23078. }
  23079. return nodeObject( functionNode.call( inputNodes ) );
  23080. }
  23081. const jsFunc = shaderNode.jsFunc;
  23082. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder.stack, builder ) : jsFunc( builder.stack, builder );
  23083. return nodeObject( outputNode );
  23084. }
  23085. setup( builder ) {
  23086. const { outputNode } = builder.getNodeProperties( this );
  23087. return outputNode || this.setupOutput( builder );
  23088. }
  23089. setupOutput( builder ) {
  23090. builder.addStack();
  23091. builder.stack.outputNode = this.call( builder );
  23092. return builder.removeStack();
  23093. }
  23094. generate( builder, output ) {
  23095. const { outputNode } = builder.getNodeProperties( this );
  23096. if ( outputNode === null ) {
  23097. // TSL: It's recommended to use `tslFn` in setup() pass.
  23098. return this.call( builder ).build( builder, output );
  23099. }
  23100. return super.generate( builder, output );
  23101. }
  23102. }
  23103. class ShaderNodeInternal extends Node {
  23104. constructor( jsFunc ) {
  23105. super();
  23106. this.jsFunc = jsFunc;
  23107. this.layout = null;
  23108. this.global = true;
  23109. }
  23110. get isArrayInput() {
  23111. return /^\((\s+)?\[/.test( this.jsFunc.toString() );
  23112. }
  23113. setLayout( layout ) {
  23114. this.layout = layout;
  23115. return this;
  23116. }
  23117. call( inputs = null ) {
  23118. nodeObjects( inputs );
  23119. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  23120. }
  23121. setup() {
  23122. return this.call();
  23123. }
  23124. }
  23125. const bools = [ false, true ];
  23126. const uints = [ 0, 1, 2, 3 ];
  23127. const ints = [ - 1, - 2 ];
  23128. 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 ];
  23129. const boolsCacheMap = new Map();
  23130. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  23131. const uintsCacheMap = new Map();
  23132. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  23133. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  23134. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  23135. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  23136. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  23137. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  23138. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  23139. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  23140. const getConstNode = ( value, type ) => {
  23141. if ( constNodesCacheMap.has( value ) ) {
  23142. return constNodesCacheMap.get( value );
  23143. } else if ( value.isNode === true ) {
  23144. return value;
  23145. } else {
  23146. return new ConstNode( value, type );
  23147. }
  23148. };
  23149. const safeGetNodeType = ( node ) => {
  23150. try {
  23151. return node.getNodeType();
  23152. } catch ( _ ) {
  23153. return undefined;
  23154. }
  23155. };
  23156. const ConvertType = function ( type, cacheMap = null ) {
  23157. return ( ...params ) => {
  23158. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  23159. params = [ getValueFromType( type, ...params ) ];
  23160. }
  23161. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  23162. return nodeObject( cacheMap.get( params[ 0 ] ) );
  23163. }
  23164. if ( params.length === 1 ) {
  23165. const node = getConstNode( params[ 0 ], type );
  23166. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  23167. return nodeObject( new ConvertNode( node, type ) );
  23168. }
  23169. const nodes = params.map( param => getConstNode( param ) );
  23170. return nodeObject( new JoinNode( nodes, type ) );
  23171. };
  23172. };
  23173. // exports
  23174. const defined = ( value ) => value && value.value;
  23175. // utils
  23176. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  23177. // shader node base
  23178. function ShaderNode( jsFunc ) {
  23179. return new Proxy( new ShaderNodeInternal( jsFunc ), shaderNodeHandler );
  23180. }
  23181. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  23182. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  23183. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  23184. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  23185. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  23186. const tslFn = ( jsFunc ) => {
  23187. const shaderNode = new ShaderNode( jsFunc );
  23188. const fn = ( ...params ) => {
  23189. let inputs;
  23190. nodeObjects( params );
  23191. if ( params[ 0 ] && params[ 0 ].isNode ) {
  23192. inputs = [ ...params ];
  23193. } else {
  23194. inputs = params[ 0 ];
  23195. }
  23196. return shaderNode.call( inputs );
  23197. };
  23198. fn.shaderNode = shaderNode;
  23199. fn.setLayout = ( layout ) => {
  23200. shaderNode.setLayout( layout );
  23201. return fn;
  23202. };
  23203. return fn;
  23204. };
  23205. addNodeClass( 'ShaderNode', ShaderNode );
  23206. //
  23207. addNodeElement( 'toGlobal', ( node ) => {
  23208. node.global = true;
  23209. return node;
  23210. } );
  23211. //
  23212. const setCurrentStack = ( stack ) => {
  23213. currentStack = stack;
  23214. };
  23215. const getCurrentStack = () => currentStack;
  23216. const If = ( ...params ) => currentStack.if( ...params );
  23217. function append( node ) {
  23218. if ( currentStack ) currentStack.add( node );
  23219. return node;
  23220. }
  23221. addNodeElement( 'append', append );
  23222. // types
  23223. // @TODO: Maybe export from ConstNode.js?
  23224. const color = new ConvertType( 'color' );
  23225. const float = new ConvertType( 'float', cacheMaps.float );
  23226. const int = new ConvertType( 'int', cacheMaps.ints );
  23227. const uint = new ConvertType( 'uint', cacheMaps.uint );
  23228. const bool = new ConvertType( 'bool', cacheMaps.bool );
  23229. const vec2 = new ConvertType( 'vec2' );
  23230. const ivec2 = new ConvertType( 'ivec2' );
  23231. const uvec2 = new ConvertType( 'uvec2' );
  23232. const bvec2 = new ConvertType( 'bvec2' );
  23233. const vec3 = new ConvertType( 'vec3' );
  23234. const ivec3 = new ConvertType( 'ivec3' );
  23235. const uvec3 = new ConvertType( 'uvec3' );
  23236. const bvec3 = new ConvertType( 'bvec3' );
  23237. const vec4 = new ConvertType( 'vec4' );
  23238. const ivec4 = new ConvertType( 'ivec4' );
  23239. const uvec4 = new ConvertType( 'uvec4' );
  23240. const bvec4 = new ConvertType( 'bvec4' );
  23241. const mat2 = new ConvertType( 'mat2' );
  23242. const imat2 = new ConvertType( 'imat2' );
  23243. const umat2 = new ConvertType( 'umat2' );
  23244. const bmat2 = new ConvertType( 'bmat2' );
  23245. const mat3 = new ConvertType( 'mat3' );
  23246. const imat3 = new ConvertType( 'imat3' );
  23247. const umat3 = new ConvertType( 'umat3' );
  23248. const bmat3 = new ConvertType( 'bmat3' );
  23249. const mat4 = new ConvertType( 'mat4' );
  23250. const imat4 = new ConvertType( 'imat4' );
  23251. const umat4 = new ConvertType( 'umat4' );
  23252. const bmat4 = new ConvertType( 'bmat4' );
  23253. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  23254. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  23255. addNodeElement( 'toColor', color );
  23256. addNodeElement( 'toFloat', float );
  23257. addNodeElement( 'toInt', int );
  23258. addNodeElement( 'toUint', uint );
  23259. addNodeElement( 'toBool', bool );
  23260. addNodeElement( 'toVec2', vec2 );
  23261. addNodeElement( 'toIvec2', ivec2 );
  23262. addNodeElement( 'toUvec2', uvec2 );
  23263. addNodeElement( 'toBvec2', bvec2 );
  23264. addNodeElement( 'toVec3', vec3 );
  23265. addNodeElement( 'toIvec3', ivec3 );
  23266. addNodeElement( 'toUvec3', uvec3 );
  23267. addNodeElement( 'toBvec3', bvec3 );
  23268. addNodeElement( 'toVec4', vec4 );
  23269. addNodeElement( 'toIvec4', ivec4 );
  23270. addNodeElement( 'toUvec4', uvec4 );
  23271. addNodeElement( 'toBvec4', bvec4 );
  23272. addNodeElement( 'toMat2', mat2 );
  23273. addNodeElement( 'toImat2', imat2 );
  23274. addNodeElement( 'toUmat2', umat2 );
  23275. addNodeElement( 'toBmat2', bmat2 );
  23276. addNodeElement( 'toMat3', mat3 );
  23277. addNodeElement( 'toImat3', imat3 );
  23278. addNodeElement( 'toUmat3', umat3 );
  23279. addNodeElement( 'toBmat3', bmat3 );
  23280. addNodeElement( 'toMat4', mat4 );
  23281. addNodeElement( 'toImat4', imat4 );
  23282. addNodeElement( 'toUmat4', umat4 );
  23283. addNodeElement( 'toBmat4', bmat4 );
  23284. // basic nodes
  23285. // HACK - we cannot export them from the corresponding files because of the cyclic dependency
  23286. const element = nodeProxy( ArrayElementNode );
  23287. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  23288. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  23289. addNodeElement( 'element', element );
  23290. addNodeElement( 'convert', convert );
  23291. class AssignNode extends TempNode {
  23292. constructor( targetNode, sourceNode ) {
  23293. super();
  23294. this.targetNode = targetNode;
  23295. this.sourceNode = sourceNode;
  23296. }
  23297. hasDependencies() {
  23298. return false;
  23299. }
  23300. getNodeType( builder, output ) {
  23301. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23302. }
  23303. needsSplitAssign( builder ) {
  23304. const { targetNode } = this;
  23305. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23306. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23307. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23308. return assignDiferentVector;
  23309. }
  23310. return false;
  23311. }
  23312. generate( builder, output ) {
  23313. const { targetNode, sourceNode } = this;
  23314. const needsSplitAssign = this.needsSplitAssign( builder );
  23315. const targetType = targetNode.getNodeType( builder );
  23316. const target = targetNode.context( { assign: true } ).build( builder );
  23317. const source = sourceNode.build( builder, targetType );
  23318. const sourceType = sourceNode.getNodeType( builder );
  23319. const nodeData = builder.getDataFromNode( this );
  23320. //
  23321. let snippet;
  23322. if ( nodeData.initialized === true ) {
  23323. if ( output !== 'void' ) {
  23324. snippet = target;
  23325. }
  23326. } else if ( needsSplitAssign ) {
  23327. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23328. const sourceProperty = builder.getPropertyName( sourceVar );
  23329. builder.addLineFlowCode( `${ sourceProperty } = ${ source }` );
  23330. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23331. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23332. const component = targetNode.components[ i ];
  23333. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` );
  23334. }
  23335. if ( output !== 'void' ) {
  23336. snippet = target;
  23337. }
  23338. } else {
  23339. snippet = `${ target } = ${ source }`;
  23340. if ( output === 'void' || sourceType === 'void' ) {
  23341. builder.addLineFlowCode( snippet );
  23342. if ( output !== 'void' ) {
  23343. snippet = target;
  23344. }
  23345. }
  23346. }
  23347. nodeData.initialized = true;
  23348. return builder.format( snippet, targetType, output );
  23349. }
  23350. }
  23351. const assign = nodeProxy( AssignNode );
  23352. addNodeClass( 'AssignNode', AssignNode );
  23353. addNodeElement( 'assign', assign );
  23354. class VaryingNode extends Node {
  23355. constructor( node, name = null ) {
  23356. super();
  23357. this.node = node;
  23358. this.name = name;
  23359. this.isVaryingNode = true;
  23360. }
  23361. isGlobal() {
  23362. return true;
  23363. }
  23364. getHash( builder ) {
  23365. return this.name || super.getHash( builder );
  23366. }
  23367. getNodeType( builder ) {
  23368. // VaryingNode is auto type
  23369. return this.node.getNodeType( builder );
  23370. }
  23371. setupVarying( builder ) {
  23372. const properties = builder.getNodeProperties( this );
  23373. let varying = properties.varying;
  23374. if ( varying === undefined ) {
  23375. const name = this.name;
  23376. const type = this.getNodeType( builder );
  23377. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23378. properties.node = this.node;
  23379. }
  23380. // this property can be used to check if the varying can be optimized for a variable
  23381. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23382. return varying;
  23383. }
  23384. setup( builder ) {
  23385. this.setupVarying( builder );
  23386. }
  23387. analyze( builder ) {
  23388. this.setupVarying( builder );
  23389. return this.node.analyze( builder );
  23390. }
  23391. generate( builder ) {
  23392. const properties = builder.getNodeProperties( this );
  23393. const varying = this.setupVarying( builder );
  23394. if ( properties.propertyName === undefined ) {
  23395. const type = this.getNodeType( builder );
  23396. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23397. // force node run in vertex stage
  23398. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23399. properties.propertyName = propertyName;
  23400. }
  23401. return builder.getPropertyName( varying );
  23402. }
  23403. }
  23404. const varying = nodeProxy( VaryingNode );
  23405. addNodeElement( 'varying', varying );
  23406. addNodeClass( 'VaryingNode', VaryingNode );
  23407. class AttributeNode extends Node {
  23408. constructor( attributeName, nodeType = null, defaultNode = null ) {
  23409. super( nodeType );
  23410. this.defaultNode = defaultNode;
  23411. this.global = true;
  23412. this._attributeName = attributeName;
  23413. }
  23414. getHash( builder ) {
  23415. return this.getAttributeName( builder );
  23416. }
  23417. getNodeType( builder ) {
  23418. let nodeType = super.getNodeType( builder );
  23419. if ( nodeType === null ) {
  23420. const attributeName = this.getAttributeName( builder );
  23421. if ( builder.hasGeometryAttribute( attributeName ) ) {
  23422. const attribute = builder.geometry.getAttribute( attributeName );
  23423. nodeType = builder.getTypeFromAttribute( attribute );
  23424. } else {
  23425. nodeType = 'float';
  23426. }
  23427. }
  23428. return nodeType;
  23429. }
  23430. setAttributeName( attributeName ) {
  23431. this._attributeName = attributeName;
  23432. return this;
  23433. }
  23434. getAttributeName( /*builder*/ ) {
  23435. return this._attributeName;
  23436. }
  23437. generate( builder ) {
  23438. const attributeName = this.getAttributeName( builder );
  23439. const nodeType = this.getNodeType( builder );
  23440. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  23441. if ( geometryAttribute === true ) {
  23442. const attribute = builder.geometry.getAttribute( attributeName );
  23443. const attributeType = builder.getTypeFromAttribute( attribute );
  23444. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  23445. if ( builder.shaderStage === 'vertex' ) {
  23446. return builder.format( nodeAttribute.name, attributeType, nodeType );
  23447. } else {
  23448. const nodeVarying = varying( this );
  23449. return nodeVarying.build( builder, nodeType );
  23450. }
  23451. } else {
  23452. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  23453. const { defaultNode } = this;
  23454. if ( defaultNode !== null ) {
  23455. return defaultNode.build( builder, nodeType );
  23456. } else {
  23457. return builder.generateConst( nodeType );
  23458. }
  23459. }
  23460. }
  23461. }
  23462. const attribute = ( name, nodeType, defaultNode ) => nodeObject( new AttributeNode( name, nodeType, nodeObject( defaultNode ) ) );
  23463. addNodeClass( 'AttributeNode', AttributeNode );
  23464. class BypassNode extends Node {
  23465. constructor( returnNode, callNode ) {
  23466. super();
  23467. this.isBypassNode = true;
  23468. this.outputNode = returnNode;
  23469. this.callNode = callNode;
  23470. }
  23471. getNodeType( builder ) {
  23472. return this.outputNode.getNodeType( builder );
  23473. }
  23474. generate( builder ) {
  23475. const snippet = this.callNode.build( builder, 'void' );
  23476. if ( snippet !== '' ) {
  23477. builder.addLineFlowCode( snippet );
  23478. }
  23479. return this.outputNode.build( builder );
  23480. }
  23481. }
  23482. const bypass = nodeProxy( BypassNode );
  23483. addNodeElement( 'bypass', bypass );
  23484. addNodeClass( 'BypassNode', BypassNode );
  23485. class CacheNode extends Node {
  23486. constructor( node, parent = true ) {
  23487. super();
  23488. this.node = node;
  23489. this.parent = parent;
  23490. this.isCacheNode = true;
  23491. }
  23492. getNodeType( builder ) {
  23493. return this.node.getNodeType( builder );
  23494. }
  23495. build( builder, ...params ) {
  23496. const previousCache = builder.getCache();
  23497. const cache = builder.getCacheFromNode( this, parent );
  23498. builder.setCache( cache );
  23499. const data = this.node.build( builder, ...params );
  23500. builder.setCache( previousCache );
  23501. return data;
  23502. }
  23503. }
  23504. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23505. addNodeElement( 'cache', cache );
  23506. addNodeClass( 'CacheNode', CacheNode );
  23507. class ContextNode extends Node {
  23508. constructor( node, context = {} ) {
  23509. super();
  23510. this.isContextNode = true;
  23511. this.node = node;
  23512. this.context = context;
  23513. }
  23514. getNodeType( builder ) {
  23515. return this.node.getNodeType( builder );
  23516. }
  23517. analyze( builder ) {
  23518. this.node.build( builder );
  23519. }
  23520. setup( builder ) {
  23521. const previousContext = builder.getContext();
  23522. builder.setContext( { ...builder.context, ...this.context } );
  23523. const node = this.node.build( builder );
  23524. builder.setContext( previousContext );
  23525. return node;
  23526. }
  23527. generate( builder, output ) {
  23528. const previousContext = builder.getContext();
  23529. builder.setContext( { ...builder.context, ...this.context } );
  23530. const snippet = this.node.build( builder, output );
  23531. builder.setContext( previousContext );
  23532. return snippet;
  23533. }
  23534. }
  23535. const context = nodeProxy( ContextNode );
  23536. const label = ( node, name ) => context( node, { label: name } );
  23537. addNodeElement( 'context', context );
  23538. addNodeElement( 'label', label );
  23539. addNodeClass( 'ContextNode', ContextNode );
  23540. class IndexNode extends Node {
  23541. constructor( scope ) {
  23542. super( 'uint' );
  23543. this.scope = scope;
  23544. this.isInstanceIndexNode = true;
  23545. }
  23546. generate( builder ) {
  23547. const nodeType = this.getNodeType( builder );
  23548. const scope = this.scope;
  23549. let propertyName;
  23550. if ( scope === IndexNode.VERTEX ) {
  23551. propertyName = builder.getVertexIndex();
  23552. } else if ( scope === IndexNode.INSTANCE ) {
  23553. propertyName = builder.getInstanceIndex();
  23554. } else if ( scope === IndexNode.DRAW ) {
  23555. propertyName = builder.getDrawIndex();
  23556. } else {
  23557. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  23558. }
  23559. let output;
  23560. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23561. output = propertyName;
  23562. } else {
  23563. const nodeVarying = varying( this );
  23564. output = nodeVarying.build( builder, nodeType );
  23565. }
  23566. return output;
  23567. }
  23568. }
  23569. IndexNode.VERTEX = 'vertex';
  23570. IndexNode.INSTANCE = 'instance';
  23571. IndexNode.DRAW = 'draw';
  23572. const vertexIndex = nodeImmutable( IndexNode, IndexNode.VERTEX );
  23573. const instanceIndex = nodeImmutable( IndexNode, IndexNode.INSTANCE );
  23574. const drawIndex = nodeImmutable( IndexNode, IndexNode.DRAW );
  23575. addNodeClass( 'IndexNode', IndexNode );
  23576. class LightingModel {
  23577. start( /*input, stack, builder*/ ) { }
  23578. finish( /*input, stack, builder*/ ) { }
  23579. direct( /*input, stack, builder*/ ) { }
  23580. directRectArea( /*input, stack, builder*/ ) {}
  23581. indirectDiffuse( /*input, stack, builder*/ ) { }
  23582. indirectSpecular( /*input, stack, builder*/ ) { }
  23583. ambientOcclusion( /*input, stack, builder*/ ) { }
  23584. }
  23585. class VarNode extends Node {
  23586. constructor( node, name = null ) {
  23587. super();
  23588. this.node = node;
  23589. this.name = name;
  23590. this.global = true;
  23591. this.isVarNode = true;
  23592. }
  23593. getHash( builder ) {
  23594. return this.name || super.getHash( builder );
  23595. }
  23596. getNodeType( builder ) {
  23597. return this.node.getNodeType( builder );
  23598. }
  23599. generate( builder ) {
  23600. const { node, name } = this;
  23601. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23602. const propertyName = builder.getPropertyName( nodeVar );
  23603. const snippet = node.build( builder, nodeVar.type );
  23604. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  23605. return propertyName;
  23606. }
  23607. }
  23608. const temp = nodeProxy( VarNode );
  23609. addNodeElement( 'temp', temp ); // @TODO: Will be removed in the future
  23610. addNodeElement( 'toVar', ( ...params ) => temp( ...params ).append() );
  23611. addNodeClass( 'VarNode', VarNode );
  23612. class NodeAttribute {
  23613. constructor( name, type, node = null ) {
  23614. this.isNodeAttribute = true;
  23615. this.name = name;
  23616. this.type = type;
  23617. this.node = node;
  23618. }
  23619. }
  23620. class NodeUniform {
  23621. constructor( name, type, node ) {
  23622. this.isNodeUniform = true;
  23623. this.name = name;
  23624. this.type = type;
  23625. this.node = node.getSelf();
  23626. }
  23627. get value() {
  23628. return this.node.value;
  23629. }
  23630. set value( val ) {
  23631. this.node.value = val;
  23632. }
  23633. get id() {
  23634. return this.node.id;
  23635. }
  23636. get groupNode() {
  23637. return this.node.groupNode;
  23638. }
  23639. }
  23640. class NodeVar {
  23641. constructor( name, type ) {
  23642. this.isNodeVar = true;
  23643. this.name = name;
  23644. this.type = type;
  23645. }
  23646. }
  23647. class NodeVarying extends NodeVar {
  23648. constructor( name, type ) {
  23649. super( name, type );
  23650. this.needsInterpolation = false;
  23651. this.isNodeVarying = true;
  23652. }
  23653. }
  23654. class NodeCode {
  23655. constructor( name, type, code = '' ) {
  23656. this.name = name;
  23657. this.type = type;
  23658. this.code = code;
  23659. Object.defineProperty( this, 'isNodeCode', { value: true } );
  23660. }
  23661. }
  23662. class NodeKeywords {
  23663. constructor() {
  23664. this.keywords = [];
  23665. this.nodes = {};
  23666. this.keywordsCallback = {};
  23667. }
  23668. getNode( name ) {
  23669. let node = this.nodes[ name ];
  23670. if ( node === undefined && this.keywordsCallback[ name ] !== undefined ) {
  23671. node = this.keywordsCallback[ name ]( name );
  23672. this.nodes[ name ] = node;
  23673. }
  23674. return node;
  23675. }
  23676. addKeyword( name, callback ) {
  23677. this.keywords.push( name );
  23678. this.keywordsCallback[ name ] = callback;
  23679. return this;
  23680. }
  23681. parse( code ) {
  23682. const keywordNames = this.keywords;
  23683. const regExp = new RegExp( `\\b${keywordNames.join( '\\b|\\b' )}\\b`, 'g' );
  23684. const codeKeywords = code.match( regExp );
  23685. const keywordNodes = [];
  23686. if ( codeKeywords !== null ) {
  23687. for ( const keyword of codeKeywords ) {
  23688. const node = this.getNode( keyword );
  23689. if ( node !== undefined && keywordNodes.indexOf( node ) === - 1 ) {
  23690. keywordNodes.push( node );
  23691. }
  23692. }
  23693. }
  23694. return keywordNodes;
  23695. }
  23696. include( builder, code ) {
  23697. const keywordNodes = this.parse( code );
  23698. for ( const keywordNode of keywordNodes ) {
  23699. keywordNode.build( builder );
  23700. }
  23701. }
  23702. }
  23703. let id$3 = 0;
  23704. class NodeCache {
  23705. constructor( parent = null ) {
  23706. this.id = id$3 ++;
  23707. this.nodesData = new WeakMap();
  23708. this.parent = parent;
  23709. }
  23710. getData( node ) {
  23711. let data = this.nodesData.get( node );
  23712. if ( data === undefined && this.parent !== null ) {
  23713. data = this.parent.getData( node );
  23714. }
  23715. return data;
  23716. }
  23717. setData( node, data ) {
  23718. this.nodesData.set( node, data );
  23719. }
  23720. }
  23721. class PropertyNode extends Node {
  23722. constructor( nodeType, name = null, varying = false ) {
  23723. super( nodeType );
  23724. this.name = name;
  23725. this.varying = varying;
  23726. this.isPropertyNode = true;
  23727. }
  23728. getHash( builder ) {
  23729. return this.name || super.getHash( builder );
  23730. }
  23731. isGlobal( /*builder*/ ) {
  23732. return true;
  23733. }
  23734. generate( builder ) {
  23735. let nodeVar;
  23736. if ( this.varying === true ) {
  23737. nodeVar = builder.getVaryingFromNode( this, this.name );
  23738. nodeVar.needsInterpolation = true;
  23739. } else {
  23740. nodeVar = builder.getVarFromNode( this, this.name );
  23741. }
  23742. return builder.getPropertyName( nodeVar );
  23743. }
  23744. }
  23745. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23746. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23747. const diffuseColor = nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23748. const roughness = nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23749. const metalness = nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23750. const clearcoat = nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23751. const clearcoatRoughness = nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23752. const sheen = nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23753. const sheenRoughness = nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23754. const iridescence = nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23755. const iridescenceIOR = nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23756. const iridescenceThickness = nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23757. const alphaT = nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23758. const anisotropy = nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23759. const anisotropyT = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23760. const anisotropyB = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23761. const specularColor = nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23762. const specularF90 = nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23763. const shininess = nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23764. const output = nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23765. const dashSize = nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23766. const gapSize = nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23767. const pointWidth = nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23768. const ior = nodeImmutable( PropertyNode, 'float', 'IOR' );
  23769. const transmission = nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23770. const thickness = nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23771. const attenuationDistance = nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23772. const attenuationColor = nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23773. const dispersion = nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23774. addNodeClass( 'PropertyNode', PropertyNode );
  23775. class ParameterNode extends PropertyNode {
  23776. constructor( nodeType, name = null ) {
  23777. super( nodeType, name );
  23778. this.isParameterNode = true;
  23779. }
  23780. getHash() {
  23781. return this.uuid;
  23782. }
  23783. generate() {
  23784. return this.name;
  23785. }
  23786. }
  23787. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23788. addNodeClass( 'ParameterNode', ParameterNode );
  23789. class CodeNode extends Node {
  23790. constructor( code = '', includes = [], language = '' ) {
  23791. super( 'code' );
  23792. this.isCodeNode = true;
  23793. this.code = code;
  23794. this.language = language;
  23795. this.includes = includes;
  23796. }
  23797. isGlobal() {
  23798. return true;
  23799. }
  23800. setIncludes( includes ) {
  23801. this.includes = includes;
  23802. return this;
  23803. }
  23804. getIncludes( /*builder*/ ) {
  23805. return this.includes;
  23806. }
  23807. generate( builder ) {
  23808. const includes = this.getIncludes( builder );
  23809. for ( const include of includes ) {
  23810. include.build( builder );
  23811. }
  23812. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23813. nodeCode.code = this.code;
  23814. return nodeCode.code;
  23815. }
  23816. serialize( data ) {
  23817. super.serialize( data );
  23818. data.code = this.code;
  23819. data.language = this.language;
  23820. }
  23821. deserialize( data ) {
  23822. super.deserialize( data );
  23823. this.code = data.code;
  23824. this.language = data.language;
  23825. }
  23826. }
  23827. const code = nodeProxy( CodeNode );
  23828. const js = ( src, includes ) => code( src, includes, 'js' );
  23829. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23830. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23831. addNodeClass( 'CodeNode', CodeNode );
  23832. class FunctionNode extends CodeNode {
  23833. constructor( code = '', includes = [], language = '' ) {
  23834. super( code, includes, language );
  23835. this.keywords = {};
  23836. }
  23837. getNodeType( builder ) {
  23838. return this.getNodeFunction( builder ).type;
  23839. }
  23840. getInputs( builder ) {
  23841. return this.getNodeFunction( builder ).inputs;
  23842. }
  23843. getNodeFunction( builder ) {
  23844. const nodeData = builder.getDataFromNode( this );
  23845. let nodeFunction = nodeData.nodeFunction;
  23846. if ( nodeFunction === undefined ) {
  23847. nodeFunction = builder.parser.parseFunction( this.code );
  23848. nodeData.nodeFunction = nodeFunction;
  23849. }
  23850. return nodeFunction;
  23851. }
  23852. generate( builder, output ) {
  23853. super.generate( builder );
  23854. const nodeFunction = this.getNodeFunction( builder );
  23855. const name = nodeFunction.name;
  23856. const type = nodeFunction.type;
  23857. const nodeCode = builder.getCodeFromNode( this, type );
  23858. if ( name !== '' ) {
  23859. // use a custom property name
  23860. nodeCode.name = name;
  23861. }
  23862. const propertyName = builder.getPropertyName( nodeCode );
  23863. let code = this.getNodeFunction( builder ).getCode( propertyName );
  23864. const keywords = this.keywords;
  23865. const keywordsProperties = Object.keys( keywords );
  23866. if ( keywordsProperties.length > 0 ) {
  23867. for ( const property of keywordsProperties ) {
  23868. const propertyRegExp = new RegExp( `\\b${property}\\b`, 'g' );
  23869. const nodeProperty = keywords[ property ].build( builder, 'property' );
  23870. code = code.replace( propertyRegExp, nodeProperty );
  23871. }
  23872. }
  23873. nodeCode.code = code + '\n';
  23874. if ( output === 'property' ) {
  23875. return propertyName;
  23876. } else {
  23877. return builder.format( `${ propertyName }()`, type, output );
  23878. }
  23879. }
  23880. }
  23881. const nativeFn = ( code, includes = [], language = '' ) => {
  23882. for ( let i = 0; i < includes.length; i ++ ) {
  23883. const include = includes[ i ];
  23884. // TSL Function: glslFn, wgslFn
  23885. if ( typeof include === 'function' ) {
  23886. includes[ i ] = include.functionNode;
  23887. }
  23888. }
  23889. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23890. const fn = ( ...params ) => functionNode.call( ...params );
  23891. fn.functionNode = functionNode;
  23892. return fn;
  23893. };
  23894. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23895. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23896. addNodeClass( 'FunctionNode', FunctionNode );
  23897. class UniformGroupNode extends Node {
  23898. constructor( name, shared = false ) {
  23899. super( 'string' );
  23900. this.name = name;
  23901. this.version = 0;
  23902. this.shared = shared;
  23903. this.isUniformGroup = true;
  23904. }
  23905. set needsUpdate( value ) {
  23906. if ( value === true ) this.version ++;
  23907. }
  23908. }
  23909. const uniformGroup = ( name ) => new UniformGroupNode( name );
  23910. const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true );
  23911. const frameGroup = sharedUniformGroup( 'frame' );
  23912. const renderGroup = sharedUniformGroup( 'render' );
  23913. const objectGroup = uniformGroup( 'object' );
  23914. addNodeClass( 'UniformGroupNode', UniformGroupNode );
  23915. class UniformNode extends InputNode {
  23916. constructor( value, nodeType = null ) {
  23917. super( value, nodeType );
  23918. this.isUniformNode = true;
  23919. this.name = '';
  23920. this.groupNode = objectGroup;
  23921. }
  23922. label( name ) {
  23923. this.name = name;
  23924. return this;
  23925. }
  23926. setGroup( group ) {
  23927. this.groupNode = group;
  23928. return this;
  23929. }
  23930. getGroup() {
  23931. return this.groupNode;
  23932. }
  23933. getUniformHash( builder ) {
  23934. return this.getHash( builder );
  23935. }
  23936. onUpdate( callback, updateType ) {
  23937. const self = this.getSelf();
  23938. callback = callback.bind( self );
  23939. return super.onUpdate( ( frame ) => {
  23940. const value = callback( frame, self );
  23941. if ( value !== undefined ) {
  23942. this.value = value;
  23943. }
  23944. }, updateType );
  23945. }
  23946. generate( builder, output ) {
  23947. const type = this.getNodeType( builder );
  23948. const hash = this.getUniformHash( builder );
  23949. let sharedNode = builder.getNodeFromHash( hash );
  23950. if ( sharedNode === undefined ) {
  23951. builder.setHashNode( this, hash );
  23952. sharedNode = this;
  23953. }
  23954. const sharedNodeType = sharedNode.getInputType( builder );
  23955. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  23956. const propertyName = builder.getPropertyName( nodeUniform );
  23957. if ( builder.context.label !== undefined ) delete builder.context.label;
  23958. return builder.format( propertyName, type, output );
  23959. }
  23960. }
  23961. const uniform = ( arg1, arg2 ) => {
  23962. const nodeType = getConstNodeType( arg2 || arg1 );
  23963. // @TODO: get ConstNode from .traverse() in the future
  23964. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  23965. return nodeObject( new UniformNode( value, nodeType ) );
  23966. };
  23967. addNodeClass( 'UniformNode', UniformNode );
  23968. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  23969. class TextureSizeNode extends Node {
  23970. constructor( textureNode, levelNode = null ) {
  23971. super( 'uvec2' );
  23972. this.isTextureSizeNode = true;
  23973. this.textureNode = textureNode;
  23974. this.levelNode = levelNode;
  23975. }
  23976. generate( builder, output ) {
  23977. const textureProperty = this.textureNode.build( builder, 'property' );
  23978. const levelNode = this.levelNode.build( builder, 'int' );
  23979. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ levelNode } )`, this.getNodeType( builder ), output );
  23980. }
  23981. }
  23982. const textureSize = nodeProxy( TextureSizeNode );
  23983. addNodeElement( 'textureSize', textureSize );
  23984. addNodeClass( 'TextureSizeNode', TextureSizeNode );
  23985. class OperatorNode extends TempNode {
  23986. constructor( op, aNode, bNode, ...params ) {
  23987. super();
  23988. if ( params.length > 0 ) {
  23989. let finalOp = new OperatorNode( op, aNode, bNode );
  23990. for ( let i = 0; i < params.length - 1; i ++ ) {
  23991. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  23992. }
  23993. aNode = finalOp;
  23994. bNode = params[ params.length - 1 ];
  23995. }
  23996. this.op = op;
  23997. this.aNode = aNode;
  23998. this.bNode = bNode;
  23999. }
  24000. getNodeType( builder, output ) {
  24001. const op = this.op;
  24002. const aNode = this.aNode;
  24003. const bNode = this.bNode;
  24004. const typeA = aNode.getNodeType( builder );
  24005. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24006. if ( typeA === 'void' || typeB === 'void' ) {
  24007. return 'void';
  24008. } else if ( op === '%' ) {
  24009. return typeA;
  24010. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  24011. return builder.getIntegerType( typeA );
  24012. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  24013. return 'bool';
  24014. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  24015. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  24016. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  24017. } else {
  24018. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  24019. return typeB;
  24020. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24021. // matrix x vector
  24022. return builder.getVectorFromMatrix( typeA );
  24023. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24024. // vector x matrix
  24025. return builder.getVectorFromMatrix( typeB );
  24026. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  24027. // anytype x anytype: use the greater length vector
  24028. return typeB;
  24029. }
  24030. return typeA;
  24031. }
  24032. }
  24033. generate( builder, output ) {
  24034. const op = this.op;
  24035. const aNode = this.aNode;
  24036. const bNode = this.bNode;
  24037. const type = this.getNodeType( builder, output );
  24038. let typeA = null;
  24039. let typeB = null;
  24040. if ( type !== 'void' ) {
  24041. typeA = aNode.getNodeType( builder );
  24042. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24043. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  24044. if ( builder.isVector( typeA ) ) {
  24045. typeB = typeA;
  24046. } else {
  24047. typeA = typeB = 'float';
  24048. }
  24049. } else if ( op === '>>' || op === '<<' ) {
  24050. typeA = type;
  24051. typeB = builder.changeComponentType( typeB, 'uint' );
  24052. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24053. // matrix x vector
  24054. typeB = builder.getVectorFromMatrix( typeA );
  24055. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24056. // vector x matrix
  24057. typeA = builder.getVectorFromMatrix( typeB );
  24058. } else {
  24059. // anytype x anytype
  24060. typeA = typeB = type;
  24061. }
  24062. } else {
  24063. typeA = typeB = type;
  24064. }
  24065. const a = aNode.build( builder, typeA );
  24066. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  24067. const outputLength = builder.getTypeLength( output );
  24068. const fnOpSnippet = builder.getFunctionOperator( op );
  24069. if ( output !== 'void' ) {
  24070. if ( op === '<' && outputLength > 1 ) {
  24071. return builder.format( `${ builder.getMethod( 'lessThan' ) }( ${ a }, ${ b } )`, type, output );
  24072. } else if ( op === '<=' && outputLength > 1 ) {
  24073. return builder.format( `${ builder.getMethod( 'lessThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24074. } else if ( op === '>' && outputLength > 1 ) {
  24075. return builder.format( `${ builder.getMethod( 'greaterThan' ) }( ${ a }, ${ b } )`, type, output );
  24076. } else if ( op === '>=' && outputLength > 1 ) {
  24077. return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24078. } else if ( op === '!' || op === '~' ) {
  24079. return builder.format( `(${op}${a})`, typeA, output );
  24080. } else if ( fnOpSnippet ) {
  24081. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24082. } else {
  24083. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  24084. }
  24085. } else if ( typeA !== 'void' ) {
  24086. if ( fnOpSnippet ) {
  24087. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24088. } else {
  24089. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  24090. }
  24091. }
  24092. }
  24093. serialize( data ) {
  24094. super.serialize( data );
  24095. data.op = this.op;
  24096. }
  24097. deserialize( data ) {
  24098. super.deserialize( data );
  24099. this.op = data.op;
  24100. }
  24101. }
  24102. const add = nodeProxy( OperatorNode, '+' );
  24103. const sub = nodeProxy( OperatorNode, '-' );
  24104. const mul = nodeProxy( OperatorNode, '*' );
  24105. const div = nodeProxy( OperatorNode, '/' );
  24106. const remainder = nodeProxy( OperatorNode, '%' );
  24107. const equal = nodeProxy( OperatorNode, '==' );
  24108. const notEqual = nodeProxy( OperatorNode, '!=' );
  24109. const lessThan = nodeProxy( OperatorNode, '<' );
  24110. const greaterThan = nodeProxy( OperatorNode, '>' );
  24111. const lessThanEqual = nodeProxy( OperatorNode, '<=' );
  24112. const greaterThanEqual = nodeProxy( OperatorNode, '>=' );
  24113. const and = nodeProxy( OperatorNode, '&&' );
  24114. const or = nodeProxy( OperatorNode, '||' );
  24115. const not = nodeProxy( OperatorNode, '!' );
  24116. const xor = nodeProxy( OperatorNode, '^^' );
  24117. const bitAnd = nodeProxy( OperatorNode, '&' );
  24118. const bitNot = nodeProxy( OperatorNode, '~' );
  24119. const bitOr = nodeProxy( OperatorNode, '|' );
  24120. const bitXor = nodeProxy( OperatorNode, '^' );
  24121. const shiftLeft = nodeProxy( OperatorNode, '<<' );
  24122. const shiftRight = nodeProxy( OperatorNode, '>>' );
  24123. addNodeElement( 'add', add );
  24124. addNodeElement( 'sub', sub );
  24125. addNodeElement( 'mul', mul );
  24126. addNodeElement( 'div', div );
  24127. addNodeElement( 'remainder', remainder );
  24128. addNodeElement( 'equal', equal );
  24129. addNodeElement( 'notEqual', notEqual );
  24130. addNodeElement( 'lessThan', lessThan );
  24131. addNodeElement( 'greaterThan', greaterThan );
  24132. addNodeElement( 'lessThanEqual', lessThanEqual );
  24133. addNodeElement( 'greaterThanEqual', greaterThanEqual );
  24134. addNodeElement( 'and', and );
  24135. addNodeElement( 'or', or );
  24136. addNodeElement( 'not', not );
  24137. addNodeElement( 'xor', xor );
  24138. addNodeElement( 'bitAnd', bitAnd );
  24139. addNodeElement( 'bitNot', bitNot );
  24140. addNodeElement( 'bitOr', bitOr );
  24141. addNodeElement( 'bitXor', bitXor );
  24142. addNodeElement( 'shiftLeft', shiftLeft );
  24143. addNodeElement( 'shiftRight', shiftRight );
  24144. addNodeClass( 'OperatorNode', OperatorNode );
  24145. class MathNode extends TempNode {
  24146. constructor( method, aNode, bNode = null, cNode = null ) {
  24147. super();
  24148. this.method = method;
  24149. this.aNode = aNode;
  24150. this.bNode = bNode;
  24151. this.cNode = cNode;
  24152. }
  24153. getInputType( builder ) {
  24154. const aType = this.aNode.getNodeType( builder );
  24155. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  24156. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  24157. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  24158. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  24159. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  24160. if ( aLen > bLen && aLen > cLen ) {
  24161. return aType;
  24162. } else if ( bLen > cLen ) {
  24163. return bType;
  24164. } else if ( cLen > aLen ) {
  24165. return cType;
  24166. }
  24167. return aType;
  24168. }
  24169. getNodeType( builder ) {
  24170. const method = this.method;
  24171. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  24172. return 'float';
  24173. } else if ( method === MathNode.CROSS ) {
  24174. return 'vec3';
  24175. } else if ( method === MathNode.ALL ) {
  24176. return 'bool';
  24177. } else if ( method === MathNode.EQUALS ) {
  24178. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  24179. } else if ( method === MathNode.MOD ) {
  24180. return this.aNode.getNodeType( builder );
  24181. } else {
  24182. return this.getInputType( builder );
  24183. }
  24184. }
  24185. generate( builder, output ) {
  24186. const method = this.method;
  24187. const type = this.getNodeType( builder );
  24188. const inputType = this.getInputType( builder );
  24189. const a = this.aNode;
  24190. const b = this.bNode;
  24191. const c = this.cNode;
  24192. const isWebGL = builder.renderer.isWebGLRenderer === true;
  24193. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  24194. // dir can be either a direction vector or a normal vector
  24195. // upper-left 3x3 of matrix is assumed to be orthogonal
  24196. let tA = a;
  24197. let tB = b;
  24198. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  24199. tB = vec4( vec3( tB ), 0.0 );
  24200. } else {
  24201. tA = vec4( vec3( tA ), 0.0 );
  24202. }
  24203. const mulNode = mul( tA, tB ).xyz;
  24204. return normalize( mulNode ).build( builder, output );
  24205. } else if ( method === MathNode.NEGATE ) {
  24206. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  24207. } else if ( method === MathNode.ONE_MINUS ) {
  24208. return sub( 1.0, a ).build( builder, output );
  24209. } else if ( method === MathNode.RECIPROCAL ) {
  24210. return div( 1.0, a ).build( builder, output );
  24211. } else if ( method === MathNode.DIFFERENCE ) {
  24212. return abs( sub( a, b ) ).build( builder, output );
  24213. } else {
  24214. const params = [];
  24215. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  24216. params.push(
  24217. a.build( builder, type ),
  24218. b.build( builder, type )
  24219. );
  24220. } else if ( method === MathNode.STEP ) {
  24221. params.push(
  24222. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  24223. b.build( builder, inputType )
  24224. );
  24225. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  24226. params.push(
  24227. a.build( builder, inputType ),
  24228. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24229. );
  24230. } else if ( method === MathNode.REFRACT ) {
  24231. params.push(
  24232. a.build( builder, inputType ),
  24233. b.build( builder, inputType ),
  24234. c.build( builder, 'float' )
  24235. );
  24236. } else if ( method === MathNode.MIX ) {
  24237. params.push(
  24238. a.build( builder, inputType ),
  24239. b.build( builder, inputType ),
  24240. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24241. );
  24242. } else {
  24243. params.push( a.build( builder, inputType ) );
  24244. if ( b !== null ) params.push( b.build( builder, inputType ) );
  24245. if ( c !== null ) params.push( c.build( builder, inputType ) );
  24246. }
  24247. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  24248. }
  24249. }
  24250. serialize( data ) {
  24251. super.serialize( data );
  24252. data.method = this.method;
  24253. }
  24254. deserialize( data ) {
  24255. super.deserialize( data );
  24256. this.method = data.method;
  24257. }
  24258. }
  24259. // 1 input
  24260. MathNode.ALL = 'all';
  24261. MathNode.ANY = 'any';
  24262. MathNode.EQUALS = 'equals';
  24263. MathNode.RADIANS = 'radians';
  24264. MathNode.DEGREES = 'degrees';
  24265. MathNode.EXP = 'exp';
  24266. MathNode.EXP2 = 'exp2';
  24267. MathNode.LOG = 'log';
  24268. MathNode.LOG2 = 'log2';
  24269. MathNode.SQRT = 'sqrt';
  24270. MathNode.INVERSE_SQRT = 'inversesqrt';
  24271. MathNode.FLOOR = 'floor';
  24272. MathNode.CEIL = 'ceil';
  24273. MathNode.NORMALIZE = 'normalize';
  24274. MathNode.FRACT = 'fract';
  24275. MathNode.SIN = 'sin';
  24276. MathNode.COS = 'cos';
  24277. MathNode.TAN = 'tan';
  24278. MathNode.ASIN = 'asin';
  24279. MathNode.ACOS = 'acos';
  24280. MathNode.ATAN = 'atan';
  24281. MathNode.ABS = 'abs';
  24282. MathNode.SIGN = 'sign';
  24283. MathNode.LENGTH = 'length';
  24284. MathNode.NEGATE = 'negate';
  24285. MathNode.ONE_MINUS = 'oneMinus';
  24286. MathNode.DFDX = 'dFdx';
  24287. MathNode.DFDY = 'dFdy';
  24288. MathNode.ROUND = 'round';
  24289. MathNode.RECIPROCAL = 'reciprocal';
  24290. MathNode.TRUNC = 'trunc';
  24291. MathNode.FWIDTH = 'fwidth';
  24292. MathNode.BITCAST = 'bitcast';
  24293. MathNode.TRANSPOSE = 'transpose';
  24294. // 2 inputs
  24295. MathNode.ATAN2 = 'atan2';
  24296. MathNode.MIN = 'min';
  24297. MathNode.MAX = 'max';
  24298. MathNode.MOD = 'mod';
  24299. MathNode.STEP = 'step';
  24300. MathNode.REFLECT = 'reflect';
  24301. MathNode.DISTANCE = 'distance';
  24302. MathNode.DIFFERENCE = 'difference';
  24303. MathNode.DOT = 'dot';
  24304. MathNode.CROSS = 'cross';
  24305. MathNode.POW = 'pow';
  24306. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  24307. // 3 inputs
  24308. MathNode.MIX = 'mix';
  24309. MathNode.CLAMP = 'clamp';
  24310. MathNode.REFRACT = 'refract';
  24311. MathNode.SMOOTHSTEP = 'smoothstep';
  24312. MathNode.FACEFORWARD = 'faceforward';
  24313. const EPSILON = float( 1e-6 );
  24314. const INFINITY = float( 1e6 );
  24315. const PI = float( Math.PI );
  24316. const PI2 = float( Math.PI * 2 );
  24317. const all = nodeProxy( MathNode, MathNode.ALL );
  24318. const any = nodeProxy( MathNode, MathNode.ANY );
  24319. const equals = nodeProxy( MathNode, MathNode.EQUALS );
  24320. const radians = nodeProxy( MathNode, MathNode.RADIANS );
  24321. const degrees = nodeProxy( MathNode, MathNode.DEGREES );
  24322. const exp = nodeProxy( MathNode, MathNode.EXP );
  24323. const exp2 = nodeProxy( MathNode, MathNode.EXP2 );
  24324. const log = nodeProxy( MathNode, MathNode.LOG );
  24325. const log2 = nodeProxy( MathNode, MathNode.LOG2 );
  24326. const sqrt = nodeProxy( MathNode, MathNode.SQRT );
  24327. const inverseSqrt = nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  24328. const floor = nodeProxy( MathNode, MathNode.FLOOR );
  24329. const ceil = nodeProxy( MathNode, MathNode.CEIL );
  24330. const normalize = nodeProxy( MathNode, MathNode.NORMALIZE );
  24331. const fract = nodeProxy( MathNode, MathNode.FRACT );
  24332. const sin = nodeProxy( MathNode, MathNode.SIN );
  24333. const cos = nodeProxy( MathNode, MathNode.COS );
  24334. const tan = nodeProxy( MathNode, MathNode.TAN );
  24335. const asin = nodeProxy( MathNode, MathNode.ASIN );
  24336. const acos = nodeProxy( MathNode, MathNode.ACOS );
  24337. const atan = nodeProxy( MathNode, MathNode.ATAN );
  24338. const abs = nodeProxy( MathNode, MathNode.ABS );
  24339. const sign = nodeProxy( MathNode, MathNode.SIGN );
  24340. const length = nodeProxy( MathNode, MathNode.LENGTH );
  24341. const negate = nodeProxy( MathNode, MathNode.NEGATE );
  24342. const oneMinus = nodeProxy( MathNode, MathNode.ONE_MINUS );
  24343. const dFdx = nodeProxy( MathNode, MathNode.DFDX );
  24344. const dFdy = nodeProxy( MathNode, MathNode.DFDY );
  24345. const round = nodeProxy( MathNode, MathNode.ROUND );
  24346. const reciprocal = nodeProxy( MathNode, MathNode.RECIPROCAL );
  24347. const trunc = nodeProxy( MathNode, MathNode.TRUNC );
  24348. const fwidth = nodeProxy( MathNode, MathNode.FWIDTH );
  24349. const bitcast = nodeProxy( MathNode, MathNode.BITCAST );
  24350. const transpose = nodeProxy( MathNode, MathNode.TRANSPOSE );
  24351. const atan2 = nodeProxy( MathNode, MathNode.ATAN2 );
  24352. const min$1 = nodeProxy( MathNode, MathNode.MIN );
  24353. const max$1 = nodeProxy( MathNode, MathNode.MAX );
  24354. const mod = nodeProxy( MathNode, MathNode.MOD );
  24355. const step = nodeProxy( MathNode, MathNode.STEP );
  24356. const reflect = nodeProxy( MathNode, MathNode.REFLECT );
  24357. const distance = nodeProxy( MathNode, MathNode.DISTANCE );
  24358. const difference = nodeProxy( MathNode, MathNode.DIFFERENCE );
  24359. const dot = nodeProxy( MathNode, MathNode.DOT );
  24360. const cross = nodeProxy( MathNode, MathNode.CROSS );
  24361. const pow = nodeProxy( MathNode, MathNode.POW );
  24362. const pow2 = nodeProxy( MathNode, MathNode.POW, 2 );
  24363. const pow3 = nodeProxy( MathNode, MathNode.POW, 3 );
  24364. const pow4 = nodeProxy( MathNode, MathNode.POW, 4 );
  24365. const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  24366. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  24367. const lengthSq = ( a ) => dot( a, a );
  24368. const mix = nodeProxy( MathNode, MathNode.MIX );
  24369. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  24370. const saturate = ( value ) => clamp( value );
  24371. const refract = nodeProxy( MathNode, MathNode.REFRACT );
  24372. const smoothstep = nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  24373. const faceForward = nodeProxy( MathNode, MathNode.FACEFORWARD );
  24374. const rand = tslFn( ( [ uv ] ) => {
  24375. const a = 12.9898, b = 78.233, c = 43758.5453;
  24376. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  24377. return fract( sin( sn ).mul( c ) );
  24378. } );
  24379. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  24380. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  24381. addNodeElement( 'all', all );
  24382. addNodeElement( 'any', any );
  24383. addNodeElement( 'equals', equals );
  24384. addNodeElement( 'radians', radians );
  24385. addNodeElement( 'degrees', degrees );
  24386. addNodeElement( 'exp', exp );
  24387. addNodeElement( 'exp2', exp2 );
  24388. addNodeElement( 'log', log );
  24389. addNodeElement( 'log2', log2 );
  24390. addNodeElement( 'sqrt', sqrt );
  24391. addNodeElement( 'inverseSqrt', inverseSqrt );
  24392. addNodeElement( 'floor', floor );
  24393. addNodeElement( 'ceil', ceil );
  24394. addNodeElement( 'normalize', normalize );
  24395. addNodeElement( 'fract', fract );
  24396. addNodeElement( 'sin', sin );
  24397. addNodeElement( 'cos', cos );
  24398. addNodeElement( 'tan', tan );
  24399. addNodeElement( 'asin', asin );
  24400. addNodeElement( 'acos', acos );
  24401. addNodeElement( 'atan', atan );
  24402. addNodeElement( 'abs', abs );
  24403. addNodeElement( 'sign', sign );
  24404. addNodeElement( 'length', length );
  24405. addNodeElement( 'lengthSq', lengthSq );
  24406. addNodeElement( 'negate', negate );
  24407. addNodeElement( 'oneMinus', oneMinus );
  24408. addNodeElement( 'dFdx', dFdx );
  24409. addNodeElement( 'dFdy', dFdy );
  24410. addNodeElement( 'round', round );
  24411. addNodeElement( 'reciprocal', reciprocal );
  24412. addNodeElement( 'trunc', trunc );
  24413. addNodeElement( 'fwidth', fwidth );
  24414. addNodeElement( 'atan2', atan2 );
  24415. addNodeElement( 'min', min$1 );
  24416. addNodeElement( 'max', max$1 );
  24417. addNodeElement( 'mod', mod );
  24418. addNodeElement( 'step', step );
  24419. addNodeElement( 'reflect', reflect );
  24420. addNodeElement( 'distance', distance );
  24421. addNodeElement( 'dot', dot );
  24422. addNodeElement( 'cross', cross );
  24423. addNodeElement( 'pow', pow );
  24424. addNodeElement( 'pow2', pow2 );
  24425. addNodeElement( 'pow3', pow3 );
  24426. addNodeElement( 'pow4', pow4 );
  24427. addNodeElement( 'transformDirection', transformDirection );
  24428. addNodeElement( 'mix', mixElement );
  24429. addNodeElement( 'clamp', clamp );
  24430. addNodeElement( 'refract', refract );
  24431. addNodeElement( 'smoothstep', smoothstepElement );
  24432. addNodeElement( 'faceForward', faceForward );
  24433. addNodeElement( 'difference', difference );
  24434. addNodeElement( 'saturate', saturate );
  24435. addNodeElement( 'cbrt', cbrt );
  24436. addNodeElement( 'transpose', transpose );
  24437. addNodeElement( 'rand', rand );
  24438. addNodeClass( 'MathNode', MathNode );
  24439. const sRGBToLinearShader = tslFn( ( inputs ) => {
  24440. const { value } = inputs;
  24441. const { rgb } = value;
  24442. const a = rgb.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  24443. const b = rgb.mul( 0.0773993808 );
  24444. const factor = rgb.lessThanEqual( 0.04045 );
  24445. const rgbResult = mix( a, b, factor );
  24446. return vec4( rgbResult, value.a );
  24447. } );
  24448. const LinearTosRGBShader = tslFn( ( inputs ) => {
  24449. const { value } = inputs;
  24450. const { rgb } = value;
  24451. const a = rgb.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  24452. const b = rgb.mul( 12.92 );
  24453. const factor = rgb.lessThanEqual( 0.0031308 );
  24454. const rgbResult = mix( a, b, factor );
  24455. return vec4( rgbResult, value.a );
  24456. } );
  24457. const getColorSpaceMethod = ( colorSpace ) => {
  24458. let method = null;
  24459. if ( colorSpace === LinearSRGBColorSpace ) {
  24460. method = 'Linear';
  24461. } else if ( colorSpace === SRGBColorSpace ) {
  24462. method = 'sRGB';
  24463. }
  24464. return method;
  24465. };
  24466. const getMethod = ( source, target ) => {
  24467. return getColorSpaceMethod( source ) + 'To' + getColorSpaceMethod( target );
  24468. };
  24469. class ColorSpaceNode extends TempNode {
  24470. constructor( method, node ) {
  24471. super( 'vec4' );
  24472. this.method = method;
  24473. this.node = node;
  24474. }
  24475. setup() {
  24476. const { method, node } = this;
  24477. if ( method === ColorSpaceNode.LINEAR_TO_LINEAR )
  24478. return node;
  24479. return Methods[ method ]( { value: node } );
  24480. }
  24481. }
  24482. ColorSpaceNode.LINEAR_TO_LINEAR = 'LinearToLinear';
  24483. ColorSpaceNode.LINEAR_TO_sRGB = 'LinearTosRGB';
  24484. ColorSpaceNode.sRGB_TO_LINEAR = 'sRGBToLinear';
  24485. const Methods = {
  24486. [ ColorSpaceNode.LINEAR_TO_sRGB ]: LinearTosRGBShader,
  24487. [ ColorSpaceNode.sRGB_TO_LINEAR ]: sRGBToLinearShader
  24488. };
  24489. const linearToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( LinearSRGBColorSpace, colorSpace ), nodeObject( node ) ) );
  24490. const colorSpaceToLinear = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( colorSpace, LinearSRGBColorSpace ), nodeObject( node ) ) );
  24491. const linearTosRGB = nodeProxy( ColorSpaceNode, ColorSpaceNode.LINEAR_TO_sRGB );
  24492. const sRGBToLinear = nodeProxy( ColorSpaceNode, ColorSpaceNode.sRGB_TO_LINEAR );
  24493. addNodeElement( 'linearTosRGB', linearTosRGB );
  24494. addNodeElement( 'sRGBToLinear', sRGBToLinear );
  24495. addNodeElement( 'linearToColorSpace', linearToColorSpace );
  24496. addNodeElement( 'colorSpaceToLinear', colorSpaceToLinear );
  24497. addNodeClass( 'ColorSpaceNode', ColorSpaceNode );
  24498. class ExpressionNode extends Node {
  24499. constructor( snippet = '', nodeType = 'void' ) {
  24500. super( nodeType );
  24501. this.snippet = snippet;
  24502. }
  24503. generate( builder, output ) {
  24504. const type = this.getNodeType( builder );
  24505. const snippet = this.snippet;
  24506. if ( type === 'void' ) {
  24507. builder.addLineFlowCode( snippet );
  24508. } else {
  24509. return builder.format( `( ${ snippet } )`, type, output );
  24510. }
  24511. }
  24512. }
  24513. const expression = nodeProxy( ExpressionNode );
  24514. addNodeClass( 'ExpressionNode', ExpressionNode );
  24515. class MaxMipLevelNode extends UniformNode {
  24516. constructor( textureNode ) {
  24517. super( 0 );
  24518. this._textureNode = textureNode;
  24519. this.updateType = NodeUpdateType.FRAME;
  24520. }
  24521. get textureNode() {
  24522. return this._textureNode;
  24523. }
  24524. get texture() {
  24525. return this._textureNode.value;
  24526. }
  24527. update() {
  24528. const texture = this.texture;
  24529. const images = texture.images;
  24530. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24531. if ( image && image.width !== undefined ) {
  24532. const { width, height } = image;
  24533. this.value = Math.log2( Math.max( width, height ) );
  24534. }
  24535. }
  24536. }
  24537. const maxMipLevel = nodeProxy( MaxMipLevelNode );
  24538. addNodeClass( 'MaxMipLevelNode', MaxMipLevelNode );
  24539. class TextureNode extends UniformNode {
  24540. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24541. super( value );
  24542. this.isTextureNode = true;
  24543. this.uvNode = uvNode;
  24544. this.levelNode = levelNode;
  24545. this.biasNode = biasNode;
  24546. this.compareNode = null;
  24547. this.depthNode = null;
  24548. this.gradNode = null;
  24549. this.sampler = true;
  24550. this.updateMatrix = false;
  24551. this.updateType = NodeUpdateType.NONE;
  24552. this.referenceNode = null;
  24553. this._value = value;
  24554. this._matrixUniform = null;
  24555. this.setUpdateMatrix( uvNode === null );
  24556. }
  24557. set value( value ) {
  24558. if ( this.referenceNode ) {
  24559. this.referenceNode.value = value;
  24560. } else {
  24561. this._value = value;
  24562. }
  24563. }
  24564. get value() {
  24565. return this.referenceNode ? this.referenceNode.value : this._value;
  24566. }
  24567. getUniformHash( /*builder*/ ) {
  24568. return this.value.uuid;
  24569. }
  24570. getNodeType( /*builder*/ ) {
  24571. if ( this.value.isDepthTexture === true ) return 'float';
  24572. if ( this.value.type === UnsignedIntType ) {
  24573. return 'uvec4';
  24574. } else if ( this.value.type === IntType ) {
  24575. return 'ivec4';
  24576. }
  24577. return 'vec4';
  24578. }
  24579. getInputType( /*builder*/ ) {
  24580. return 'texture';
  24581. }
  24582. getDefaultUV() {
  24583. return uv( this.value.channel );
  24584. }
  24585. updateReference( /*state*/ ) {
  24586. return this.value;
  24587. }
  24588. getTransformedUV( uvNode ) {
  24589. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24590. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24591. }
  24592. setUpdateMatrix( value ) {
  24593. this.updateMatrix = value;
  24594. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24595. return this;
  24596. }
  24597. setupUV( builder, uvNode ) {
  24598. const texture = this.value;
  24599. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24600. uvNode = uvNode.setY( uvNode.y.oneMinus() );
  24601. }
  24602. return uvNode;
  24603. }
  24604. setup( builder ) {
  24605. const properties = builder.getNodeProperties( this );
  24606. properties.referenceNode = this.referenceNode;
  24607. //
  24608. let uvNode = this.uvNode;
  24609. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24610. uvNode = builder.context.getUV( this );
  24611. }
  24612. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24613. if ( this.updateMatrix === true ) {
  24614. uvNode = this.getTransformedUV( uvNode );
  24615. }
  24616. uvNode = this.setupUV( builder, uvNode );
  24617. //
  24618. let levelNode = this.levelNode;
  24619. if ( levelNode === null && builder.context.getTextureLevel ) {
  24620. levelNode = builder.context.getTextureLevel( this );
  24621. }
  24622. //
  24623. properties.uvNode = uvNode;
  24624. properties.levelNode = levelNode;
  24625. properties.biasNode = this.biasNode;
  24626. properties.compareNode = this.compareNode;
  24627. properties.gradNode = this.gradNode;
  24628. properties.depthNode = this.depthNode;
  24629. }
  24630. generateUV( builder, uvNode ) {
  24631. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24632. }
  24633. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24634. const texture = this.value;
  24635. let snippet;
  24636. if ( levelSnippet ) {
  24637. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24638. } else if ( biasSnippet ) {
  24639. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24640. } else if ( gradSnippet ) {
  24641. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24642. } else if ( compareSnippet ) {
  24643. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24644. } else if ( this.sampler === false ) {
  24645. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24646. } else {
  24647. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24648. }
  24649. return snippet;
  24650. }
  24651. generate( builder, output ) {
  24652. const properties = builder.getNodeProperties( this );
  24653. const texture = this.value;
  24654. if ( ! texture || texture.isTexture !== true ) {
  24655. throw new Error( 'TextureNode: Need a three.js texture.' );
  24656. }
  24657. const textureProperty = super.generate( builder, 'property' );
  24658. if ( output === 'sampler' ) {
  24659. return textureProperty + '_sampler';
  24660. } else if ( builder.isReference( output ) ) {
  24661. return textureProperty;
  24662. } else {
  24663. const nodeData = builder.getDataFromNode( this );
  24664. let propertyName = nodeData.propertyName;
  24665. if ( propertyName === undefined ) {
  24666. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24667. const uvSnippet = this.generateUV( builder, uvNode );
  24668. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24669. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24670. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24671. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24672. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24673. const nodeVar = builder.getVarFromNode( this );
  24674. propertyName = builder.getPropertyName( nodeVar );
  24675. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24676. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  24677. nodeData.snippet = snippet;
  24678. nodeData.propertyName = propertyName;
  24679. }
  24680. let snippet = propertyName;
  24681. const nodeType = this.getNodeType( builder );
  24682. if ( builder.needsColorSpaceToLinear( texture ) ) {
  24683. snippet = colorSpaceToLinear( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24684. }
  24685. return builder.format( snippet, nodeType, output );
  24686. }
  24687. }
  24688. setSampler( value ) {
  24689. this.sampler = value;
  24690. return this;
  24691. }
  24692. getSampler() {
  24693. return this.sampler;
  24694. }
  24695. // @TODO: Move to TSL
  24696. uv( uvNode ) {
  24697. const textureNode = this.clone();
  24698. textureNode.uvNode = nodeObject( uvNode );
  24699. textureNode.referenceNode = this;
  24700. return nodeObject( textureNode );
  24701. }
  24702. blur( amountNode ) {
  24703. const textureNode = this.clone();
  24704. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24705. textureNode.referenceNode = this;
  24706. return nodeObject( textureNode );
  24707. }
  24708. level( levelNode ) {
  24709. const textureNode = this.clone();
  24710. textureNode.levelNode = nodeObject( levelNode );
  24711. textureNode.referenceNode = this;
  24712. return nodeObject( textureNode );
  24713. }
  24714. size( levelNode ) {
  24715. return textureSize( this, levelNode );
  24716. }
  24717. bias( biasNode ) {
  24718. const textureNode = this.clone();
  24719. textureNode.biasNode = nodeObject( biasNode );
  24720. textureNode.referenceNode = this;
  24721. return nodeObject( textureNode );
  24722. }
  24723. compare( compareNode ) {
  24724. const textureNode = this.clone();
  24725. textureNode.compareNode = nodeObject( compareNode );
  24726. textureNode.referenceNode = this;
  24727. return nodeObject( textureNode );
  24728. }
  24729. grad( gradNodeX, gradNodeY ) {
  24730. const textureNode = this.clone();
  24731. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24732. textureNode.referenceNode = this;
  24733. return nodeObject( textureNode );
  24734. }
  24735. depth( depthNode ) {
  24736. const textureNode = this.clone();
  24737. textureNode.depthNode = nodeObject( depthNode );
  24738. textureNode.referenceNode = this;
  24739. return nodeObject( textureNode );
  24740. }
  24741. // --
  24742. serialize( data ) {
  24743. super.serialize( data );
  24744. data.value = this.value.toJSON( data.meta ).uuid;
  24745. }
  24746. deserialize( data ) {
  24747. super.deserialize( data );
  24748. this.value = data.meta.textures[ data.value ];
  24749. }
  24750. update() {
  24751. const texture = this.value;
  24752. const matrixUniform = this._matrixUniform;
  24753. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24754. if ( texture.matrixAutoUpdate === true ) {
  24755. texture.updateMatrix();
  24756. }
  24757. }
  24758. clone() {
  24759. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24760. newNode.sampler = this.sampler;
  24761. return newNode;
  24762. }
  24763. }
  24764. const texture = nodeProxy( TextureNode );
  24765. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24766. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24767. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24768. addNodeElement( 'texture', texture );
  24769. //addNodeElement( 'textureLevel', textureLevel );
  24770. addNodeClass( 'TextureNode', TextureNode );
  24771. class BufferNode extends UniformNode {
  24772. constructor( value, bufferType, bufferCount = 0 ) {
  24773. super( value, bufferType );
  24774. this.isBufferNode = true;
  24775. this.bufferType = bufferType;
  24776. this.bufferCount = bufferCount;
  24777. }
  24778. getElementType( builder ) {
  24779. return this.getNodeType( builder );
  24780. }
  24781. getInputType( /*builder*/ ) {
  24782. return 'buffer';
  24783. }
  24784. }
  24785. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24786. addNodeClass( 'BufferNode', BufferNode );
  24787. class UniformsElementNode extends ArrayElementNode {
  24788. constructor( arrayBuffer, indexNode ) {
  24789. super( arrayBuffer, indexNode );
  24790. this.isArrayBufferElementNode = true;
  24791. }
  24792. getNodeType( builder ) {
  24793. return this.node.getElementType( builder );
  24794. }
  24795. generate( builder ) {
  24796. const snippet = super.generate( builder );
  24797. const type = this.getNodeType();
  24798. return builder.format( snippet, 'vec4', type );
  24799. }
  24800. }
  24801. class UniformsNode extends BufferNode {
  24802. constructor( value, elementType = null ) {
  24803. super( null, 'vec4' );
  24804. this.array = value;
  24805. this.elementType = elementType;
  24806. this._elementType = null;
  24807. this._elementLength = 0;
  24808. this.updateType = NodeUpdateType.RENDER;
  24809. this.isArrayBufferNode = true;
  24810. }
  24811. getElementType() {
  24812. return this.elementType || this._elementType;
  24813. }
  24814. getElementLength() {
  24815. return this._elementLength;
  24816. }
  24817. update( /*frame*/ ) {
  24818. const { array, value } = this;
  24819. const elementLength = this.getElementLength();
  24820. const elementType = this.getElementType();
  24821. if ( elementLength === 1 ) {
  24822. for ( let i = 0; i < array.length; i ++ ) {
  24823. const index = i * 4;
  24824. value[ index ] = array[ i ];
  24825. }
  24826. } else if ( elementType === 'color' ) {
  24827. for ( let i = 0; i < array.length; i ++ ) {
  24828. const index = i * 4;
  24829. const vector = array[ i ];
  24830. value[ index ] = vector.r;
  24831. value[ index + 1 ] = vector.g;
  24832. value[ index + 2 ] = vector.b || 0;
  24833. //value[ index + 3 ] = vector.a || 0;
  24834. }
  24835. } else {
  24836. for ( let i = 0; i < array.length; i ++ ) {
  24837. const index = i * 4;
  24838. const vector = array[ i ];
  24839. value[ index ] = vector.x;
  24840. value[ index + 1 ] = vector.y;
  24841. value[ index + 2 ] = vector.z || 0;
  24842. value[ index + 3 ] = vector.w || 0;
  24843. }
  24844. }
  24845. }
  24846. setup( builder ) {
  24847. const length = this.array.length;
  24848. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24849. this._elementLength = builder.getTypeLength( this._elementType );
  24850. let arrayType = Float32Array;
  24851. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24852. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24853. this.value = new arrayType( length * 4 );
  24854. this.bufferCount = length;
  24855. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24856. return super.setup( builder );
  24857. }
  24858. element( indexNode ) {
  24859. return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) );
  24860. }
  24861. }
  24862. const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) );
  24863. addNodeClass( 'UniformsNode', UniformsNode );
  24864. class ReferenceElementNode extends ArrayElementNode {
  24865. constructor( referenceNode, indexNode ) {
  24866. super( referenceNode, indexNode );
  24867. this.referenceNode = referenceNode;
  24868. this.isReferenceElementNode = true;
  24869. }
  24870. getNodeType() {
  24871. return this.referenceNode.uniformType;
  24872. }
  24873. generate( builder ) {
  24874. const snippet = super.generate( builder );
  24875. const arrayType = this.referenceNode.getNodeType();
  24876. const elementType = this.getNodeType();
  24877. return builder.format( snippet, arrayType, elementType );
  24878. }
  24879. }
  24880. class ReferenceNode extends Node {
  24881. constructor( property, uniformType, object = null, count = null ) {
  24882. super();
  24883. this.property = property;
  24884. this.uniformType = uniformType;
  24885. this.object = object;
  24886. this.count = count;
  24887. this.properties = property.split( '.' );
  24888. this.reference = null;
  24889. this.node = null;
  24890. this.updateType = NodeUpdateType.OBJECT;
  24891. }
  24892. element( indexNode ) {
  24893. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24894. }
  24895. setNodeType( uniformType ) {
  24896. let node = null;
  24897. if ( this.count !== null ) {
  24898. node = buffer( null, uniformType, this.count );
  24899. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24900. node = uniforms( null, uniformType );
  24901. } else if ( uniformType === 'texture' ) {
  24902. node = texture( null );
  24903. } else {
  24904. node = uniform( null, uniformType );
  24905. }
  24906. this.node = node;
  24907. }
  24908. getNodeType( builder ) {
  24909. if ( this.node === null ) {
  24910. this.updateValue();
  24911. }
  24912. return this.node.getNodeType( builder );
  24913. }
  24914. getValueFromReference( object = this.reference ) {
  24915. const { properties } = this;
  24916. let value = object[ properties[ 0 ] ];
  24917. for ( let i = 1; i < properties.length; i ++ ) {
  24918. value = value[ properties[ i ] ];
  24919. }
  24920. return value;
  24921. }
  24922. updateReference( state ) {
  24923. this.reference = this.object !== null ? this.object : state.object;
  24924. return this.reference;
  24925. }
  24926. setup() {
  24927. this.updateValue();
  24928. return this.node;
  24929. }
  24930. update( /*frame*/ ) {
  24931. this.updateValue();
  24932. }
  24933. updateValue() {
  24934. if ( this.node === null ) this.setNodeType( this.uniformType );
  24935. const value = this.getValueFromReference();
  24936. if ( Array.isArray( value ) ) {
  24937. this.node.array = value;
  24938. } else {
  24939. this.node.value = value;
  24940. }
  24941. }
  24942. }
  24943. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  24944. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  24945. addNodeClass( 'ReferenceNode', ReferenceNode );
  24946. class MaterialReferenceNode extends ReferenceNode {
  24947. constructor( property, inputType, material = null ) {
  24948. super( property, inputType, material );
  24949. this.material = material;
  24950. //this.updateType = NodeUpdateType.RENDER;
  24951. }
  24952. /*setNodeType( node ) {
  24953. super.setNodeType( node );
  24954. this.node.groupNode = renderGroup;
  24955. }*/
  24956. updateReference( state ) {
  24957. this.reference = this.material !== null ? this.material : state.material;
  24958. return this.reference;
  24959. }
  24960. }
  24961. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  24962. addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode );
  24963. const cameraGroup = /*#__PURE__*/ sharedUniformGroup( 'camera' ).onRenderUpdate( () => {
  24964. cameraGroup.needsUpdate = true;
  24965. } );
  24966. const cameraNear = /*#__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24967. const cameraFar = /*#__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24968. const cameraLogDepth = /*#__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  24969. const cameraProjectionMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24970. const cameraProjectionMatrixInverse = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24971. const cameraViewMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24972. const cameraWorldMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24973. const cameraNormalMatrix = /*#__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24974. const cameraPosition = /*#__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24975. class Object3DNode extends Node {
  24976. constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) {
  24977. super();
  24978. this.scope = scope;
  24979. this.object3d = object3d;
  24980. this.updateType = NodeUpdateType.OBJECT;
  24981. this._uniformNode = new UniformNode( null );
  24982. }
  24983. getNodeType() {
  24984. const scope = this.scope;
  24985. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  24986. return 'mat4';
  24987. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  24988. return 'mat3';
  24989. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24990. return 'vec3';
  24991. }
  24992. }
  24993. update( frame ) {
  24994. const object = this.object3d;
  24995. const uniformNode = this._uniformNode;
  24996. const scope = this.scope;
  24997. if ( scope === Object3DNode.VIEW_MATRIX ) {
  24998. uniformNode.value = object.modelViewMatrix;
  24999. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25000. uniformNode.value = object.normalMatrix;
  25001. } else if ( scope === Object3DNode.WORLD_MATRIX ) {
  25002. uniformNode.value = object.matrixWorld;
  25003. } else if ( scope === Object3DNode.POSITION ) {
  25004. uniformNode.value = uniformNode.value || new Vector3();
  25005. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25006. } else if ( scope === Object3DNode.SCALE ) {
  25007. uniformNode.value = uniformNode.value || new Vector3();
  25008. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  25009. } else if ( scope === Object3DNode.DIRECTION ) {
  25010. uniformNode.value = uniformNode.value || new Vector3();
  25011. object.getWorldDirection( uniformNode.value );
  25012. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  25013. const camera = frame.camera;
  25014. uniformNode.value = uniformNode.value || new Vector3();
  25015. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25016. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  25017. }
  25018. }
  25019. generate( builder ) {
  25020. const scope = this.scope;
  25021. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  25022. this._uniformNode.nodeType = 'mat4';
  25023. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25024. this._uniformNode.nodeType = 'mat3';
  25025. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  25026. this._uniformNode.nodeType = 'vec3';
  25027. }
  25028. return this._uniformNode.build( builder );
  25029. }
  25030. serialize( data ) {
  25031. super.serialize( data );
  25032. data.scope = this.scope;
  25033. }
  25034. deserialize( data ) {
  25035. super.deserialize( data );
  25036. this.scope = data.scope;
  25037. }
  25038. }
  25039. Object3DNode.VIEW_MATRIX = 'viewMatrix';
  25040. Object3DNode.NORMAL_MATRIX = 'normalMatrix';
  25041. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  25042. Object3DNode.POSITION = 'position';
  25043. Object3DNode.SCALE = 'scale';
  25044. Object3DNode.VIEW_POSITION = 'viewPosition';
  25045. Object3DNode.DIRECTION = 'direction';
  25046. const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  25047. const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX );
  25048. const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX );
  25049. const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  25050. const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION );
  25051. const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE );
  25052. const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  25053. addNodeClass( 'Object3DNode', Object3DNode );
  25054. class ModelNode extends Object3DNode {
  25055. constructor( scope = ModelNode.VIEW_MATRIX ) {
  25056. super( scope );
  25057. }
  25058. update( frame ) {
  25059. this.object3d = frame.object;
  25060. super.update( frame );
  25061. }
  25062. }
  25063. const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION );
  25064. const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' );
  25065. const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX );
  25066. const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  25067. const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION );
  25068. const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE );
  25069. const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  25070. const modelWorldMatrixInverse = uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  25071. addNodeClass( 'ModelNode', ModelNode );
  25072. const normalGeometry = /*#__PURE__*/ attribute( 'normal', 'vec3', vec3( 0, 1, 0 ) );
  25073. const normalLocal = /*#__PURE__*/ normalGeometry.toVar( 'normalLocal' );
  25074. const normalView = /*#__PURE__*/ varying( modelNormalMatrix.mul( normalLocal ), 'v_normalView' ).normalize().toVar( 'normalView' );
  25075. const normalWorld = /*#__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'transformedNormalWorld' );
  25076. const transformedNormalView = /*#__PURE__*/ property( 'vec3', 'transformedNormalView' );
  25077. const transformedNormalWorld = /*#__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedNormalWorld' );
  25078. const transformedClearcoatNormalView = /*#__PURE__*/ property( 'vec3', 'transformedClearcoatNormalView' );
  25079. const _propertyCache = new Map();
  25080. class MaterialNode extends Node {
  25081. constructor( scope ) {
  25082. super();
  25083. this.scope = scope;
  25084. }
  25085. getCache( property, type ) {
  25086. let node = _propertyCache.get( property );
  25087. if ( node === undefined ) {
  25088. node = materialReference( property, type );
  25089. _propertyCache.set( property, node );
  25090. }
  25091. return node;
  25092. }
  25093. getFloat( property ) {
  25094. return this.getCache( property, 'float' );
  25095. }
  25096. getColor( property ) {
  25097. return this.getCache( property, 'color' );
  25098. }
  25099. getTexture( property ) {
  25100. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25101. }
  25102. setup( builder ) {
  25103. const material = builder.context.material;
  25104. const scope = this.scope;
  25105. let node = null;
  25106. if ( scope === MaterialNode.COLOR ) {
  25107. const colorNode = this.getColor( scope );
  25108. if ( material.map && material.map.isTexture === true ) {
  25109. node = colorNode.mul( this.getTexture( 'map' ) );
  25110. } else {
  25111. node = colorNode;
  25112. }
  25113. } else if ( scope === MaterialNode.OPACITY ) {
  25114. const opacityNode = this.getFloat( scope );
  25115. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25116. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25117. } else {
  25118. node = opacityNode;
  25119. }
  25120. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25121. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25122. node = this.getTexture( 'specular' ).r;
  25123. } else {
  25124. node = float( 1 );
  25125. }
  25126. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25127. const specularIntensity = this.getFloat( scope );
  25128. if ( material.specularMap ) {
  25129. node = specularIntensity.mul( this.getTexture( scope ).a );
  25130. } else {
  25131. node = specularIntensity;
  25132. }
  25133. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25134. const specularColorNode = this.getColor( scope );
  25135. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25136. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25137. } else {
  25138. node = specularColorNode;
  25139. }
  25140. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25141. const roughnessNode = this.getFloat( scope );
  25142. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25143. node = roughnessNode.mul( this.getTexture( scope ).g );
  25144. } else {
  25145. node = roughnessNode;
  25146. }
  25147. } else if ( scope === MaterialNode.METALNESS ) {
  25148. const metalnessNode = this.getFloat( scope );
  25149. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25150. node = metalnessNode.mul( this.getTexture( scope ).b );
  25151. } else {
  25152. node = metalnessNode;
  25153. }
  25154. } else if ( scope === MaterialNode.EMISSIVE ) {
  25155. const emissiveNode = this.getColor( scope );
  25156. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25157. node = emissiveNode.mul( this.getTexture( scope ) );
  25158. } else {
  25159. node = emissiveNode;
  25160. }
  25161. } else if ( scope === MaterialNode.NORMAL ) {
  25162. if ( material.normalMap ) {
  25163. node = this.getTexture( 'normal' ).normalMap( this.getCache( 'normalScale', 'vec2' ) );
  25164. } else if ( material.bumpMap ) {
  25165. node = this.getTexture( 'bump' ).r.bumpMap( this.getFloat( 'bumpScale' ) );
  25166. } else {
  25167. node = normalView;
  25168. }
  25169. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25170. const clearcoatNode = this.getFloat( scope );
  25171. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25172. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25173. } else {
  25174. node = clearcoatNode;
  25175. }
  25176. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25177. const clearcoatRoughnessNode = this.getFloat( scope );
  25178. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25179. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25180. } else {
  25181. node = clearcoatRoughnessNode;
  25182. }
  25183. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25184. if ( material.clearcoatNormalMap ) {
  25185. node = this.getTexture( scope ).normalMap( this.getCache( scope + 'Scale', 'vec2' ) );
  25186. } else {
  25187. node = normalView;
  25188. }
  25189. } else if ( scope === MaterialNode.SHEEN ) {
  25190. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25191. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25192. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25193. } else {
  25194. node = sheenNode;
  25195. }
  25196. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25197. const sheenRoughnessNode = this.getFloat( scope );
  25198. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25199. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25200. } else {
  25201. node = sheenRoughnessNode;
  25202. }
  25203. node = node.clamp( 0.07, 1.0 );
  25204. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25205. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25206. const anisotropyPolar = this.getTexture( scope );
  25207. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25208. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25209. } else {
  25210. node = materialAnisotropyVector;
  25211. }
  25212. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25213. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25214. if ( material.iridescenceThicknessMap ) {
  25215. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25216. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25217. } else {
  25218. node = iridescenceThicknessMaximum;
  25219. }
  25220. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25221. const transmissionNode = this.getFloat( scope );
  25222. if ( material.transmissionMap ) {
  25223. node = transmissionNode.mul( this.getTexture( scope ).r );
  25224. } else {
  25225. node = transmissionNode;
  25226. }
  25227. } else if ( scope === MaterialNode.THICKNESS ) {
  25228. const thicknessNode = this.getFloat( scope );
  25229. if ( material.thicknessMap ) {
  25230. node = thicknessNode.mul( this.getTexture( scope ).g );
  25231. } else {
  25232. node = thicknessNode;
  25233. }
  25234. } else if ( scope === MaterialNode.IOR ) {
  25235. node = this.getFloat( scope );
  25236. } else {
  25237. const outputType = this.getNodeType( builder );
  25238. node = this.getCache( scope, outputType );
  25239. }
  25240. return node;
  25241. }
  25242. }
  25243. MaterialNode.ALPHA_TEST = 'alphaTest';
  25244. MaterialNode.COLOR = 'color';
  25245. MaterialNode.OPACITY = 'opacity';
  25246. MaterialNode.SHININESS = 'shininess';
  25247. MaterialNode.SPECULAR = 'specular';
  25248. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25249. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25250. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25251. MaterialNode.REFLECTIVITY = 'reflectivity';
  25252. MaterialNode.ROUGHNESS = 'roughness';
  25253. MaterialNode.METALNESS = 'metalness';
  25254. MaterialNode.NORMAL = 'normal';
  25255. MaterialNode.CLEARCOAT = 'clearcoat';
  25256. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25257. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25258. MaterialNode.EMISSIVE = 'emissive';
  25259. MaterialNode.ROTATION = 'rotation';
  25260. MaterialNode.SHEEN = 'sheen';
  25261. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25262. MaterialNode.ANISOTROPY = 'anisotropy';
  25263. MaterialNode.IRIDESCENCE = 'iridescence';
  25264. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25265. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25266. MaterialNode.IOR = 'ior';
  25267. MaterialNode.TRANSMISSION = 'transmission';
  25268. MaterialNode.THICKNESS = 'thickness';
  25269. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25270. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25271. MaterialNode.LINE_SCALE = 'scale';
  25272. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25273. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25274. MaterialNode.LINE_WIDTH = 'linewidth';
  25275. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25276. MaterialNode.POINT_WIDTH = 'pointWidth';
  25277. MaterialNode.DISPERSION = 'dispersion';
  25278. const materialAlphaTest = nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25279. const materialColor = nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25280. const materialShininess = nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25281. const materialEmissive = nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25282. const materialOpacity = nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25283. const materialSpecular = nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25284. const materialSpecularIntensity = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25285. const materialSpecularColor = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25286. const materialSpecularStrength = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25287. const materialReflectivity = nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25288. const materialRoughness = nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25289. const materialMetalness = nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25290. const materialNormal = nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  25291. const materialClearcoat = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25292. const materialClearcoatRoughness = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25293. const materialClearcoatNormal = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  25294. const materialRotation = nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25295. const materialSheen = nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25296. const materialSheenRoughness = nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25297. const materialAnisotropy = nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25298. const materialIridescence = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25299. const materialIridescenceIOR = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25300. const materialIridescenceThickness = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25301. const materialTransmission = nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25302. const materialThickness = nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25303. const materialIOR = nodeImmutable( MaterialNode, MaterialNode.IOR );
  25304. const materialAttenuationDistance = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25305. const materialAttenuationColor = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25306. const materialLineScale = nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25307. const materialLineDashSize = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25308. const materialLineGapSize = nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25309. const materialLineWidth = nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25310. const materialLineDashOffset = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25311. const materialPointWidth = nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25312. const materialDispersion = nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25313. const materialAnisotropyVector = uniform( new Vector2() ).onReference( function ( frame ) {
  25314. return frame.material;
  25315. } ).onRenderUpdate( function ( { material } ) {
  25316. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25317. } );
  25318. addNodeClass( 'MaterialNode', MaterialNode );
  25319. const positionGeometry = /*#__PURE__*/ attribute( 'position', 'vec3' );
  25320. const positionLocal = /*#__PURE__*/ positionGeometry.toVar( 'positionLocal' );
  25321. const positionWorld = /*#__PURE__*/ varying( modelWorldMatrix.mul( positionLocal ).xyz, 'v_positionWorld' );
  25322. const positionWorldDirection = /*#__PURE__*/ varying( positionLocal.transformDirection( modelWorldMatrix ), 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  25323. const positionView = /*#__PURE__*/ varying( modelViewMatrix.mul( positionLocal ).xyz, 'v_positionView' );
  25324. const positionViewDirection = /*#__PURE__*/ varying( positionView.negate(), 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  25325. class ModelViewProjectionNode extends TempNode {
  25326. constructor( positionNode = null ) {
  25327. super( 'vec4' );
  25328. this.positionNode = positionNode;
  25329. }
  25330. setup( builder ) {
  25331. if ( builder.shaderStage === 'fragment' ) {
  25332. return varying( builder.context.mvp );
  25333. }
  25334. const position = this.positionNode || positionLocal;
  25335. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( position );
  25336. }
  25337. }
  25338. const modelViewProjection = nodeProxy( ModelViewProjectionNode );
  25339. addNodeClass( 'ModelViewProjectionNode', ModelViewProjectionNode );
  25340. class BufferAttributeNode extends InputNode {
  25341. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  25342. super( value, bufferType );
  25343. this.isBufferNode = true;
  25344. this.bufferType = bufferType;
  25345. this.bufferStride = bufferStride;
  25346. this.bufferOffset = bufferOffset;
  25347. this.usage = StaticDrawUsage;
  25348. this.instanced = false;
  25349. this.attribute = null;
  25350. this.global = true;
  25351. if ( value && value.isBufferAttribute === true ) {
  25352. this.attribute = value;
  25353. this.usage = value.usage;
  25354. this.instanced = value.isInstancedBufferAttribute;
  25355. }
  25356. }
  25357. getHash( builder ) {
  25358. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  25359. let bufferData = builder.globalCache.getData( this.value );
  25360. if ( bufferData === undefined ) {
  25361. bufferData = {
  25362. node: this
  25363. };
  25364. builder.globalCache.setData( this.value, bufferData );
  25365. }
  25366. return bufferData.node.uuid;
  25367. }
  25368. return this.uuid;
  25369. }
  25370. getNodeType( builder ) {
  25371. if ( this.bufferType === null ) {
  25372. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  25373. }
  25374. return this.bufferType;
  25375. }
  25376. setup( builder ) {
  25377. if ( this.attribute !== null ) return;
  25378. const type = this.getNodeType( builder );
  25379. const array = this.value;
  25380. const itemSize = builder.getTypeLength( type );
  25381. const stride = this.bufferStride || itemSize;
  25382. const offset = this.bufferOffset;
  25383. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  25384. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  25385. buffer.setUsage( this.usage );
  25386. this.attribute = bufferAttribute;
  25387. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  25388. }
  25389. generate( builder ) {
  25390. const nodeType = this.getNodeType( builder );
  25391. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  25392. const propertyName = builder.getPropertyName( nodeAttribute );
  25393. let output = null;
  25394. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25395. this.name = propertyName;
  25396. output = propertyName;
  25397. } else {
  25398. const nodeVarying = varying( this );
  25399. output = nodeVarying.build( builder, nodeType );
  25400. }
  25401. return output;
  25402. }
  25403. getInputType( /*builder*/ ) {
  25404. return 'bufferAttribute';
  25405. }
  25406. setUsage( value ) {
  25407. this.usage = value;
  25408. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  25409. this.attribute.usage = value;
  25410. }
  25411. return this;
  25412. }
  25413. setInstanced( value ) {
  25414. this.instanced = value;
  25415. return this;
  25416. }
  25417. }
  25418. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  25419. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  25420. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  25421. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  25422. addNodeElement( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  25423. addNodeClass( 'BufferAttributeNode', BufferAttributeNode );
  25424. class InstanceNode extends Node {
  25425. constructor( instanceMesh ) {
  25426. super( 'void' );
  25427. this.instanceMesh = instanceMesh;
  25428. this.instanceMatrixNode = null;
  25429. this.instanceColorNode = null;
  25430. this.updateType = NodeUpdateType.FRAME;
  25431. this.buffer = null;
  25432. this.bufferColor = null;
  25433. }
  25434. setup( /*builder*/ ) {
  25435. let instanceMatrixNode = this.instanceMatrixNode;
  25436. const instanceMesh = this.instanceMesh;
  25437. if ( instanceMatrixNode === null ) {
  25438. const instanceAttribute = instanceMesh.instanceMatrix;
  25439. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25440. this.buffer = buffer;
  25441. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25442. const instanceBuffers = [
  25443. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25444. bufferFn( buffer, 'vec4', 16, 0 ),
  25445. bufferFn( buffer, 'vec4', 16, 4 ),
  25446. bufferFn( buffer, 'vec4', 16, 8 ),
  25447. bufferFn( buffer, 'vec4', 16, 12 )
  25448. ];
  25449. instanceMatrixNode = mat4( ...instanceBuffers );
  25450. this.instanceMatrixNode = instanceMatrixNode;
  25451. }
  25452. const instanceColorAttribute = instanceMesh.instanceColor;
  25453. if ( instanceColorAttribute && this.instanceColorNode === null ) {
  25454. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25455. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25456. this.bufferColor = buffer;
  25457. this.instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25458. }
  25459. // POSITION
  25460. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25461. // NORMAL
  25462. const m = mat3( instanceMatrixNode[ 0 ].xyz, instanceMatrixNode[ 1 ].xyz, instanceMatrixNode[ 2 ].xyz );
  25463. const transformedNormal = normalLocal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  25464. const instanceNormal = m.mul( transformedNormal ).xyz;
  25465. // ASSIGNS
  25466. positionLocal.assign( instancePosition );
  25467. normalLocal.assign( instanceNormal );
  25468. // COLOR
  25469. if ( this.instanceColorNode !== null ) {
  25470. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25471. }
  25472. }
  25473. update( /*frame*/ ) {
  25474. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25475. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25476. }
  25477. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25478. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25479. }
  25480. }
  25481. }
  25482. const instance = nodeProxy( InstanceNode );
  25483. addNodeClass( 'InstanceNode', InstanceNode );
  25484. const tangentGeometry = /*#__PURE__*/ tslFn( ( stack, builder ) => {
  25485. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25486. builder.geometry.computeTangents();
  25487. }
  25488. return attribute( 'tangent', 'vec4' );
  25489. } )();
  25490. const tangentLocal = /*#__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25491. const tangentView = /*#__PURE__*/ varying( modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz, 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25492. const tangentWorld = /*#__PURE__*/ varying( tangentView.transformDirection( cameraViewMatrix ), 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25493. const transformedTangentView = /*#__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25494. const transformedTangentWorld = /*#__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25495. class BatchNode extends Node {
  25496. constructor( batchMesh ) {
  25497. super( 'void' );
  25498. this.batchMesh = batchMesh;
  25499. this.instanceColorNode = null;
  25500. this.batchingIdNode = null;
  25501. }
  25502. setup( builder ) {
  25503. // POSITION
  25504. if ( this.batchingIdNode === null ) {
  25505. if ( builder.getDrawIndex() === null ) {
  25506. this.batchingIdNode = instanceIndex;
  25507. } else {
  25508. this.batchingIdNode = drawIndex;
  25509. }
  25510. }
  25511. const getIndirectIndex = tslFn( ( [ id ] ) => {
  25512. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25513. const x = int( id ).remainder( int( size ) );
  25514. const y = int( id ).div( int( size ) );
  25515. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25516. } ).setLayout( {
  25517. name: 'getIndirectIndex',
  25518. type: 'uint',
  25519. inputs: [
  25520. { name: 'id', type: 'int' }
  25521. ]
  25522. } );
  25523. const matriceTexture = this.batchMesh._matricesTexture;
  25524. const size = textureSize( textureLoad( matriceTexture ), 0 );
  25525. const j = float( getIndirectIndex( int( this.batchingIdNode ) ) ).mul( 4 ).toVar();
  25526. const x = int( j.mod( size ) );
  25527. const y = int( j ).div( int( size ) );
  25528. const batchingMatrix = mat4(
  25529. textureLoad( matriceTexture, ivec2( x, y ) ),
  25530. textureLoad( matriceTexture, ivec2( x.add( 1 ), y ) ),
  25531. textureLoad( matriceTexture, ivec2( x.add( 2 ), y ) ),
  25532. textureLoad( matriceTexture, ivec2( x.add( 3 ), y ) )
  25533. );
  25534. const bm = mat3(
  25535. batchingMatrix[ 0 ].xyz,
  25536. batchingMatrix[ 1 ].xyz,
  25537. batchingMatrix[ 2 ].xyz
  25538. );
  25539. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25540. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25541. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25542. normalLocal.assign( batchingNormal );
  25543. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25544. tangentLocal.mulAssign( bm );
  25545. }
  25546. }
  25547. }
  25548. const batch = nodeProxy( BatchNode );
  25549. addNodeClass( 'batch', BatchNode );
  25550. class SkinningNode extends Node {
  25551. constructor( skinnedMesh, useReference = false ) {
  25552. super( 'void' );
  25553. this.skinnedMesh = skinnedMesh;
  25554. this.useReference = useReference;
  25555. this.updateType = NodeUpdateType.OBJECT;
  25556. //
  25557. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25558. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25559. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25560. if ( useReference ) {
  25561. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25562. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25563. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25564. } else {
  25565. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25566. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25567. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25568. }
  25569. this.bindMatrixNode = bindMatrixNode;
  25570. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25571. this.boneMatricesNode = boneMatricesNode;
  25572. }
  25573. setup( builder ) {
  25574. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode, boneMatricesNode } = this;
  25575. const boneMatX = boneMatricesNode.element( skinIndexNode.x );
  25576. const boneMatY = boneMatricesNode.element( skinIndexNode.y );
  25577. const boneMatZ = boneMatricesNode.element( skinIndexNode.z );
  25578. const boneMatW = boneMatricesNode.element( skinIndexNode.w );
  25579. // POSITION
  25580. const skinVertex = bindMatrixNode.mul( positionLocal );
  25581. const skinned = add(
  25582. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25583. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25584. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25585. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25586. );
  25587. const skinPosition = bindMatrixInverseNode.mul( skinned ).xyz;
  25588. // NORMAL
  25589. let skinMatrix = add(
  25590. skinWeightNode.x.mul( boneMatX ),
  25591. skinWeightNode.y.mul( boneMatY ),
  25592. skinWeightNode.z.mul( boneMatZ ),
  25593. skinWeightNode.w.mul( boneMatW )
  25594. );
  25595. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25596. const skinNormal = skinMatrix.transformDirection( normalLocal ).xyz;
  25597. // ASSIGNS
  25598. positionLocal.assign( skinPosition );
  25599. normalLocal.assign( skinNormal );
  25600. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25601. tangentLocal.assign( skinNormal );
  25602. }
  25603. }
  25604. generate( builder, output ) {
  25605. if ( output !== 'void' ) {
  25606. return positionLocal.build( builder, output );
  25607. }
  25608. }
  25609. update( frame ) {
  25610. const object = this.useReference ? frame.object : this.skinnedMesh;
  25611. object.skeleton.update();
  25612. }
  25613. }
  25614. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25615. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25616. addNodeClass( 'SkinningNode', SkinningNode );
  25617. class LoopNode extends Node {
  25618. constructor( params = [] ) {
  25619. super();
  25620. this.params = params;
  25621. }
  25622. getVarName( index ) {
  25623. return String.fromCharCode( 'i'.charCodeAt() + index );
  25624. }
  25625. getProperties( builder ) {
  25626. const properties = builder.getNodeProperties( this );
  25627. if ( properties.stackNode !== undefined ) return properties;
  25628. //
  25629. const inputs = {};
  25630. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25631. const param = this.params[ i ];
  25632. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25633. const type = ( param.isNode !== true && param.type ) || 'int';
  25634. inputs[ name ] = expression( name, type );
  25635. }
  25636. const stack = builder.addStack(); // TODO: cache() it
  25637. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25638. properties.stackNode = stack;
  25639. builder.removeStack();
  25640. return properties;
  25641. }
  25642. getNodeType( builder ) {
  25643. const { returnsNode } = this.getProperties( builder );
  25644. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25645. }
  25646. setup( builder ) {
  25647. // setup properties
  25648. this.getProperties( builder );
  25649. }
  25650. generate( builder ) {
  25651. const properties = this.getProperties( builder );
  25652. const params = this.params;
  25653. const stackNode = properties.stackNode;
  25654. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25655. const param = params[ i ];
  25656. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25657. if ( param.isNode ) {
  25658. type = 'int';
  25659. name = this.getVarName( i );
  25660. start = '0';
  25661. end = param.build( builder, type );
  25662. condition = '<';
  25663. } else {
  25664. type = param.type || 'int';
  25665. name = param.name || this.getVarName( i );
  25666. start = param.start;
  25667. end = param.end;
  25668. condition = param.condition;
  25669. update = param.update;
  25670. if ( typeof start === 'number' ) start = start.toString();
  25671. else if ( start && start.isNode ) start = start.build( builder, type );
  25672. if ( typeof end === 'number' ) end = end.toString();
  25673. else if ( end && end.isNode ) end = end.build( builder, type );
  25674. if ( start !== undefined && end === undefined ) {
  25675. start = start + ' - 1';
  25676. end = '0';
  25677. condition = '>=';
  25678. } else if ( end !== undefined && start === undefined ) {
  25679. start = '0';
  25680. condition = '<';
  25681. }
  25682. if ( condition === undefined ) {
  25683. if ( Number( start ) > Number( end ) ) {
  25684. condition = '>=';
  25685. } else {
  25686. condition = '<';
  25687. }
  25688. }
  25689. }
  25690. const internalParam = { start, end, condition };
  25691. //
  25692. const startSnippet = internalParam.start;
  25693. const endSnippet = internalParam.end;
  25694. let declarationSnippet = '';
  25695. let conditionalSnippet = '';
  25696. let updateSnippet = '';
  25697. if ( ! update ) {
  25698. if ( type === 'int' || type === 'uint' ) {
  25699. if ( condition.includes( '<' ) ) update = '++';
  25700. else update = '--';
  25701. } else {
  25702. if ( condition.includes( '<' ) ) update = '+= 1.';
  25703. else update = '-= 1.';
  25704. }
  25705. }
  25706. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25707. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25708. updateSnippet += name + ' ' + update;
  25709. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25710. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25711. }
  25712. const stackSnippet = stackNode.build( builder, 'void' );
  25713. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25714. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25715. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25716. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25717. }
  25718. builder.addFlowTab();
  25719. return returnsSnippet;
  25720. }
  25721. }
  25722. const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25723. const Continue = () => expression( 'continue' ).append();
  25724. const Break = () => expression( 'break' ).append();
  25725. addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) );
  25726. addNodeClass( 'LoopNode', LoopNode );
  25727. const morphTextures = new WeakMap();
  25728. const morphVec4 = new Vector4();
  25729. const getMorph = tslFn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25730. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25731. const y = texelIndex.div( width );
  25732. const x = texelIndex.sub( y.mul( width ) );
  25733. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25734. return bufferAttrib.mul( influence );
  25735. } );
  25736. function getEntry( geometry ) {
  25737. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25738. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25739. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25740. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25741. // into an array of data textures. Each layer represents a single morph target.
  25742. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25743. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25744. let entry = morphTextures.get( geometry );
  25745. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25746. if ( entry !== undefined ) entry.texture.dispose();
  25747. const morphTargets = geometry.morphAttributes.position || [];
  25748. const morphNormals = geometry.morphAttributes.normal || [];
  25749. const morphColors = geometry.morphAttributes.color || [];
  25750. let vertexDataCount = 0;
  25751. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25752. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25753. if ( hasMorphColors === true ) vertexDataCount = 3;
  25754. let width = geometry.attributes.position.count * vertexDataCount;
  25755. let height = 1;
  25756. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25757. if ( width > maxTextureSize ) {
  25758. height = Math.ceil( width / maxTextureSize );
  25759. width = maxTextureSize;
  25760. }
  25761. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25762. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25763. bufferTexture.type = FloatType;
  25764. bufferTexture.needsUpdate = true;
  25765. // fill buffer
  25766. const vertexDataStride = vertexDataCount * 4;
  25767. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25768. const morphTarget = morphTargets[ i ];
  25769. const morphNormal = morphNormals[ i ];
  25770. const morphColor = morphColors[ i ];
  25771. const offset = width * height * 4 * i;
  25772. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25773. const stride = j * vertexDataStride;
  25774. if ( hasMorphPosition === true ) {
  25775. morphVec4.fromBufferAttribute( morphTarget, j );
  25776. buffer[ offset + stride + 0 ] = morphVec4.x;
  25777. buffer[ offset + stride + 1 ] = morphVec4.y;
  25778. buffer[ offset + stride + 2 ] = morphVec4.z;
  25779. buffer[ offset + stride + 3 ] = 0;
  25780. }
  25781. if ( hasMorphNormals === true ) {
  25782. morphVec4.fromBufferAttribute( morphNormal, j );
  25783. buffer[ offset + stride + 4 ] = morphVec4.x;
  25784. buffer[ offset + stride + 5 ] = morphVec4.y;
  25785. buffer[ offset + stride + 6 ] = morphVec4.z;
  25786. buffer[ offset + stride + 7 ] = 0;
  25787. }
  25788. if ( hasMorphColors === true ) {
  25789. morphVec4.fromBufferAttribute( morphColor, j );
  25790. buffer[ offset + stride + 8 ] = morphVec4.x;
  25791. buffer[ offset + stride + 9 ] = morphVec4.y;
  25792. buffer[ offset + stride + 10 ] = morphVec4.z;
  25793. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morphVec4.w : 1;
  25794. }
  25795. }
  25796. }
  25797. entry = {
  25798. count: morphTargetsCount,
  25799. texture: bufferTexture,
  25800. stride: vertexDataCount,
  25801. size: new Vector2( width, height )
  25802. };
  25803. morphTextures.set( geometry, entry );
  25804. function disposeTexture() {
  25805. bufferTexture.dispose();
  25806. morphTextures.delete( geometry );
  25807. geometry.removeEventListener( 'dispose', disposeTexture );
  25808. }
  25809. geometry.addEventListener( 'dispose', disposeTexture );
  25810. }
  25811. return entry;
  25812. }
  25813. class MorphNode extends Node {
  25814. constructor( mesh ) {
  25815. super( 'void' );
  25816. this.mesh = mesh;
  25817. this.morphBaseInfluence = uniform( 1 );
  25818. this.updateType = NodeUpdateType.OBJECT;
  25819. }
  25820. setup( builder ) {
  25821. const { geometry } = builder;
  25822. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25823. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25824. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25825. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25826. // nodes
  25827. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25828. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25829. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25830. const width = int( size.width );
  25831. loop( morphTargetsCount, ( { i } ) => {
  25832. const influence = float( 0 ).toVar();
  25833. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25834. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25835. } else {
  25836. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25837. }
  25838. if ( hasMorphPosition === true ) {
  25839. positionLocal.addAssign( getMorph( {
  25840. bufferMap,
  25841. influence,
  25842. stride,
  25843. width,
  25844. depth: i,
  25845. offset: int( 0 )
  25846. } ) );
  25847. }
  25848. if ( hasMorphNormals === true ) {
  25849. normalLocal.addAssign( getMorph( {
  25850. bufferMap,
  25851. influence,
  25852. stride,
  25853. width,
  25854. depth: i,
  25855. offset: int( 1 )
  25856. } ) );
  25857. }
  25858. } );
  25859. }
  25860. update() {
  25861. const morphBaseInfluence = this.morphBaseInfluence;
  25862. if ( this.mesh.geometry.morphTargetsRelative ) {
  25863. morphBaseInfluence.value = 1;
  25864. } else {
  25865. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25866. }
  25867. }
  25868. }
  25869. const morphReference = nodeProxy( MorphNode );
  25870. addNodeClass( 'MorphNode', MorphNode );
  25871. const reflectView = /*#__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  25872. const reflectVector = /*#__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25873. class CubeTextureNode extends TextureNode {
  25874. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  25875. super( value, uvNode, levelNode, biasNode );
  25876. this.isCubeTextureNode = true;
  25877. }
  25878. getInputType( /*builder*/ ) {
  25879. return 'cubeTexture';
  25880. }
  25881. getDefaultUV() {
  25882. return reflectVector;
  25883. }
  25884. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  25885. setupUV( builder, uvNode ) {
  25886. const texture = this.value;
  25887. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  25888. return vec3( uvNode.x.negate(), uvNode.yz );
  25889. } else {
  25890. return uvNode;
  25891. }
  25892. }
  25893. generateUV( builder, cubeUV ) {
  25894. return cubeUV.build( builder, 'vec3' );
  25895. }
  25896. }
  25897. const cubeTexture = nodeProxy( CubeTextureNode );
  25898. addNodeElement( 'cubeTexture', cubeTexture );
  25899. addNodeClass( 'CubeTextureNode', CubeTextureNode );
  25900. class LightingNode extends Node {
  25901. constructor() {
  25902. super( 'vec3' );
  25903. this.isLightingNode = true;
  25904. }
  25905. generate( /*builder*/ ) {
  25906. console.warn( 'Abstract function.' );
  25907. }
  25908. }
  25909. addNodeClass( 'LightingNode', LightingNode );
  25910. let overrideMaterial = null;
  25911. class AnalyticLightNode extends LightingNode {
  25912. constructor( light = null ) {
  25913. super();
  25914. this.updateType = NodeUpdateType.FRAME;
  25915. this.light = light;
  25916. this.rtt = null;
  25917. this.shadowNode = null;
  25918. this.shadowMaskNode = null;
  25919. this.color = new Color();
  25920. this._defaultColorNode = uniform( this.color );
  25921. this.colorNode = this._defaultColorNode;
  25922. this.isAnalyticLightNode = true;
  25923. }
  25924. getCacheKey() {
  25925. return super.getCacheKey() + '-' + ( this.light.id + '-' + ( this.light.castShadow ? '1' : '0' ) );
  25926. }
  25927. getHash() {
  25928. return this.light.uuid;
  25929. }
  25930. setupShadow( builder ) {
  25931. const { object } = builder;
  25932. if ( object.receiveShadow === false ) return;
  25933. let shadowNode = this.shadowNode;
  25934. if ( shadowNode === null ) {
  25935. if ( overrideMaterial === null ) {
  25936. overrideMaterial = builder.createNodeMaterial();
  25937. overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  25938. overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  25939. }
  25940. const shadow = this.light.shadow;
  25941. const rtt = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25942. const depthTexture = new DepthTexture();
  25943. depthTexture.minFilter = NearestFilter;
  25944. depthTexture.magFilter = NearestFilter;
  25945. depthTexture.image.width = shadow.mapSize.width;
  25946. depthTexture.image.height = shadow.mapSize.height;
  25947. depthTexture.compareFunction = LessCompare;
  25948. rtt.depthTexture = depthTexture;
  25949. shadow.camera.updateProjectionMatrix();
  25950. //
  25951. const shadowIntensity = reference( 'intensity', 'float', shadow );
  25952. const bias = reference( 'bias', 'float', shadow );
  25953. const normalBias = reference( 'normalBias', 'float', shadow );
  25954. const position = object.material.shadowPositionNode || positionWorld;
  25955. let shadowCoord = uniform( shadow.matrix ).mul( position.add( normalWorld.mul( normalBias ) ) );
  25956. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25957. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25958. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25959. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25960. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25961. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25962. let coordZ = shadowCoord.z.add( bias );
  25963. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25964. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  25965. }
  25966. shadowCoord = vec3(
  25967. shadowCoord.x,
  25968. shadowCoord.y.oneMinus(), // follow webgpu standards
  25969. coordZ
  25970. );
  25971. const textureCompare = ( depthTexture, shadowCoord, compare ) => texture( depthTexture, shadowCoord ).compare( compare );
  25972. //const textureCompare = ( depthTexture, shadowCoord, compare ) => compare.step( texture( depthTexture, shadowCoord ) );
  25973. // BasicShadowMap
  25974. shadowNode = textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z );
  25975. // PCFShadowMap
  25976. /*
  25977. const mapSize = reference( 'mapSize', 'vec2', shadow );
  25978. const radius = reference( 'radius', 'float', shadow );
  25979. const texelSize = vec2( 1 ).div( mapSize );
  25980. const dx0 = texelSize.x.negate().mul( radius );
  25981. const dy0 = texelSize.y.negate().mul( radius );
  25982. const dx1 = texelSize.x.mul( radius );
  25983. const dy1 = texelSize.y.mul( radius );
  25984. const dx2 = dx0.mul( 2 );
  25985. const dy2 = dy0.mul( 2 );
  25986. const dx3 = dx1.mul( 2 );
  25987. const dy3 = dy1.mul( 2 );
  25988. shadowNode = add(
  25989. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25990. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25991. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25992. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25993. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25994. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25995. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25996. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25997. textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z ),
  25998. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25999. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  26000. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  26001. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  26002. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  26003. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  26004. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  26005. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  26006. ).mul( 1 / 17 );
  26007. */
  26008. //
  26009. const shadowColor = texture( rtt.texture, shadowCoord );
  26010. const shadowMaskNode = frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) );
  26011. this.rtt = rtt;
  26012. this.colorNode = this.colorNode.mul( mix( 1, shadowMaskNode, shadowIntensity ) );
  26013. this.shadowNode = shadowNode;
  26014. this.shadowMaskNode = shadowMaskNode;
  26015. //
  26016. this.updateBeforeType = NodeUpdateType.RENDER;
  26017. }
  26018. }
  26019. setup( builder ) {
  26020. if ( this.light.castShadow ) this.setupShadow( builder );
  26021. else if ( this.shadowNode !== null ) this.disposeShadow();
  26022. }
  26023. updateShadow( frame ) {
  26024. const { rtt, light } = this;
  26025. const { renderer, scene, camera } = frame;
  26026. const currentOverrideMaterial = scene.overrideMaterial;
  26027. scene.overrideMaterial = overrideMaterial;
  26028. rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  26029. light.shadow.updateMatrices( light );
  26030. light.shadow.camera.layers.mask = camera.layers.mask;
  26031. const currentToneMapping = renderer.toneMapping;
  26032. const currentRenderTarget = renderer.getRenderTarget();
  26033. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26034. renderer.setRenderObjectFunction( ( object, ...params ) => {
  26035. if ( object.castShadow === true ) {
  26036. renderer.renderObject( object, ...params );
  26037. }
  26038. } );
  26039. renderer.setRenderTarget( rtt );
  26040. renderer.toneMapping = NoToneMapping;
  26041. renderer.render( scene, light.shadow.camera );
  26042. renderer.setRenderTarget( currentRenderTarget );
  26043. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26044. renderer.toneMapping = currentToneMapping;
  26045. scene.overrideMaterial = currentOverrideMaterial;
  26046. }
  26047. disposeShadow() {
  26048. this.rtt.dispose();
  26049. this.shadowNode = null;
  26050. this.shadowMaskNode = null;
  26051. this.rtt = null;
  26052. this.colorNode = this._defaultColorNode;
  26053. }
  26054. updateBefore( frame ) {
  26055. const { light } = this;
  26056. if ( light.castShadow ) this.updateShadow( frame );
  26057. }
  26058. update( /*frame*/ ) {
  26059. const { light } = this;
  26060. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26061. }
  26062. }
  26063. addNodeClass( 'AnalyticLightNode', AnalyticLightNode );
  26064. const LightNodes = new WeakMap();
  26065. const sortLights = ( lights ) => {
  26066. return lights.sort( ( a, b ) => a.id - b.id );
  26067. };
  26068. class LightsNode extends Node {
  26069. constructor( lightNodes = [] ) {
  26070. super( 'vec3' );
  26071. this.totalDiffuseNode = vec3().temp( 'totalDiffuse' );
  26072. this.totalSpecularNode = vec3().temp( 'totalSpecular' );
  26073. this.outgoingLightNode = vec3().temp( 'outgoingLight' );
  26074. this.lightNodes = lightNodes;
  26075. this._hash = null;
  26076. }
  26077. get hasLight() {
  26078. return this.lightNodes.length > 0;
  26079. }
  26080. getHash() {
  26081. if ( this._hash === null ) {
  26082. const hash = [];
  26083. for ( const lightNode of this.lightNodes ) {
  26084. hash.push( lightNode.getHash() );
  26085. }
  26086. this._hash = 'lights-' + hash.join( ',' );
  26087. }
  26088. return this._hash;
  26089. }
  26090. analyze( builder ) {
  26091. const properties = builder.getDataFromNode( this );
  26092. for ( const node of properties.nodes ) {
  26093. node.build( builder );
  26094. }
  26095. }
  26096. setup( builder ) {
  26097. const context = builder.context;
  26098. const lightingModel = context.lightingModel;
  26099. let outgoingLightNode = this.outgoingLightNode;
  26100. if ( lightingModel ) {
  26101. const { lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  26102. context.outgoingLight = outgoingLightNode;
  26103. const stack = builder.addStack();
  26104. //
  26105. const properties = builder.getDataFromNode( this );
  26106. properties.nodes = stack.nodes;
  26107. //
  26108. lightingModel.start( context, stack, builder );
  26109. // lights
  26110. for ( const lightNode of lightNodes ) {
  26111. lightNode.build( builder );
  26112. }
  26113. //
  26114. lightingModel.indirectDiffuse( context, stack, builder );
  26115. lightingModel.indirectSpecular( context, stack, builder );
  26116. lightingModel.ambientOcclusion( context, stack, builder );
  26117. //
  26118. const { backdrop, backdropAlpha } = context;
  26119. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26120. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26121. if ( backdrop !== null ) {
  26122. if ( backdropAlpha !== null ) {
  26123. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26124. } else {
  26125. totalDiffuse = vec3( backdrop );
  26126. }
  26127. context.material.transparent = true;
  26128. }
  26129. totalDiffuseNode.assign( totalDiffuse );
  26130. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26131. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26132. //
  26133. lightingModel.finish( context, stack, builder );
  26134. //
  26135. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26136. }
  26137. return outgoingLightNode;
  26138. }
  26139. _getLightNodeById( id ) {
  26140. for ( const lightNode of this.lightNodes ) {
  26141. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26142. return lightNode;
  26143. }
  26144. }
  26145. return null;
  26146. }
  26147. fromLights( lights = [] ) {
  26148. const lightNodes = [];
  26149. lights = sortLights( lights );
  26150. for ( const light of lights ) {
  26151. let lightNode = this._getLightNodeById( light.id );
  26152. if ( lightNode === null ) {
  26153. const lightClass = light.constructor;
  26154. const lightNodeClass = LightNodes.has( lightClass ) ? LightNodes.get( lightClass ) : AnalyticLightNode;
  26155. lightNode = nodeObject( new lightNodeClass( light ) );
  26156. }
  26157. lightNodes.push( lightNode );
  26158. }
  26159. this.lightNodes = lightNodes;
  26160. this._hash = null;
  26161. return this;
  26162. }
  26163. }
  26164. const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) );
  26165. const lightsNode = nodeProxy( LightsNode );
  26166. function addLightNode( lightClass, lightNodeClass ) {
  26167. if ( LightNodes.has( lightClass ) ) {
  26168. console.warn( `Redefinition of light node ${ lightNodeClass.type }` );
  26169. return;
  26170. }
  26171. if ( typeof lightClass !== 'function' ) throw new Error( `Light ${ lightClass.name } is not a class` );
  26172. if ( typeof lightNodeClass !== 'function' || ! lightNodeClass.type ) throw new Error( `Light node ${ lightNodeClass.type } is not a class` );
  26173. LightNodes.set( lightClass, lightNodeClass );
  26174. }
  26175. class AONode extends LightingNode {
  26176. constructor( aoNode = null ) {
  26177. super();
  26178. this.aoNode = aoNode;
  26179. }
  26180. setup( builder ) {
  26181. const aoIntensity = 1;
  26182. const aoNode = this.aoNode.x.sub( 1.0 ).mul( aoIntensity ).add( 1.0 );
  26183. builder.context.ambientOcclusion.mulAssign( aoNode );
  26184. }
  26185. }
  26186. addNodeClass( 'AONode', AONode );
  26187. class LightingContextNode extends ContextNode {
  26188. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26189. super( node );
  26190. this.lightingModel = lightingModel;
  26191. this.backdropNode = backdropNode;
  26192. this.backdropAlphaNode = backdropAlphaNode;
  26193. this._context = null;
  26194. }
  26195. getContext() {
  26196. const { backdropNode, backdropAlphaNode } = this;
  26197. const directDiffuse = vec3().temp( 'directDiffuse' ),
  26198. directSpecular = vec3().temp( 'directSpecular' ),
  26199. indirectDiffuse = vec3().temp( 'indirectDiffuse' ),
  26200. indirectSpecular = vec3().temp( 'indirectSpecular' );
  26201. const reflectedLight = {
  26202. directDiffuse,
  26203. directSpecular,
  26204. indirectDiffuse,
  26205. indirectSpecular
  26206. };
  26207. const context = {
  26208. radiance: vec3().temp( 'radiance' ),
  26209. irradiance: vec3().temp( 'irradiance' ),
  26210. iblIrradiance: vec3().temp( 'iblIrradiance' ),
  26211. ambientOcclusion: float( 1 ).temp( 'ambientOcclusion' ),
  26212. reflectedLight,
  26213. backdrop: backdropNode,
  26214. backdropAlpha: backdropAlphaNode
  26215. };
  26216. return context;
  26217. }
  26218. setup( builder ) {
  26219. this.context = this._context || ( this._context = this.getContext() );
  26220. this.context.lightingModel = this.lightingModel || builder.context.lightingModel;
  26221. return super.setup( builder );
  26222. }
  26223. }
  26224. const lightingContext = nodeProxy( LightingContextNode );
  26225. addNodeElement( 'lightingContext', lightingContext );
  26226. addNodeClass( 'LightingContextNode', LightingContextNode );
  26227. class IrradianceNode extends LightingNode {
  26228. constructor( node ) {
  26229. super();
  26230. this.node = node;
  26231. }
  26232. setup( builder ) {
  26233. builder.context.irradiance.addAssign( this.node );
  26234. }
  26235. }
  26236. addNodeClass( 'IrradianceNode', IrradianceNode );
  26237. let resolution, viewportResult;
  26238. class ViewportNode extends Node {
  26239. constructor( scope ) {
  26240. super();
  26241. this.scope = scope;
  26242. this.isViewportNode = true;
  26243. }
  26244. getNodeType() {
  26245. if ( this.scope === ViewportNode.VIEWPORT ) return 'vec4';
  26246. else if ( this.scope === ViewportNode.COORDINATE ) return 'vec3';
  26247. else return 'vec2';
  26248. }
  26249. getUpdateType() {
  26250. let updateType = NodeUpdateType.NONE;
  26251. if ( this.scope === ViewportNode.RESOLUTION || this.scope === ViewportNode.VIEWPORT ) {
  26252. updateType = NodeUpdateType.RENDER;
  26253. }
  26254. this.updateType = updateType;
  26255. return updateType;
  26256. }
  26257. update( { renderer } ) {
  26258. if ( this.scope === ViewportNode.VIEWPORT ) {
  26259. renderer.getViewport( viewportResult );
  26260. } else {
  26261. renderer.getDrawingBufferSize( resolution );
  26262. }
  26263. }
  26264. setup( /*builder*/ ) {
  26265. const scope = this.scope;
  26266. let output = null;
  26267. if ( scope === ViewportNode.RESOLUTION ) {
  26268. output = uniform( resolution || ( resolution = new Vector2() ) );
  26269. } else if ( scope === ViewportNode.VIEWPORT ) {
  26270. output = uniform( viewportResult || ( viewportResult = new Vector4() ) );
  26271. } else {
  26272. output = viewportCoordinate.div( viewportResolution );
  26273. let outX = output.x;
  26274. let outY = output.y;
  26275. if ( /bottom/i.test( scope ) ) outY = outY.oneMinus();
  26276. if ( /right/i.test( scope ) ) outX = outX.oneMinus();
  26277. output = vec2( outX, outY );
  26278. }
  26279. return output;
  26280. }
  26281. generate( builder ) {
  26282. if ( this.scope === ViewportNode.COORDINATE ) {
  26283. let coord = builder.getFragCoord();
  26284. if ( builder.isFlipY() ) {
  26285. // follow webgpu standards
  26286. const resolution = builder.getNodeProperties( viewportResolution ).outputNode.build( builder );
  26287. coord = `${ builder.getType( 'vec3' ) }( ${ coord }.x, ${ resolution }.y - ${ coord }.y, ${ coord }.z )`;
  26288. }
  26289. return coord;
  26290. }
  26291. return super.generate( builder );
  26292. }
  26293. }
  26294. ViewportNode.COORDINATE = 'coordinate';
  26295. ViewportNode.RESOLUTION = 'resolution';
  26296. ViewportNode.VIEWPORT = 'viewport';
  26297. ViewportNode.TOP_LEFT = 'topLeft';
  26298. ViewportNode.BOTTOM_LEFT = 'bottomLeft';
  26299. ViewportNode.TOP_RIGHT = 'topRight';
  26300. ViewportNode.BOTTOM_RIGHT = 'bottomRight';
  26301. const viewportCoordinate = nodeImmutable( ViewportNode, ViewportNode.COORDINATE );
  26302. const viewportResolution = nodeImmutable( ViewportNode, ViewportNode.RESOLUTION );
  26303. const viewport = nodeImmutable( ViewportNode, ViewportNode.VIEWPORT );
  26304. const viewportTopLeft = nodeImmutable( ViewportNode, ViewportNode.TOP_LEFT );
  26305. const viewportBottomLeft = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_LEFT );
  26306. const viewportTopRight = nodeImmutable( ViewportNode, ViewportNode.TOP_RIGHT );
  26307. const viewportBottomRight = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_RIGHT );
  26308. addNodeClass( 'ViewportNode', ViewportNode );
  26309. const _size$5 = new Vector2();
  26310. class ViewportTextureNode extends TextureNode {
  26311. constructor( uvNode = viewportTopLeft, levelNode = null, framebufferTexture = null ) {
  26312. if ( framebufferTexture === null ) {
  26313. framebufferTexture = new FramebufferTexture();
  26314. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26315. }
  26316. super( framebufferTexture, uvNode, levelNode );
  26317. this.generateMipmaps = false;
  26318. this.isOutputTextureNode = true;
  26319. this.updateBeforeType = NodeUpdateType.FRAME;
  26320. }
  26321. updateBefore( frame ) {
  26322. const renderer = frame.renderer;
  26323. renderer.getDrawingBufferSize( _size$5 );
  26324. //
  26325. const framebufferTexture = this.value;
  26326. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  26327. framebufferTexture.image.width = _size$5.width;
  26328. framebufferTexture.image.height = _size$5.height;
  26329. framebufferTexture.needsUpdate = true;
  26330. }
  26331. //
  26332. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26333. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26334. renderer.copyFramebufferToTexture( framebufferTexture );
  26335. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26336. }
  26337. clone() {
  26338. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26339. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26340. return viewportTextureNode;
  26341. }
  26342. }
  26343. const viewportTexture = nodeProxy( ViewportTextureNode );
  26344. const viewportMipTexture = nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26345. addNodeElement( 'viewportTexture', viewportTexture );
  26346. addNodeElement( 'viewportMipTexture', viewportMipTexture );
  26347. addNodeClass( 'ViewportTextureNode', ViewportTextureNode );
  26348. let sharedDepthbuffer = null;
  26349. class ViewportDepthTextureNode extends ViewportTextureNode {
  26350. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  26351. if ( sharedDepthbuffer === null ) {
  26352. sharedDepthbuffer = new DepthTexture();
  26353. }
  26354. super( uvNode, levelNode, sharedDepthbuffer );
  26355. }
  26356. }
  26357. const viewportDepthTexture = nodeProxy( ViewportDepthTextureNode );
  26358. addNodeElement( 'viewportDepthTexture', viewportDepthTexture );
  26359. addNodeClass( 'ViewportDepthTextureNode', ViewportDepthTextureNode );
  26360. class ViewportDepthNode extends Node {
  26361. constructor( scope, valueNode = null ) {
  26362. super( 'float' );
  26363. this.scope = scope;
  26364. this.valueNode = valueNode;
  26365. this.isViewportDepthNode = true;
  26366. }
  26367. generate( builder ) {
  26368. const { scope } = this;
  26369. if ( scope === ViewportDepthNode.DEPTH ) {
  26370. return builder.getFragDepth();
  26371. }
  26372. return super.generate( builder );
  26373. }
  26374. setup( { camera } ) {
  26375. const { scope } = this;
  26376. const texture = this.valueNode;
  26377. let node = null;
  26378. if ( scope === ViewportDepthNode.DEPTH ) {
  26379. if ( texture !== null ) {
  26380. node = depthBase().assign( texture );
  26381. } else {
  26382. if ( camera.isPerspectiveCamera ) {
  26383. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26384. } else {
  26385. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26386. }
  26387. }
  26388. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26389. if ( texture !== null ) {
  26390. if ( camera.isPerspectiveCamera ) {
  26391. const viewZ = perspectiveDepthToViewZ( texture, cameraNear, cameraFar );
  26392. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26393. } else {
  26394. node = texture;
  26395. }
  26396. } else {
  26397. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26398. }
  26399. }
  26400. return node;
  26401. }
  26402. }
  26403. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26404. // -near maps to 0; -far maps to 1
  26405. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26406. // maps orthographic depth in [ 0, 1 ] to viewZ
  26407. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26408. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26409. // -near maps to 0; -far maps to 1
  26410. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26411. // maps perspective depth in [ 0, 1 ] to viewZ
  26412. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26413. ViewportDepthNode.DEPTH = 'depth';
  26414. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26415. const depthBase = nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26416. const depth = nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26417. const linearDepth = nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26418. const viewportLinearDepth = linearDepth( viewportDepthTexture() );
  26419. depth.assign = ( value ) => depthBase( value );
  26420. addNodeClass( 'ViewportDepthNode', ViewportDepthNode );
  26421. class ClippingNode extends Node {
  26422. constructor( scope = ClippingNode.DEFAULT ) {
  26423. super();
  26424. this.scope = scope;
  26425. }
  26426. setup( builder ) {
  26427. super.setup( builder );
  26428. const clippingContext = builder.clippingContext;
  26429. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26430. const numClippingPlanes = globalClippingCount + localClippingCount;
  26431. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26432. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26433. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26434. } else {
  26435. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26436. }
  26437. }
  26438. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26439. return tslFn( () => {
  26440. const clippingPlanes = uniforms( planes );
  26441. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26442. const distanceGradient = property( 'float', 'distanceToGradient' );
  26443. const clipOpacity = property( 'float', 'clipOpacity' );
  26444. clipOpacity.assign( 1 );
  26445. let plane;
  26446. loop( numUnionClippingPlanes, ( { i } ) => {
  26447. plane = clippingPlanes.element( i );
  26448. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26449. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26450. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26451. clipOpacity.equal( 0.0 ).discard();
  26452. } );
  26453. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26454. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26455. unionClipOpacity.assign( 1 );
  26456. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26457. plane = clippingPlanes.element( i );
  26458. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26459. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26460. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26461. } );
  26462. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26463. }
  26464. diffuseColor.a.mulAssign( clipOpacity );
  26465. diffuseColor.a.equal( 0.0 ).discard();
  26466. } )();
  26467. }
  26468. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26469. return tslFn( () => {
  26470. const clippingPlanes = uniforms( planes );
  26471. let plane;
  26472. loop( numUnionClippingPlanes, ( { i } ) => {
  26473. plane = clippingPlanes.element( i );
  26474. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26475. } );
  26476. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26477. const clipped = property( 'bool', 'clipped' );
  26478. clipped.assign( true );
  26479. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26480. plane = clippingPlanes.element( i );
  26481. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26482. } );
  26483. clipped.discard();
  26484. }
  26485. } )();
  26486. }
  26487. }
  26488. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26489. ClippingNode.DEFAULT = 'default';
  26490. const clipping = () => nodeObject( new ClippingNode() );
  26491. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26492. class FrontFacingNode extends Node {
  26493. constructor() {
  26494. super( 'bool' );
  26495. this.isFrontFacingNode = true;
  26496. }
  26497. generate( builder ) {
  26498. const { renderer, material } = builder;
  26499. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  26500. if ( material.side === BackSide ) {
  26501. return 'false';
  26502. }
  26503. }
  26504. return builder.getFrontFacing();
  26505. }
  26506. }
  26507. const frontFacing = nodeImmutable( FrontFacingNode );
  26508. const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  26509. addNodeClass( 'FrontFacingNode', FrontFacingNode );
  26510. const NodeMaterials = new Map();
  26511. class NodeMaterial extends Material {
  26512. constructor() {
  26513. super();
  26514. this.isNodeMaterial = true;
  26515. this.type = this.constructor.type;
  26516. this.forceSinglePass = false;
  26517. this.fog = true;
  26518. this.lights = true;
  26519. this.normals = true;
  26520. this.lightsNode = null;
  26521. this.envNode = null;
  26522. this.aoNode = null;
  26523. this.colorNode = null;
  26524. this.normalNode = null;
  26525. this.opacityNode = null;
  26526. this.backdropNode = null;
  26527. this.backdropAlphaNode = null;
  26528. this.alphaTestNode = null;
  26529. this.positionNode = null;
  26530. this.depthNode = null;
  26531. this.shadowNode = null;
  26532. this.shadowPositionNode = null;
  26533. this.outputNode = null;
  26534. this.fragmentNode = null;
  26535. this.vertexNode = null;
  26536. }
  26537. customProgramCacheKey() {
  26538. return this.type + getCacheKey( this );
  26539. }
  26540. build( builder ) {
  26541. this.setup( builder );
  26542. }
  26543. setup( builder ) {
  26544. // < VERTEX STAGE >
  26545. builder.addStack();
  26546. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26547. builder.addFlow( 'vertex', builder.removeStack() );
  26548. // < FRAGMENT STAGE >
  26549. builder.addStack();
  26550. let resultNode;
  26551. const clippingNode = this.setupClipping( builder );
  26552. if ( this.depthWrite === true ) this.setupDepth( builder );
  26553. if ( this.fragmentNode === null ) {
  26554. if ( this.normals === true ) this.setupNormal( builder );
  26555. this.setupDiffuseColor( builder );
  26556. this.setupVariants( builder );
  26557. const outgoingLightNode = this.setupLighting( builder );
  26558. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26559. // force unsigned floats - useful for RenderTargets
  26560. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26561. resultNode = this.setupOutput( builder, basicOutput );
  26562. // OUTPUT NODE
  26563. output.assign( resultNode );
  26564. //
  26565. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26566. } else {
  26567. let fragmentNode = this.fragmentNode;
  26568. if ( fragmentNode.isOutputStructNode !== true ) {
  26569. fragmentNode = vec4( fragmentNode );
  26570. }
  26571. resultNode = this.setupOutput( builder, fragmentNode );
  26572. }
  26573. builder.stack.outputNode = resultNode;
  26574. builder.addFlow( 'fragment', builder.removeStack() );
  26575. }
  26576. setupClipping( builder ) {
  26577. if ( builder.clippingContext === null ) return null;
  26578. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26579. let result = null;
  26580. if ( globalClippingCount || localClippingCount ) {
  26581. if ( this.alphaToCoverage ) {
  26582. // to be added to flow when the color/alpha value has been determined
  26583. result = clippingAlpha();
  26584. } else {
  26585. builder.stack.add( clipping() );
  26586. }
  26587. }
  26588. return result;
  26589. }
  26590. setupDepth( builder ) {
  26591. const { renderer } = builder;
  26592. // Depth
  26593. let depthNode = this.depthNode;
  26594. if ( depthNode === null && renderer.logarithmicDepthBuffer === true ) {
  26595. const fragDepth = modelViewProjection().w.add( 1 );
  26596. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  26597. }
  26598. if ( depthNode !== null ) {
  26599. depth.assign( depthNode ).append();
  26600. }
  26601. }
  26602. setupPosition( builder ) {
  26603. const { object } = builder;
  26604. const geometry = object.geometry;
  26605. builder.addStack();
  26606. // Vertex
  26607. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26608. morphReference( object ).append();
  26609. }
  26610. if ( object.isSkinnedMesh === true ) {
  26611. skinningReference( object ).append();
  26612. }
  26613. if ( this.displacementMap ) {
  26614. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26615. const displacementScale = materialReference( 'displacementScale', 'float' );
  26616. const displacementBias = materialReference( 'displacementBias', 'float' );
  26617. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26618. }
  26619. if ( object.isBatchedMesh ) {
  26620. batch( object ).append();
  26621. }
  26622. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26623. instance( object ).append();
  26624. }
  26625. if ( this.positionNode !== null ) {
  26626. positionLocal.assign( this.positionNode );
  26627. }
  26628. const mvp = modelViewProjection();
  26629. builder.context.vertex = builder.removeStack();
  26630. builder.context.mvp = mvp;
  26631. return mvp;
  26632. }
  26633. setupDiffuseColor( { object, geometry } ) {
  26634. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26635. // VERTEX COLORS
  26636. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26637. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26638. }
  26639. // Instanced colors
  26640. if ( object.instanceColor ) {
  26641. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26642. colorNode = instanceColor.mul( colorNode );
  26643. }
  26644. // COLOR
  26645. diffuseColor.assign( colorNode );
  26646. // OPACITY
  26647. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26648. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26649. // ALPHA TEST
  26650. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26651. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26652. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26653. }
  26654. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26655. diffuseColor.a.assign( 1.0 );
  26656. }
  26657. }
  26658. setupVariants( /*builder*/ ) {
  26659. // Interface function.
  26660. }
  26661. setupNormal() {
  26662. // NORMAL VIEW
  26663. if ( this.flatShading === true ) {
  26664. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  26665. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  26666. } else {
  26667. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26668. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  26669. }
  26670. }
  26671. setupEnvironment( builder ) {
  26672. let node = null;
  26673. if ( this.envNode ) {
  26674. node = this.envNode;
  26675. } else if ( this.envMap ) {
  26676. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  26677. } else if ( builder.environmentNode ) {
  26678. node = builder.environmentNode;
  26679. }
  26680. return node;
  26681. }
  26682. setupLights( builder ) {
  26683. const materialLightsNode = [];
  26684. //
  26685. const envNode = this.setupEnvironment( builder );
  26686. if ( envNode && envNode.isLightingNode ) {
  26687. materialLightsNode.push( envNode );
  26688. }
  26689. if ( builder.material.lightMap ) {
  26690. materialLightsNode.push( new IrradianceNode( materialReference( 'lightMap', 'texture' ) ) );
  26691. }
  26692. if ( this.aoNode !== null || builder.material.aoMap ) {
  26693. const aoNode = this.aoNode !== null ? this.aoNode : texture( builder.material.aoMap );
  26694. materialLightsNode.push( new AONode( aoNode ) );
  26695. }
  26696. let lightsN = this.lightsNode || builder.lightsNode;
  26697. if ( materialLightsNode.length > 0 ) {
  26698. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  26699. }
  26700. return lightsN;
  26701. }
  26702. setupLightingModel( /*builder*/ ) {
  26703. // Interface function.
  26704. }
  26705. setupLighting( builder ) {
  26706. const { material } = builder;
  26707. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26708. // OUTGOING LIGHT
  26709. const lights = this.lights === true || this.lightsNode !== null;
  26710. const lightsNode = lights ? this.setupLights( builder ) : null;
  26711. let outgoingLightNode = diffuseColor.rgb;
  26712. if ( lightsNode && lightsNode.hasLight !== false ) {
  26713. const lightingModel = this.setupLightingModel( builder );
  26714. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26715. } else if ( backdropNode !== null ) {
  26716. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26717. }
  26718. // EMISSIVE
  26719. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26720. outgoingLightNode = outgoingLightNode.add( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26721. }
  26722. return outgoingLightNode;
  26723. }
  26724. setupOutput( builder, outputNode ) {
  26725. // FOG
  26726. if ( this.fog === true ) {
  26727. const fogNode = builder.fogNode;
  26728. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26729. }
  26730. return outputNode;
  26731. }
  26732. setDefaultValues( material ) {
  26733. // This approach is to reuse the native refreshUniforms*
  26734. // and turn available the use of features like transmission and environment in core
  26735. for ( const property in material ) {
  26736. const value = material[ property ];
  26737. if ( this[ property ] === undefined ) {
  26738. this[ property ] = value;
  26739. if ( value && value.clone ) this[ property ] = value.clone();
  26740. }
  26741. }
  26742. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26743. for ( const key in descriptors ) {
  26744. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26745. descriptors[ key ].get !== undefined ) {
  26746. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26747. }
  26748. }
  26749. }
  26750. toJSON( meta ) {
  26751. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26752. if ( isRoot ) {
  26753. meta = {
  26754. textures: {},
  26755. images: {},
  26756. nodes: {}
  26757. };
  26758. }
  26759. const data = Material.prototype.toJSON.call( this, meta );
  26760. const nodeChildren = getNodeChildren( this );
  26761. data.inputNodes = {};
  26762. for ( const { property, childNode } of nodeChildren ) {
  26763. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26764. }
  26765. // TODO: Copied from Object3D.toJSON
  26766. function extractFromCache( cache ) {
  26767. const values = [];
  26768. for ( const key in cache ) {
  26769. const data = cache[ key ];
  26770. delete data.metadata;
  26771. values.push( data );
  26772. }
  26773. return values;
  26774. }
  26775. if ( isRoot ) {
  26776. const textures = extractFromCache( meta.textures );
  26777. const images = extractFromCache( meta.images );
  26778. const nodes = extractFromCache( meta.nodes );
  26779. if ( textures.length > 0 ) data.textures = textures;
  26780. if ( images.length > 0 ) data.images = images;
  26781. if ( nodes.length > 0 ) data.nodes = nodes;
  26782. }
  26783. return data;
  26784. }
  26785. copy( source ) {
  26786. this.lightsNode = source.lightsNode;
  26787. this.envNode = source.envNode;
  26788. this.colorNode = source.colorNode;
  26789. this.normalNode = source.normalNode;
  26790. this.opacityNode = source.opacityNode;
  26791. this.backdropNode = source.backdropNode;
  26792. this.backdropAlphaNode = source.backdropAlphaNode;
  26793. this.alphaTestNode = source.alphaTestNode;
  26794. this.positionNode = source.positionNode;
  26795. this.depthNode = source.depthNode;
  26796. this.shadowNode = source.shadowNode;
  26797. this.shadowPositionNode = source.shadowPositionNode;
  26798. this.outputNode = source.outputNode;
  26799. this.fragmentNode = source.fragmentNode;
  26800. this.vertexNode = source.vertexNode;
  26801. return super.copy( source );
  26802. }
  26803. static fromMaterial( material ) {
  26804. if ( material.isNodeMaterial === true ) { // is already a node material
  26805. return material;
  26806. }
  26807. const type = material.type.replace( 'Material', 'NodeMaterial' );
  26808. const nodeMaterial = createNodeMaterialFromType( type );
  26809. if ( nodeMaterial === undefined ) {
  26810. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  26811. }
  26812. for ( const key in material ) {
  26813. nodeMaterial[ key ] = material[ key ];
  26814. }
  26815. return nodeMaterial;
  26816. }
  26817. }
  26818. function addNodeMaterial( type, nodeMaterial ) {
  26819. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  26820. if ( NodeMaterials.has( type ) ) {
  26821. console.warn( `Redefinition of node material ${ type }` );
  26822. return;
  26823. }
  26824. NodeMaterials.set( type, nodeMaterial );
  26825. nodeMaterial.type = type;
  26826. }
  26827. function createNodeMaterialFromType( type ) {
  26828. const Material = NodeMaterials.get( type );
  26829. if ( Material !== undefined ) {
  26830. return new Material();
  26831. }
  26832. }
  26833. addNodeMaterial( 'NodeMaterial', NodeMaterial );
  26834. class Uniform {
  26835. constructor( name, value ) {
  26836. this.name = name;
  26837. this.value = value;
  26838. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  26839. this.itemSize = 0;
  26840. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  26841. }
  26842. setValue( value ) {
  26843. this.value = value;
  26844. }
  26845. getValue() {
  26846. return this.value;
  26847. }
  26848. }
  26849. class NumberUniform extends Uniform {
  26850. constructor( name, value = 0 ) {
  26851. super( name, value );
  26852. this.isNumberUniform = true;
  26853. this.boundary = 4;
  26854. this.itemSize = 1;
  26855. }
  26856. }
  26857. class Vector2Uniform extends Uniform {
  26858. constructor( name, value = new Vector2() ) {
  26859. super( name, value );
  26860. this.isVector2Uniform = true;
  26861. this.boundary = 8;
  26862. this.itemSize = 2;
  26863. }
  26864. }
  26865. class Vector3Uniform extends Uniform {
  26866. constructor( name, value = new Vector3() ) {
  26867. super( name, value );
  26868. this.isVector3Uniform = true;
  26869. this.boundary = 16;
  26870. this.itemSize = 3;
  26871. }
  26872. }
  26873. class Vector4Uniform extends Uniform {
  26874. constructor( name, value = new Vector4() ) {
  26875. super( name, value );
  26876. this.isVector4Uniform = true;
  26877. this.boundary = 16;
  26878. this.itemSize = 4;
  26879. }
  26880. }
  26881. class ColorUniform extends Uniform {
  26882. constructor( name, value = new Color() ) {
  26883. super( name, value );
  26884. this.isColorUniform = true;
  26885. this.boundary = 16;
  26886. this.itemSize = 3;
  26887. }
  26888. }
  26889. class Matrix3Uniform extends Uniform {
  26890. constructor( name, value = new Matrix3() ) {
  26891. super( name, value );
  26892. this.isMatrix3Uniform = true;
  26893. this.boundary = 48;
  26894. this.itemSize = 12;
  26895. }
  26896. }
  26897. class Matrix4Uniform extends Uniform {
  26898. constructor( name, value = new Matrix4() ) {
  26899. super( name, value );
  26900. this.isMatrix4Uniform = true;
  26901. this.boundary = 64;
  26902. this.itemSize = 16;
  26903. }
  26904. }
  26905. class NumberNodeUniform extends NumberUniform {
  26906. constructor( nodeUniform ) {
  26907. super( nodeUniform.name, nodeUniform.value );
  26908. this.nodeUniform = nodeUniform;
  26909. }
  26910. getValue() {
  26911. return this.nodeUniform.value;
  26912. }
  26913. }
  26914. class Vector2NodeUniform extends Vector2Uniform {
  26915. constructor( nodeUniform ) {
  26916. super( nodeUniform.name, nodeUniform.value );
  26917. this.nodeUniform = nodeUniform;
  26918. }
  26919. getValue() {
  26920. return this.nodeUniform.value;
  26921. }
  26922. }
  26923. class Vector3NodeUniform extends Vector3Uniform {
  26924. constructor( nodeUniform ) {
  26925. super( nodeUniform.name, nodeUniform.value );
  26926. this.nodeUniform = nodeUniform;
  26927. }
  26928. getValue() {
  26929. return this.nodeUniform.value;
  26930. }
  26931. }
  26932. class Vector4NodeUniform extends Vector4Uniform {
  26933. constructor( nodeUniform ) {
  26934. super( nodeUniform.name, nodeUniform.value );
  26935. this.nodeUniform = nodeUniform;
  26936. }
  26937. getValue() {
  26938. return this.nodeUniform.value;
  26939. }
  26940. }
  26941. class ColorNodeUniform extends ColorUniform {
  26942. constructor( nodeUniform ) {
  26943. super( nodeUniform.name, nodeUniform.value );
  26944. this.nodeUniform = nodeUniform;
  26945. }
  26946. getValue() {
  26947. return this.nodeUniform.value;
  26948. }
  26949. }
  26950. class Matrix3NodeUniform extends Matrix3Uniform {
  26951. constructor( nodeUniform ) {
  26952. super( nodeUniform.name, nodeUniform.value );
  26953. this.nodeUniform = nodeUniform;
  26954. }
  26955. getValue() {
  26956. return this.nodeUniform.value;
  26957. }
  26958. }
  26959. class Matrix4NodeUniform extends Matrix4Uniform {
  26960. constructor( nodeUniform ) {
  26961. super( nodeUniform.name, nodeUniform.value );
  26962. this.nodeUniform = nodeUniform;
  26963. }
  26964. getValue() {
  26965. return this.nodeUniform.value;
  26966. }
  26967. }
  26968. class CondNode extends Node {
  26969. constructor( condNode, ifNode, elseNode = null ) {
  26970. super();
  26971. this.condNode = condNode;
  26972. this.ifNode = ifNode;
  26973. this.elseNode = elseNode;
  26974. }
  26975. getNodeType( builder ) {
  26976. const ifType = this.ifNode.getNodeType( builder );
  26977. if ( this.elseNode !== null ) {
  26978. const elseType = this.elseNode.getNodeType( builder );
  26979. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  26980. return elseType;
  26981. }
  26982. }
  26983. return ifType;
  26984. }
  26985. setup( builder ) {
  26986. const properties = builder.getNodeProperties( this );
  26987. properties.condNode = this.condNode.cache();
  26988. properties.ifNode = this.ifNode.cache();
  26989. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  26990. }
  26991. generate( builder, output ) {
  26992. const type = this.getNodeType( builder );
  26993. const nodeData = builder.getDataFromNode( this );
  26994. if ( nodeData.nodeProperty !== undefined ) {
  26995. return nodeData.nodeProperty;
  26996. }
  26997. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  26998. const needsOutput = output !== 'void';
  26999. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  27000. nodeData.nodeProperty = nodeProperty;
  27001. const nodeSnippet = condNode.build( builder, 'bool' );
  27002. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  27003. let ifSnippet = ifNode.build( builder, type );
  27004. if ( ifSnippet ) {
  27005. if ( needsOutput ) {
  27006. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  27007. } else {
  27008. ifSnippet = 'return ' + ifSnippet + ';';
  27009. }
  27010. }
  27011. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  27012. if ( elseNode !== null ) {
  27013. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  27014. let elseSnippet = elseNode.build( builder, type );
  27015. if ( elseSnippet ) {
  27016. if ( needsOutput ) {
  27017. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  27018. } else {
  27019. elseSnippet = 'return ' + elseSnippet + ';';
  27020. }
  27021. }
  27022. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  27023. } else {
  27024. builder.addFlowCode( '\n\n' );
  27025. }
  27026. return builder.format( nodeProperty, type, output );
  27027. }
  27028. }
  27029. const cond = nodeProxy( CondNode );
  27030. addNodeElement( 'cond', cond );
  27031. addNodeClass( 'CondNode', CondNode );
  27032. class StackNode extends Node {
  27033. constructor( parent = null ) {
  27034. super();
  27035. this.nodes = [];
  27036. this.outputNode = null;
  27037. this.parent = parent;
  27038. this._currentCond = null;
  27039. this.isStackNode = true;
  27040. }
  27041. getNodeType( builder ) {
  27042. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  27043. }
  27044. add( node ) {
  27045. this.nodes.push( node );
  27046. return this;
  27047. }
  27048. if( boolNode, method ) {
  27049. const methodNode = new ShaderNode( method );
  27050. this._currentCond = cond( boolNode, methodNode );
  27051. return this.add( this._currentCond );
  27052. }
  27053. elseif( boolNode, method ) {
  27054. const methodNode = new ShaderNode( method );
  27055. const ifNode = cond( boolNode, methodNode );
  27056. this._currentCond.elseNode = ifNode;
  27057. this._currentCond = ifNode;
  27058. return this;
  27059. }
  27060. else( method ) {
  27061. this._currentCond.elseNode = new ShaderNode( method );
  27062. return this;
  27063. }
  27064. build( builder, ...params ) {
  27065. const previousStack = getCurrentStack();
  27066. setCurrentStack( this );
  27067. for ( const node of this.nodes ) {
  27068. node.build( builder, 'void' );
  27069. }
  27070. setCurrentStack( previousStack );
  27071. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  27072. }
  27073. }
  27074. const stack = nodeProxy( StackNode );
  27075. addNodeClass( 'StackNode', StackNode );
  27076. class EquirectUVNode extends TempNode {
  27077. constructor( dirNode = positionWorldDirection ) {
  27078. super( 'vec2' );
  27079. this.dirNode = dirNode;
  27080. }
  27081. setup() {
  27082. const dir = this.dirNode;
  27083. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27084. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27085. return vec2( u, v );
  27086. }
  27087. }
  27088. const equirectUV = nodeProxy( EquirectUVNode );
  27089. addNodeClass( 'EquirectUVNode', EquirectUVNode );
  27090. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27091. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27092. constructor( size = 1, options = {} ) {
  27093. super( size, options );
  27094. this.isCubeRenderTarget = true;
  27095. }
  27096. fromEquirectangularTexture( renderer, texture$1 ) {
  27097. const currentMinFilter = texture$1.minFilter;
  27098. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27099. texture$1.generateMipmaps = true;
  27100. this.texture.type = texture$1.type;
  27101. this.texture.colorSpace = texture$1.colorSpace;
  27102. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27103. this.texture.minFilter = texture$1.minFilter;
  27104. this.texture.magFilter = texture$1.magFilter;
  27105. const geometry = new BoxGeometry( 5, 5, 5 );
  27106. const uvNode = equirectUV( positionWorldDirection );
  27107. const material = createNodeMaterialFromType( 'MeshBasicNodeMaterial' );
  27108. material.colorNode = texture( texture$1, uvNode, 0 );
  27109. material.side = BackSide;
  27110. material.blending = NoBlending;
  27111. const mesh = new Mesh( geometry, material );
  27112. const scene = new Scene();
  27113. scene.add( mesh );
  27114. // Avoid blurred poles
  27115. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27116. const camera = new CubeCamera( 1, 10, this );
  27117. camera.update( renderer, scene );
  27118. texture$1.minFilter = currentMinFilter;
  27119. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27120. mesh.geometry.dispose();
  27121. mesh.material.dispose();
  27122. return this;
  27123. }
  27124. }
  27125. // These defines must match with PMREMGenerator
  27126. const cubeUV_r0 = float( 1.0 );
  27127. const cubeUV_m0 = float( - 2.0 );
  27128. const cubeUV_r1 = float( 0.8 );
  27129. const cubeUV_m1 = float( - 1.0 );
  27130. const cubeUV_r4 = float( 0.4 );
  27131. const cubeUV_m4 = float( 2.0 );
  27132. const cubeUV_r5 = float( 0.305 );
  27133. const cubeUV_m5 = float( 3.0 );
  27134. const cubeUV_r6 = float( 0.21 );
  27135. const cubeUV_m6 = float( 4.0 );
  27136. const cubeUV_minMipLevel = float( 4.0 );
  27137. const cubeUV_minTileSize = float( 16.0 );
  27138. // These shader functions convert between the UV coordinates of a single face of
  27139. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  27140. // sampling a textureCube (not generally normalized ).
  27141. const getFace = tslFn( ( [ direction ] ) => {
  27142. const absDirection = vec3( abs( direction ) ).toVar();
  27143. const face = float( - 1.0 ).toVar();
  27144. If( absDirection.x.greaterThan( absDirection.z ), () => {
  27145. If( absDirection.x.greaterThan( absDirection.y ), () => {
  27146. face.assign( cond( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  27147. } ).else( () => {
  27148. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27149. } );
  27150. } ).else( () => {
  27151. If( absDirection.z.greaterThan( absDirection.y ), () => {
  27152. face.assign( cond( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  27153. } ).else( () => {
  27154. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27155. } );
  27156. } );
  27157. return face;
  27158. } ).setLayout( {
  27159. name: 'getFace',
  27160. type: 'float',
  27161. inputs: [
  27162. { name: 'direction', type: 'vec3' }
  27163. ]
  27164. } );
  27165. // RH coordinate system; PMREM face-indexing convention
  27166. const getUV = tslFn( ( [ direction, face ] ) => {
  27167. const uv = vec2().toVar();
  27168. If( face.equal( 0.0 ), () => {
  27169. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  27170. } ).elseif( face.equal( 1.0 ), () => {
  27171. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  27172. } ).elseif( face.equal( 2.0 ), () => {
  27173. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  27174. } ).elseif( face.equal( 3.0 ), () => {
  27175. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  27176. } ).elseif( face.equal( 4.0 ), () => {
  27177. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  27178. } ).else( () => {
  27179. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  27180. } );
  27181. return mul( 0.5, uv.add( 1.0 ) );
  27182. } ).setLayout( {
  27183. name: 'getUV',
  27184. type: 'vec2',
  27185. inputs: [
  27186. { name: 'direction', type: 'vec3' },
  27187. { name: 'face', type: 'float' }
  27188. ]
  27189. } );
  27190. const roughnessToMip = tslFn( ( [ roughness ] ) => {
  27191. const mip = float( 0.0 ).toVar();
  27192. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  27193. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  27194. } ).elseif( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  27195. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  27196. } ).elseif( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  27197. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  27198. } ).elseif( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  27199. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  27200. } ).else( () => {
  27201. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  27202. } );
  27203. return mip;
  27204. } ).setLayout( {
  27205. name: 'roughnessToMip',
  27206. type: 'float',
  27207. inputs: [
  27208. { name: 'roughness', type: 'float' }
  27209. ]
  27210. } );
  27211. // RH coordinate system; PMREM face-indexing convention
  27212. const getDirection = tslFn( ( [ uv_immutable, face ] ) => {
  27213. const uv = uv_immutable.toVar();
  27214. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  27215. const direction = vec3( uv, 1.0 ).toVar();
  27216. If( face.equal( 0.0 ), () => {
  27217. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  27218. } ).elseif( face.equal( 1.0 ), () => {
  27219. direction.assign( direction.xzy );
  27220. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  27221. } ).elseif( face.equal( 2.0 ), () => {
  27222. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  27223. } ).elseif( face.equal( 3.0 ), () => {
  27224. direction.assign( direction.zyx );
  27225. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  27226. } ).elseif( face.equal( 4.0 ), () => {
  27227. direction.assign( direction.xzy );
  27228. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  27229. } ).elseif( face.equal( 5.0 ), () => {
  27230. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  27231. } );
  27232. return direction;
  27233. } ).setLayout( {
  27234. name: 'getDirection',
  27235. type: 'vec3',
  27236. inputs: [
  27237. { name: 'uv', type: 'vec2' },
  27238. { name: 'face', type: 'float' }
  27239. ]
  27240. } );
  27241. //
  27242. const textureCubeUV = tslFn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27243. const roughness = float( roughness_immutable );
  27244. const sampleDir = vec3( sampleDir_immutable );
  27245. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  27246. const mipF = fract( mip );
  27247. const mipInt = floor( mip );
  27248. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27249. If( mipF.notEqual( 0.0 ), () => {
  27250. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27251. color0.assign( mix( color0, color1, mipF ) );
  27252. } );
  27253. return color0;
  27254. } );
  27255. const bilinearCubeUV = tslFn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27256. const mipInt = float( mipInt_immutable ).toVar();
  27257. const direction = vec3( direction_immutable );
  27258. const face = float( getFace( direction ) ).toVar();
  27259. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  27260. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  27261. const faceSize = float( exp2( mipInt ) ).toVar();
  27262. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  27263. If( face.greaterThan( 2.0 ), () => {
  27264. uv.y.addAssign( faceSize );
  27265. face.subAssign( 3.0 );
  27266. } );
  27267. uv.x.addAssign( face.mul( faceSize ) );
  27268. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  27269. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  27270. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  27271. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  27272. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  27273. } );
  27274. const getSample = tslFn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27275. const cosTheta = cos( theta );
  27276. // Rodrigues' axis-angle rotation
  27277. const sampleDirection = outputDirection.mul( cosTheta )
  27278. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  27279. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  27280. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  27281. } );
  27282. const blur = tslFn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27283. const axis = vec3( cond( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  27284. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  27285. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  27286. } );
  27287. axis.assign( normalize( axis ) );
  27288. const gl_FragColor = vec3().toVar();
  27289. 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 } ) ) );
  27290. loop( { start: int( 1 ), end: n }, ( { i } ) => {
  27291. If( i.greaterThanEqual( samples ), () => {
  27292. Break();
  27293. } );
  27294. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  27295. 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 } ) ) );
  27296. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  27297. } );
  27298. return vec4( gl_FragColor, 1 );
  27299. } );
  27300. const LOD_MIN = 4;
  27301. // The standard deviations (radians) associated with the extra mips. These are
  27302. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27303. // geometric shadowing function. These sigma values squared must match the
  27304. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27305. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27306. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27307. // samples and exit early, but not recompile the shader.
  27308. const MAX_SAMPLES = 20;
  27309. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  27310. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  27311. const _clearColor$1 = /*@__PURE__*/ new Color();
  27312. let _oldTarget = null;
  27313. let _oldActiveCubeFace = 0;
  27314. let _oldActiveMipmapLevel = 0;
  27315. // Golden Ratio
  27316. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27317. const INV_PHI = 1 / PHI;
  27318. // Vertices of a dodecahedron (except the opposites, which represent the
  27319. // same axis), used as axis directions evenly spread on a sphere.
  27320. const _axisDirections = [
  27321. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  27322. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27323. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27324. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27325. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27326. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27327. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27328. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27329. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27330. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  27331. ];
  27332. //
  27333. // WebGPU Face indices
  27334. const _faceLib = [
  27335. 3, 1, 5,
  27336. 0, 4, 2
  27337. ];
  27338. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  27339. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  27340. /**
  27341. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27342. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27343. * blur to be quickly accessed based on material roughness. It is packed into a
  27344. * special CubeUV format that allows us to perform custom interpolation so that
  27345. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27346. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27347. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27348. * higher roughness levels. In this way we maintain resolution to smoothly
  27349. * interpolate diffuse lighting while limiting sampling computation.
  27350. *
  27351. * Paper: Fast, Accurate Image-Based Lighting
  27352. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27353. */
  27354. class PMREMGenerator {
  27355. constructor( renderer ) {
  27356. this._renderer = renderer;
  27357. this._pingPongRenderTarget = null;
  27358. this._lodMax = 0;
  27359. this._cubeSize = 0;
  27360. this._lodPlanes = [];
  27361. this._sizeLods = [];
  27362. this._sigmas = [];
  27363. this._lodMeshes = [];
  27364. this._blurMaterial = null;
  27365. this._cubemapMaterial = null;
  27366. this._equirectMaterial = null;
  27367. this._backgroundBox = null;
  27368. }
  27369. /**
  27370. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27371. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27372. * in radians to be applied to the scene before PMREM generation. Optional near
  27373. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27374. * is placed at the origin).
  27375. */
  27376. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27377. _oldTarget = this._renderer.getRenderTarget();
  27378. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27379. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27380. this._setSize( 256 );
  27381. const cubeUVRenderTarget = this._allocateTargets();
  27382. cubeUVRenderTarget.depthBuffer = true;
  27383. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27384. if ( sigma > 0 ) {
  27385. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27386. }
  27387. this._applyPMREM( cubeUVRenderTarget );
  27388. this._cleanup( cubeUVRenderTarget );
  27389. return cubeUVRenderTarget;
  27390. }
  27391. /**
  27392. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27393. * or HDR. The ideal input image size is 1k (1024 x 512),
  27394. * as this matches best with the 256 x 256 cubemap output.
  27395. */
  27396. fromEquirectangular( equirectangular, renderTarget = null ) {
  27397. return this._fromTexture( equirectangular, renderTarget );
  27398. }
  27399. /**
  27400. * Generates a PMREM from an cubemap texture, which can be either LDR
  27401. * or HDR. The ideal input cube size is 256 x 256,
  27402. * as this matches best with the 256 x 256 cubemap output.
  27403. */
  27404. fromCubemap( cubemap, renderTarget = null ) {
  27405. return this._fromTexture( cubemap, renderTarget );
  27406. }
  27407. /**
  27408. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27409. * your texture's network fetch for increased concurrency.
  27410. */
  27411. compileCubemapShader() {
  27412. if ( this._cubemapMaterial === null ) {
  27413. this._cubemapMaterial = _getCubemapMaterial();
  27414. this._compileMaterial( this._cubemapMaterial );
  27415. }
  27416. }
  27417. /**
  27418. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27419. * your texture's network fetch for increased concurrency.
  27420. */
  27421. compileEquirectangularShader() {
  27422. if ( this._equirectMaterial === null ) {
  27423. this._equirectMaterial = _getEquirectMaterial();
  27424. this._compileMaterial( this._equirectMaterial );
  27425. }
  27426. }
  27427. /**
  27428. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27429. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27430. * one of them will cause any others to also become unusable.
  27431. */
  27432. dispose() {
  27433. this._dispose();
  27434. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  27435. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  27436. if ( this._backgroundBox !== null ) {
  27437. this._backgroundBox.geometry.dispose();
  27438. this._backgroundBox.material.dispose();
  27439. }
  27440. }
  27441. // private interface
  27442. _setSize( cubeSize ) {
  27443. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  27444. this._cubeSize = Math.pow( 2, this._lodMax );
  27445. }
  27446. _dispose() {
  27447. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  27448. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  27449. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  27450. this._lodPlanes[ i ].dispose();
  27451. }
  27452. }
  27453. _cleanup( outputTarget ) {
  27454. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  27455. outputTarget.scissorTest = false;
  27456. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27457. }
  27458. _fromTexture( texture, renderTarget ) {
  27459. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  27460. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  27461. } else { // Equirectangular
  27462. this._setSize( texture.image.width / 4 );
  27463. }
  27464. _oldTarget = this._renderer.getRenderTarget();
  27465. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27466. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27467. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  27468. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27469. this._applyPMREM( cubeUVRenderTarget );
  27470. this._cleanup( cubeUVRenderTarget );
  27471. return cubeUVRenderTarget;
  27472. }
  27473. _allocateTargets() {
  27474. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  27475. const height = 4 * this._cubeSize;
  27476. const params = {
  27477. magFilter: LinearFilter,
  27478. minFilter: LinearFilter,
  27479. generateMipmaps: false,
  27480. type: HalfFloatType,
  27481. format: RGBAFormat,
  27482. colorSpace: LinearSRGBColorSpace,
  27483. //depthBuffer: false
  27484. };
  27485. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  27486. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  27487. if ( this._pingPongRenderTarget !== null ) {
  27488. this._dispose();
  27489. }
  27490. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  27491. const { _lodMax } = this;
  27492. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  27493. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  27494. }
  27495. return cubeUVRenderTarget;
  27496. }
  27497. _compileMaterial( material ) {
  27498. const tmpMesh = this._lodMeshes[ 0 ];
  27499. tmpMesh.material = material;
  27500. this._renderer.compile( tmpMesh, _flatCamera );
  27501. }
  27502. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27503. const cubeCamera = _cubeCamera;
  27504. cubeCamera.near = near;
  27505. cubeCamera.far = far;
  27506. // px, py, pz, nx, ny, nz
  27507. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  27508. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27509. const renderer = this._renderer;
  27510. const originalAutoClear = renderer.autoClear;
  27511. renderer.getClearColor( _clearColor$1 );
  27512. renderer.autoClear = false;
  27513. let backgroundBox = this._backgroundBox;
  27514. if ( backgroundBox === null ) {
  27515. const backgroundMaterial = new MeshBasicMaterial( {
  27516. name: 'PMREM.Background',
  27517. side: BackSide,
  27518. depthWrite: false,
  27519. depthTest: false
  27520. } );
  27521. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27522. }
  27523. let useSolidColor = false;
  27524. const background = scene.background;
  27525. if ( background ) {
  27526. if ( background.isColor ) {
  27527. backgroundBox.material.color.copy( background );
  27528. scene.background = null;
  27529. useSolidColor = true;
  27530. }
  27531. } else {
  27532. backgroundBox.material.color.copy( _clearColor$1 );
  27533. useSolidColor = true;
  27534. }
  27535. renderer.setRenderTarget( cubeUVRenderTarget );
  27536. renderer.clear();
  27537. if ( useSolidColor ) {
  27538. renderer.render( backgroundBox, cubeCamera );
  27539. }
  27540. for ( let i = 0; i < 6; i ++ ) {
  27541. const col = i % 3;
  27542. if ( col === 0 ) {
  27543. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27544. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27545. } else if ( col === 1 ) {
  27546. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27547. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27548. } else {
  27549. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27550. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27551. }
  27552. const size = this._cubeSize;
  27553. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  27554. renderer.render( scene, cubeCamera );
  27555. }
  27556. renderer.autoClear = originalAutoClear;
  27557. scene.background = background;
  27558. }
  27559. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27560. const renderer = this._renderer;
  27561. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  27562. if ( isCubeTexture ) {
  27563. if ( this._cubemapMaterial === null ) {
  27564. this._cubemapMaterial = _getCubemapMaterial( texture );
  27565. }
  27566. } else {
  27567. if ( this._equirectMaterial === null ) {
  27568. this._equirectMaterial = _getEquirectMaterial( texture );
  27569. }
  27570. }
  27571. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  27572. material.fragmentNode.value = texture;
  27573. const mesh = this._lodMeshes[ 0 ];
  27574. mesh.material = material;
  27575. const size = this._cubeSize;
  27576. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  27577. renderer.setRenderTarget( cubeUVRenderTarget );
  27578. renderer.render( mesh, _flatCamera );
  27579. }
  27580. _applyPMREM( cubeUVRenderTarget ) {
  27581. const renderer = this._renderer;
  27582. const autoClear = renderer.autoClear;
  27583. renderer.autoClear = false;
  27584. const n = this._lodPlanes.length;
  27585. for ( let i = 1; i < n; i ++ ) {
  27586. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  27587. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  27588. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27589. }
  27590. renderer.autoClear = autoClear;
  27591. }
  27592. /**
  27593. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27594. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27595. * the blur latitudinally (around the poles), and then longitudinally (towards
  27596. * the poles) to approximate the orthogonally-separable blur. It is least
  27597. * accurate at the poles, but still does a decent job.
  27598. */
  27599. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27600. const pingPongRenderTarget = this._pingPongRenderTarget;
  27601. this._halfBlur(
  27602. cubeUVRenderTarget,
  27603. pingPongRenderTarget,
  27604. lodIn,
  27605. lodOut,
  27606. sigma,
  27607. 'latitudinal',
  27608. poleAxis );
  27609. this._halfBlur(
  27610. pingPongRenderTarget,
  27611. cubeUVRenderTarget,
  27612. lodOut,
  27613. lodOut,
  27614. sigma,
  27615. 'longitudinal',
  27616. poleAxis );
  27617. }
  27618. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27619. const renderer = this._renderer;
  27620. const blurMaterial = this._blurMaterial;
  27621. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27622. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  27623. }
  27624. // Number of standard deviations at which to cut off the discrete approximation.
  27625. const STANDARD_DEVIATIONS = 3;
  27626. const blurMesh = this._lodMeshes[ lodOut ];
  27627. blurMesh.material = blurMaterial;
  27628. const blurUniforms = blurMaterial.uniforms;
  27629. const pixels = this._sizeLods[ lodIn ] - 1;
  27630. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27631. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27632. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27633. if ( samples > MAX_SAMPLES ) {
  27634. console.warn( `sigmaRadians, ${
  27635. sigmaRadians}, is too large and will clip, as it requested ${
  27636. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27637. }
  27638. const weights = [];
  27639. let sum = 0;
  27640. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27641. const x = i / sigmaPixels;
  27642. const weight = Math.exp( - x * x / 2 );
  27643. weights.push( weight );
  27644. if ( i === 0 ) {
  27645. sum += weight;
  27646. } else if ( i < samples ) {
  27647. sum += 2 * weight;
  27648. }
  27649. }
  27650. for ( let i = 0; i < weights.length; i ++ ) {
  27651. weights[ i ] = weights[ i ] / sum;
  27652. }
  27653. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  27654. blurUniforms.envMap.value = targetIn.texture;
  27655. blurUniforms.samples.value = samples;
  27656. blurUniforms.weights.array = weights;
  27657. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  27658. if ( poleAxis ) {
  27659. blurUniforms.poleAxis.value = poleAxis;
  27660. }
  27661. const { _lodMax } = this;
  27662. blurUniforms.dTheta.value = radiansPerPixel;
  27663. blurUniforms.mipInt.value = _lodMax - lodIn;
  27664. const outputSize = this._sizeLods[ lodOut ];
  27665. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  27666. const y = 4 * ( this._cubeSize - outputSize );
  27667. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27668. renderer.setRenderTarget( targetOut );
  27669. renderer.render( blurMesh, _flatCamera );
  27670. }
  27671. }
  27672. function _createPlanes( lodMax ) {
  27673. const lodPlanes = [];
  27674. const sizeLods = [];
  27675. const sigmas = [];
  27676. const lodMeshes = [];
  27677. let lod = lodMax;
  27678. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27679. for ( let i = 0; i < totalLods; i ++ ) {
  27680. const sizeLod = Math.pow( 2, lod );
  27681. sizeLods.push( sizeLod );
  27682. let sigma = 1.0 / sizeLod;
  27683. if ( i > lodMax - LOD_MIN ) {
  27684. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  27685. } else if ( i === 0 ) {
  27686. sigma = 0;
  27687. }
  27688. sigmas.push( sigma );
  27689. const texelSize = 1.0 / ( sizeLod - 2 );
  27690. const min = - texelSize;
  27691. const max = 1 + texelSize;
  27692. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27693. const cubeFaces = 6;
  27694. const vertices = 6;
  27695. const positionSize = 3;
  27696. const uvSize = 2;
  27697. const faceIndexSize = 1;
  27698. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27699. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27700. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27701. for ( let face = 0; face < cubeFaces; face ++ ) {
  27702. const x = ( face % 3 ) * 2 / 3 - 1;
  27703. const y = face > 2 ? 0 : - 1;
  27704. const coordinates = [
  27705. x, y, 0,
  27706. x + 2 / 3, y, 0,
  27707. x + 2 / 3, y + 1, 0,
  27708. x, y, 0,
  27709. x + 2 / 3, y + 1, 0,
  27710. x, y + 1, 0
  27711. ];
  27712. const faceIdx = _faceLib[ face ];
  27713. position.set( coordinates, positionSize * vertices * faceIdx );
  27714. uv.set( uv1, uvSize * vertices * faceIdx );
  27715. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  27716. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  27717. }
  27718. const planes = new BufferGeometry();
  27719. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27720. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27721. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27722. lodPlanes.push( planes );
  27723. lodMeshes.push( new Mesh( planes, null ) );
  27724. if ( lod > LOD_MIN ) {
  27725. lod --;
  27726. }
  27727. }
  27728. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  27729. }
  27730. function _createRenderTarget( width, height, params ) {
  27731. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  27732. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27733. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27734. cubeUVRenderTarget.texture.isPMREMTexture = true;
  27735. cubeUVRenderTarget.scissorTest = true;
  27736. return cubeUVRenderTarget;
  27737. }
  27738. function _setViewport( target, x, y, width, height ) {
  27739. const viewY = target.height - height - y;
  27740. target.viewport.set( x, viewY, width, height );
  27741. target.scissor.set( x, viewY, width, height );
  27742. }
  27743. function _getMaterial() {
  27744. const material = new NodeMaterial();
  27745. material.depthTest = false;
  27746. material.depthWrite = false;
  27747. material.blending = NoBlending;
  27748. return material;
  27749. }
  27750. function _getBlurShader( lodMax, width, height ) {
  27751. const weights = uniforms( new Array( MAX_SAMPLES ).fill( 0 ) );
  27752. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  27753. const dTheta = uniform( 0 );
  27754. const n = float( MAX_SAMPLES );
  27755. const latitudinal = uniform( 0 ); // false, bool
  27756. const samples = uniform( 1 ); // int
  27757. const envMap = texture( null );
  27758. const mipInt = uniform( 0 ); // int
  27759. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  27760. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  27761. const CUBEUV_MAX_MIP = float( lodMax );
  27762. const materialUniforms = {
  27763. n,
  27764. latitudinal,
  27765. weights,
  27766. poleAxis,
  27767. outputDirection,
  27768. dTheta,
  27769. samples,
  27770. envMap,
  27771. mipInt,
  27772. CUBEUV_TEXEL_WIDTH,
  27773. CUBEUV_TEXEL_HEIGHT,
  27774. CUBEUV_MAX_MIP
  27775. };
  27776. const material = _getMaterial();
  27777. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  27778. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  27779. return material;
  27780. }
  27781. function _getCubemapMaterial( envTexture ) {
  27782. const material = _getMaterial();
  27783. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  27784. return material;
  27785. }
  27786. function _getEquirectMaterial( envTexture ) {
  27787. const material = _getMaterial();
  27788. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  27789. return material;
  27790. }
  27791. let _id$3 = 0;
  27792. class BindGroup {
  27793. constructor( name = '', bindings = [] ) {
  27794. this.name = name;
  27795. this.bindings = bindings;
  27796. this.id = _id$3 ++;
  27797. }
  27798. }
  27799. const rendererCache = new WeakMap();
  27800. const typeFromLength = new Map( [
  27801. [ 2, 'vec2' ],
  27802. [ 3, 'vec3' ],
  27803. [ 4, 'vec4' ],
  27804. [ 9, 'mat3' ],
  27805. [ 16, 'mat4' ]
  27806. ] );
  27807. const typeFromArray = new Map( [
  27808. [ Int8Array, 'int' ],
  27809. [ Int16Array, 'int' ],
  27810. [ Int32Array, 'int' ],
  27811. [ Uint8Array, 'uint' ],
  27812. [ Uint16Array, 'uint' ],
  27813. [ Uint32Array, 'uint' ],
  27814. [ Float32Array, 'float' ]
  27815. ] );
  27816. const toFloat = ( value ) => {
  27817. value = Number( value );
  27818. return value + ( value % 1 ? '' : '.0' );
  27819. };
  27820. class NodeBuilder {
  27821. constructor( object, renderer, parser ) {
  27822. this.object = object;
  27823. this.material = ( object && object.material ) || null;
  27824. this.geometry = ( object && object.geometry ) || null;
  27825. this.renderer = renderer;
  27826. this.parser = parser;
  27827. this.scene = null;
  27828. this.camera = null;
  27829. this.nodes = [];
  27830. this.updateNodes = [];
  27831. this.updateBeforeNodes = [];
  27832. this.updateAfterNodes = [];
  27833. this.hashNodes = {};
  27834. this.lightsNode = null;
  27835. this.environmentNode = null;
  27836. this.fogNode = null;
  27837. this.clippingContext = null;
  27838. this.vertexShader = null;
  27839. this.fragmentShader = null;
  27840. this.computeShader = null;
  27841. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  27842. this.flowCode = { vertex: '', fragment: '', compute: '' };
  27843. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  27844. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  27845. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  27846. this.bindingsIndexes = {};
  27847. this.bindGroups = null;
  27848. this.attributes = [];
  27849. this.bufferAttributes = [];
  27850. this.varyings = [];
  27851. this.codes = {};
  27852. this.vars = {};
  27853. this.flow = { code: '' };
  27854. this.chaining = [];
  27855. this.stack = stack();
  27856. this.stacks = [];
  27857. this.tab = '\t';
  27858. this.instanceBindGroups = true;
  27859. this.currentFunctionNode = null;
  27860. this.context = {
  27861. keywords: new NodeKeywords(),
  27862. material: this.material
  27863. };
  27864. this.cache = new NodeCache();
  27865. this.globalCache = this.cache;
  27866. this.flowsData = new WeakMap();
  27867. this.shaderStage = null;
  27868. this.buildStage = null;
  27869. }
  27870. getBingGroupsCache() {
  27871. let bindGroupsCache = rendererCache.get( this.renderer );
  27872. if ( bindGroupsCache === undefined ) {
  27873. bindGroupsCache = new ChainMap();
  27874. rendererCache.set( this.renderer, bindGroupsCache );
  27875. }
  27876. return bindGroupsCache;
  27877. }
  27878. createRenderTarget( width, height, options ) {
  27879. return new RenderTarget( width, height, options );
  27880. }
  27881. createCubeRenderTarget( size, options ) {
  27882. return new CubeRenderTarget( size, options );
  27883. }
  27884. createPMREMGenerator() {
  27885. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  27886. return new PMREMGenerator( this.renderer );
  27887. }
  27888. includes( node ) {
  27889. return this.nodes.includes( node );
  27890. }
  27891. _getBindGroup( groupName, bindings ) {
  27892. const bindGroupsCache = this.getBingGroupsCache();
  27893. //
  27894. const bindingsArray = [];
  27895. let sharedGroup = true;
  27896. for ( const binding of bindings ) {
  27897. bindingsArray.push( binding );
  27898. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  27899. }
  27900. //
  27901. let bindGroup;
  27902. if ( sharedGroup ) {
  27903. bindGroup = bindGroupsCache.get( bindingsArray );
  27904. if ( bindGroup === undefined ) {
  27905. bindGroup = new BindGroup( groupName, bindingsArray );
  27906. bindGroupsCache.set( bindingsArray, bindGroup );
  27907. }
  27908. } else {
  27909. bindGroup = new BindGroup( groupName, bindingsArray );
  27910. }
  27911. return bindGroup;
  27912. }
  27913. getBindGroupArray( groupName, shaderStage ) {
  27914. const bindings = this.bindings[ shaderStage ];
  27915. let bindGroup = bindings[ groupName ];
  27916. if ( bindGroup === undefined ) {
  27917. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  27918. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  27919. }
  27920. bindings[ groupName ] = bindGroup = [];
  27921. }
  27922. return bindGroup;
  27923. }
  27924. getBindings() {
  27925. let bindingsGroups = this.bindGroups;
  27926. if ( bindingsGroups === null ) {
  27927. const groups = {};
  27928. const bindings = this.bindings;
  27929. for ( const shaderStage of shaderStages ) {
  27930. for ( const groupName in bindings[ shaderStage ] ) {
  27931. const uniforms = bindings[ shaderStage ][ groupName ];
  27932. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  27933. groupUniforms.push( ...uniforms );
  27934. }
  27935. }
  27936. bindingsGroups = [];
  27937. for ( const groupName in groups ) {
  27938. const group = groups[ groupName ];
  27939. const bindingsGroup = this._getBindGroup( groupName, group );
  27940. bindingsGroups.push( bindingsGroup );
  27941. }
  27942. this.bindGroups = bindingsGroups;
  27943. }
  27944. return bindingsGroups;
  27945. }
  27946. setHashNode( node, hash ) {
  27947. this.hashNodes[ hash ] = node;
  27948. }
  27949. addNode( node ) {
  27950. if ( this.nodes.includes( node ) === false ) {
  27951. this.nodes.push( node );
  27952. this.setHashNode( node, node.getHash( this ) );
  27953. }
  27954. }
  27955. buildUpdateNodes() {
  27956. for ( const node of this.nodes ) {
  27957. const updateType = node.getUpdateType();
  27958. const updateBeforeType = node.getUpdateBeforeType();
  27959. const updateAfterType = node.getUpdateAfterType();
  27960. if ( updateType !== NodeUpdateType.NONE ) {
  27961. this.updateNodes.push( node.getSelf() );
  27962. }
  27963. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  27964. this.updateBeforeNodes.push( node );
  27965. }
  27966. if ( updateAfterType !== NodeUpdateType.NONE ) {
  27967. this.updateAfterNodes.push( node );
  27968. }
  27969. }
  27970. }
  27971. get currentNode() {
  27972. return this.chaining[ this.chaining.length - 1 ];
  27973. }
  27974. isFilteredTexture( texture ) {
  27975. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  27976. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  27977. }
  27978. addChain( node ) {
  27979. /*
  27980. if ( this.chaining.indexOf( node ) !== - 1 ) {
  27981. console.warn( 'Recursive node: ', node );
  27982. }
  27983. */
  27984. this.chaining.push( node );
  27985. }
  27986. removeChain( node ) {
  27987. const lastChain = this.chaining.pop();
  27988. if ( lastChain !== node ) {
  27989. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  27990. }
  27991. }
  27992. getMethod( method ) {
  27993. return method;
  27994. }
  27995. getNodeFromHash( hash ) {
  27996. return this.hashNodes[ hash ];
  27997. }
  27998. addFlow( shaderStage, node ) {
  27999. this.flowNodes[ shaderStage ].push( node );
  28000. return node;
  28001. }
  28002. setContext( context ) {
  28003. this.context = context;
  28004. }
  28005. getContext() {
  28006. return this.context;
  28007. }
  28008. getSharedContext() {
  28009. ({ ...this.context });
  28010. return this.context;
  28011. }
  28012. setCache( cache ) {
  28013. this.cache = cache;
  28014. }
  28015. getCache() {
  28016. return this.cache;
  28017. }
  28018. getCacheFromNode( node, parent = true ) {
  28019. const data = this.getDataFromNode( node );
  28020. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  28021. return data.cache;
  28022. }
  28023. isAvailable( /*name*/ ) {
  28024. return false;
  28025. }
  28026. getVertexIndex() {
  28027. console.warn( 'Abstract function.' );
  28028. }
  28029. getInstanceIndex() {
  28030. console.warn( 'Abstract function.' );
  28031. }
  28032. getDrawIndex() {
  28033. console.warn( 'Abstract function.' );
  28034. }
  28035. getFrontFacing() {
  28036. console.warn( 'Abstract function.' );
  28037. }
  28038. getFragCoord() {
  28039. console.warn( 'Abstract function.' );
  28040. }
  28041. isFlipY() {
  28042. return false;
  28043. }
  28044. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  28045. console.warn( 'Abstract function.' );
  28046. }
  28047. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  28048. console.warn( 'Abstract function.' );
  28049. }
  28050. generateConst( type, value = null ) {
  28051. if ( value === null ) {
  28052. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  28053. else if ( type === 'bool' ) value = false;
  28054. else if ( type === 'color' ) value = new Color();
  28055. else if ( type === 'vec2' ) value = new Vector2();
  28056. else if ( type === 'vec3' ) value = new Vector3();
  28057. else if ( type === 'vec4' ) value = new Vector4();
  28058. }
  28059. if ( type === 'float' ) return toFloat( value );
  28060. if ( type === 'int' ) return `${ Math.round( value ) }`;
  28061. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  28062. if ( type === 'bool' ) return value ? 'true' : 'false';
  28063. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  28064. const typeLength = this.getTypeLength( type );
  28065. const componentType = this.getComponentType( type );
  28066. const generateConst = value => this.generateConst( componentType, value );
  28067. if ( typeLength === 2 ) {
  28068. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  28069. } else if ( typeLength === 3 ) {
  28070. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  28071. } else if ( typeLength === 4 ) {
  28072. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  28073. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  28074. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  28075. } else if ( typeLength > 4 ) {
  28076. return `${ this.getType( type ) }()`;
  28077. }
  28078. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  28079. }
  28080. getType( type ) {
  28081. if ( type === 'color' ) return 'vec3';
  28082. return type;
  28083. }
  28084. hasGeometryAttribute( name ) {
  28085. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  28086. }
  28087. getAttribute( name, type ) {
  28088. const attributes = this.attributes;
  28089. // find attribute
  28090. for ( const attribute of attributes ) {
  28091. if ( attribute.name === name ) {
  28092. return attribute;
  28093. }
  28094. }
  28095. // create a new if no exist
  28096. const attribute = new NodeAttribute( name, type );
  28097. attributes.push( attribute );
  28098. return attribute;
  28099. }
  28100. getPropertyName( node/*, shaderStage*/ ) {
  28101. return node.name;
  28102. }
  28103. isVector( type ) {
  28104. return /vec\d/.test( type );
  28105. }
  28106. isMatrix( type ) {
  28107. return /mat\d/.test( type );
  28108. }
  28109. isReference( type ) {
  28110. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  28111. }
  28112. needsColorSpaceToLinear( /*texture*/ ) {
  28113. return false;
  28114. }
  28115. getComponentTypeFromTexture( texture ) {
  28116. const type = texture.type;
  28117. if ( texture.isDataTexture ) {
  28118. if ( type === IntType ) return 'int';
  28119. if ( type === UnsignedIntType ) return 'uint';
  28120. }
  28121. return 'float';
  28122. }
  28123. getElementType( type ) {
  28124. if ( type === 'mat2' ) return 'vec2';
  28125. if ( type === 'mat3' ) return 'vec3';
  28126. if ( type === 'mat4' ) return 'vec4';
  28127. return this.getComponentType( type );
  28128. }
  28129. getComponentType( type ) {
  28130. type = this.getVectorType( type );
  28131. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  28132. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  28133. if ( componentType === null ) return null;
  28134. if ( componentType[ 1 ] === 'b' ) return 'bool';
  28135. if ( componentType[ 1 ] === 'i' ) return 'int';
  28136. if ( componentType[ 1 ] === 'u' ) return 'uint';
  28137. return 'float';
  28138. }
  28139. getVectorType( type ) {
  28140. if ( type === 'color' ) return 'vec3';
  28141. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  28142. return type;
  28143. }
  28144. getTypeFromLength( length, componentType = 'float' ) {
  28145. if ( length === 1 ) return componentType;
  28146. const baseType = typeFromLength.get( length );
  28147. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  28148. return prefix + baseType;
  28149. }
  28150. getTypeFromArray( array ) {
  28151. return typeFromArray.get( array.constructor );
  28152. }
  28153. getTypeFromAttribute( attribute ) {
  28154. let dataAttribute = attribute;
  28155. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  28156. const array = dataAttribute.array;
  28157. const itemSize = attribute.itemSize;
  28158. const normalized = attribute.normalized;
  28159. let arrayType;
  28160. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  28161. arrayType = this.getTypeFromArray( array );
  28162. }
  28163. return this.getTypeFromLength( itemSize, arrayType );
  28164. }
  28165. getTypeLength( type ) {
  28166. const vecType = this.getVectorType( type );
  28167. const vecNum = /vec([2-4])/.exec( vecType );
  28168. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  28169. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  28170. if ( /mat2/.test( type ) === true ) return 4;
  28171. if ( /mat3/.test( type ) === true ) return 9;
  28172. if ( /mat4/.test( type ) === true ) return 16;
  28173. return 0;
  28174. }
  28175. getVectorFromMatrix( type ) {
  28176. return type.replace( 'mat', 'vec' );
  28177. }
  28178. changeComponentType( type, newComponentType ) {
  28179. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  28180. }
  28181. getIntegerType( type ) {
  28182. const componentType = this.getComponentType( type );
  28183. if ( componentType === 'int' || componentType === 'uint' ) return type;
  28184. return this.changeComponentType( type, 'int' );
  28185. }
  28186. addStack() {
  28187. this.stack = stack( this.stack );
  28188. this.stacks.push( getCurrentStack() || this.stack );
  28189. setCurrentStack( this.stack );
  28190. return this.stack;
  28191. }
  28192. removeStack() {
  28193. const lastStack = this.stack;
  28194. this.stack = lastStack.parent;
  28195. setCurrentStack( this.stacks.pop() );
  28196. return lastStack;
  28197. }
  28198. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  28199. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  28200. let nodeData = cache.getData( node );
  28201. if ( nodeData === undefined ) {
  28202. nodeData = {};
  28203. cache.setData( node, nodeData );
  28204. }
  28205. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  28206. return nodeData[ shaderStage ];
  28207. }
  28208. getNodeProperties( node, shaderStage = 'any' ) {
  28209. const nodeData = this.getDataFromNode( node, shaderStage );
  28210. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  28211. }
  28212. getBufferAttributeFromNode( node, type ) {
  28213. const nodeData = this.getDataFromNode( node );
  28214. let bufferAttribute = nodeData.bufferAttribute;
  28215. if ( bufferAttribute === undefined ) {
  28216. const index = this.uniforms.index ++;
  28217. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  28218. this.bufferAttributes.push( bufferAttribute );
  28219. nodeData.bufferAttribute = bufferAttribute;
  28220. }
  28221. return bufferAttribute;
  28222. }
  28223. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  28224. const nodeData = this.getDataFromNode( node, shaderStage );
  28225. if ( nodeData.structType === undefined ) {
  28226. const index = this.structs.index ++;
  28227. node.name = `StructType${ index }`;
  28228. this.structs[ shaderStage ].push( node );
  28229. nodeData.structType = node;
  28230. }
  28231. return node;
  28232. }
  28233. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  28234. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  28235. let nodeUniform = nodeData.uniform;
  28236. if ( nodeUniform === undefined ) {
  28237. const index = this.uniforms.index ++;
  28238. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  28239. this.uniforms[ shaderStage ].push( nodeUniform );
  28240. nodeData.uniform = nodeUniform;
  28241. }
  28242. return nodeUniform;
  28243. }
  28244. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  28245. const nodeData = this.getDataFromNode( node, shaderStage );
  28246. let nodeVar = nodeData.variable;
  28247. if ( nodeVar === undefined ) {
  28248. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  28249. if ( name === null ) name = 'nodeVar' + vars.length;
  28250. nodeVar = new NodeVar( name, type );
  28251. vars.push( nodeVar );
  28252. nodeData.variable = nodeVar;
  28253. }
  28254. return nodeVar;
  28255. }
  28256. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  28257. const nodeData = this.getDataFromNode( node, 'any' );
  28258. let nodeVarying = nodeData.varying;
  28259. if ( nodeVarying === undefined ) {
  28260. const varyings = this.varyings;
  28261. const index = varyings.length;
  28262. if ( name === null ) name = 'nodeVarying' + index;
  28263. nodeVarying = new NodeVarying( name, type );
  28264. varyings.push( nodeVarying );
  28265. nodeData.varying = nodeVarying;
  28266. }
  28267. return nodeVarying;
  28268. }
  28269. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  28270. const nodeData = this.getDataFromNode( node );
  28271. let nodeCode = nodeData.code;
  28272. if ( nodeCode === undefined ) {
  28273. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  28274. const index = codes.length;
  28275. nodeCode = new NodeCode( 'nodeCode' + index, type );
  28276. codes.push( nodeCode );
  28277. nodeData.code = nodeCode;
  28278. }
  28279. return nodeCode;
  28280. }
  28281. addLineFlowCode( code ) {
  28282. if ( code === '' ) return this;
  28283. code = this.tab + code;
  28284. if ( ! /;\s*$/.test( code ) ) {
  28285. code = code + ';\n';
  28286. }
  28287. this.flow.code += code;
  28288. return this;
  28289. }
  28290. addFlowCode( code ) {
  28291. this.flow.code += code;
  28292. return this;
  28293. }
  28294. addFlowTab() {
  28295. this.tab += '\t';
  28296. return this;
  28297. }
  28298. removeFlowTab() {
  28299. this.tab = this.tab.slice( 0, - 1 );
  28300. return this;
  28301. }
  28302. getFlowData( node/*, shaderStage*/ ) {
  28303. return this.flowsData.get( node );
  28304. }
  28305. flowNode( node ) {
  28306. const output = node.getNodeType( this );
  28307. const flowData = this.flowChildNode( node, output );
  28308. this.flowsData.set( node, flowData );
  28309. return flowData;
  28310. }
  28311. buildFunctionNode( shaderNode ) {
  28312. const fn = new FunctionNode();
  28313. const previous = this.currentFunctionNode;
  28314. this.currentFunctionNode = fn;
  28315. fn.code = this.buildFunctionCode( shaderNode );
  28316. this.currentFunctionNode = previous;
  28317. return fn;
  28318. }
  28319. flowShaderNode( shaderNode ) {
  28320. const layout = shaderNode.layout;
  28321. let inputs;
  28322. if ( shaderNode.isArrayInput ) {
  28323. inputs = [];
  28324. for ( const input of layout.inputs ) {
  28325. inputs.push( new ParameterNode( input.type, input.name ) );
  28326. }
  28327. } else {
  28328. inputs = {};
  28329. for ( const input of layout.inputs ) {
  28330. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  28331. }
  28332. }
  28333. //
  28334. shaderNode.layout = null;
  28335. const callNode = shaderNode.call( inputs );
  28336. const flowData = this.flowStagesNode( callNode, layout.type );
  28337. shaderNode.layout = layout;
  28338. return flowData;
  28339. }
  28340. flowStagesNode( node, output = null ) {
  28341. const previousFlow = this.flow;
  28342. const previousVars = this.vars;
  28343. const previousCache = this.cache;
  28344. const previousBuildStage = this.buildStage;
  28345. const previousStack = this.stack;
  28346. const flow = {
  28347. code: ''
  28348. };
  28349. this.flow = flow;
  28350. this.vars = {};
  28351. this.cache = new NodeCache();
  28352. this.stack = stack();
  28353. for ( const buildStage of defaultBuildStages ) {
  28354. this.setBuildStage( buildStage );
  28355. flow.result = node.build( this, output );
  28356. }
  28357. flow.vars = this.getVars( this.shaderStage );
  28358. this.flow = previousFlow;
  28359. this.vars = previousVars;
  28360. this.cache = previousCache;
  28361. this.stack = previousStack;
  28362. this.setBuildStage( previousBuildStage );
  28363. return flow;
  28364. }
  28365. getFunctionOperator() {
  28366. return null;
  28367. }
  28368. flowChildNode( node, output = null ) {
  28369. const previousFlow = this.flow;
  28370. const flow = {
  28371. code: ''
  28372. };
  28373. this.flow = flow;
  28374. flow.result = node.build( this, output );
  28375. this.flow = previousFlow;
  28376. return flow;
  28377. }
  28378. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  28379. const previousShaderStage = this.shaderStage;
  28380. this.setShaderStage( shaderStage );
  28381. const flowData = this.flowChildNode( node, output );
  28382. if ( propertyName !== null ) {
  28383. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  28384. }
  28385. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  28386. this.setShaderStage( previousShaderStage );
  28387. return flowData;
  28388. }
  28389. getAttributesArray() {
  28390. return this.attributes.concat( this.bufferAttributes );
  28391. }
  28392. getAttributes( /*shaderStage*/ ) {
  28393. console.warn( 'Abstract function.' );
  28394. }
  28395. getVaryings( /*shaderStage*/ ) {
  28396. console.warn( 'Abstract function.' );
  28397. }
  28398. getVar( type, name ) {
  28399. return `${ this.getType( type ) } ${ name }`;
  28400. }
  28401. getVars( shaderStage ) {
  28402. let snippet = '';
  28403. const vars = this.vars[ shaderStage ];
  28404. if ( vars !== undefined ) {
  28405. for ( const variable of vars ) {
  28406. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  28407. }
  28408. }
  28409. return snippet;
  28410. }
  28411. getUniforms( /*shaderStage*/ ) {
  28412. console.warn( 'Abstract function.' );
  28413. }
  28414. getCodes( shaderStage ) {
  28415. const codes = this.codes[ shaderStage ];
  28416. let code = '';
  28417. if ( codes !== undefined ) {
  28418. for ( const nodeCode of codes ) {
  28419. code += nodeCode.code + '\n';
  28420. }
  28421. }
  28422. return code;
  28423. }
  28424. getHash() {
  28425. return this.vertexShader + this.fragmentShader + this.computeShader;
  28426. }
  28427. setShaderStage( shaderStage ) {
  28428. this.shaderStage = shaderStage;
  28429. }
  28430. getShaderStage() {
  28431. return this.shaderStage;
  28432. }
  28433. setBuildStage( buildStage ) {
  28434. this.buildStage = buildStage;
  28435. }
  28436. getBuildStage() {
  28437. return this.buildStage;
  28438. }
  28439. buildCode() {
  28440. console.warn( 'Abstract function.' );
  28441. }
  28442. build() {
  28443. const { object, material } = this;
  28444. if ( material !== null ) {
  28445. NodeMaterial.fromMaterial( material ).build( this );
  28446. } else {
  28447. this.addFlow( 'compute', object );
  28448. }
  28449. // setup() -> stage 1: create possible new nodes and returns an output reference node
  28450. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  28451. // generate() -> stage 3: generate shader
  28452. for ( const buildStage of defaultBuildStages ) {
  28453. this.setBuildStage( buildStage );
  28454. if ( this.context.vertex && this.context.vertex.isNode ) {
  28455. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  28456. }
  28457. for ( const shaderStage of shaderStages ) {
  28458. this.setShaderStage( shaderStage );
  28459. const flowNodes = this.flowNodes[ shaderStage ];
  28460. for ( const node of flowNodes ) {
  28461. if ( buildStage === 'generate' ) {
  28462. this.flowNode( node );
  28463. } else {
  28464. node.build( this );
  28465. }
  28466. }
  28467. }
  28468. }
  28469. this.setBuildStage( null );
  28470. this.setShaderStage( null );
  28471. // stage 4: build code for a specific output
  28472. this.buildCode();
  28473. this.buildUpdateNodes();
  28474. return this;
  28475. }
  28476. getNodeUniform( uniformNode, type ) {
  28477. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  28478. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  28479. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  28480. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  28481. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  28482. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  28483. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  28484. throw new Error( `Uniform "${type}" not declared.` );
  28485. }
  28486. createNodeMaterial( type = 'NodeMaterial' ) {
  28487. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28488. return createNodeMaterialFromType( type );
  28489. }
  28490. format( snippet, fromType, toType ) {
  28491. fromType = this.getVectorType( fromType );
  28492. toType = this.getVectorType( toType );
  28493. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  28494. return snippet;
  28495. }
  28496. const fromTypeLength = this.getTypeLength( fromType );
  28497. const toTypeLength = this.getTypeLength( toType );
  28498. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  28499. // @TODO: ignore for now
  28500. return snippet;
  28501. }
  28502. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  28503. // @TODO: ignore for now
  28504. return snippet;
  28505. }
  28506. if ( fromTypeLength === toTypeLength ) {
  28507. return `${ this.getType( toType ) }( ${ snippet } )`;
  28508. }
  28509. if ( fromTypeLength > toTypeLength ) {
  28510. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  28511. }
  28512. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  28513. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  28514. }
  28515. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  28516. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  28517. }
  28518. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  28519. // convert a number value to vector type, e.g:
  28520. // vec3( 1u ) -> vec3( float( 1u ) )
  28521. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  28522. }
  28523. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  28524. }
  28525. getSignature() {
  28526. return `// Three.js r${ REVISION } - Node System\n`;
  28527. }
  28528. }
  28529. class NodeFrame {
  28530. constructor() {
  28531. this.time = 0;
  28532. this.deltaTime = 0;
  28533. this.frameId = 0;
  28534. this.renderId = 0;
  28535. this.startTime = null;
  28536. this.updateMap = new WeakMap();
  28537. this.updateBeforeMap = new WeakMap();
  28538. this.updateAfterMap = new WeakMap();
  28539. this.renderer = null;
  28540. this.material = null;
  28541. this.camera = null;
  28542. this.object = null;
  28543. this.scene = null;
  28544. }
  28545. _getMaps( referenceMap, nodeRef ) {
  28546. let maps = referenceMap.get( nodeRef );
  28547. if ( maps === undefined ) {
  28548. maps = {
  28549. renderMap: new WeakMap(),
  28550. frameMap: new WeakMap()
  28551. };
  28552. referenceMap.set( nodeRef, maps );
  28553. }
  28554. return maps;
  28555. }
  28556. updateBeforeNode( node ) {
  28557. const updateType = node.getUpdateBeforeType();
  28558. const reference = node.updateReference( this );
  28559. if ( updateType === NodeUpdateType.FRAME ) {
  28560. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  28561. if ( frameMap.get( reference ) !== this.frameId ) {
  28562. if ( node.updateBefore( this ) !== false ) {
  28563. frameMap.set( reference, this.frameId );
  28564. }
  28565. }
  28566. } else if ( updateType === NodeUpdateType.RENDER ) {
  28567. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  28568. if ( renderMap.get( reference ) !== this.renderId ) {
  28569. if ( node.updateBefore( this ) !== false ) {
  28570. renderMap.set( reference, this.renderId );
  28571. }
  28572. }
  28573. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28574. node.updateBefore( this );
  28575. }
  28576. }
  28577. updateAfterNode( node ) {
  28578. const updateType = node.getUpdateAfterType();
  28579. const reference = node.updateReference( this );
  28580. if ( updateType === NodeUpdateType.FRAME ) {
  28581. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  28582. if ( frameMap.get( reference ) !== this.frameId ) {
  28583. if ( node.updateAfter( this ) !== false ) {
  28584. frameMap.set( reference, this.frameId );
  28585. }
  28586. }
  28587. } else if ( updateType === NodeUpdateType.RENDER ) {
  28588. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  28589. if ( renderMap.get( reference ) !== this.renderId ) {
  28590. if ( node.updateAfter( this ) !== false ) {
  28591. renderMap.set( reference, this.renderId );
  28592. }
  28593. }
  28594. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28595. node.updateAfter( this );
  28596. }
  28597. }
  28598. updateNode( node ) {
  28599. const updateType = node.getUpdateType();
  28600. const reference = node.updateReference( this );
  28601. if ( updateType === NodeUpdateType.FRAME ) {
  28602. const { frameMap } = this._getMaps( this.updateMap, reference );
  28603. if ( frameMap.get( reference ) !== this.frameId ) {
  28604. if ( node.update( this ) !== false ) {
  28605. frameMap.set( reference, this.frameId );
  28606. }
  28607. }
  28608. } else if ( updateType === NodeUpdateType.RENDER ) {
  28609. const { renderMap } = this._getMaps( this.updateMap, reference );
  28610. if ( renderMap.get( reference ) !== this.renderId ) {
  28611. if ( node.update( this ) !== false ) {
  28612. renderMap.set( reference, this.renderId );
  28613. }
  28614. }
  28615. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28616. node.update( this );
  28617. }
  28618. }
  28619. update() {
  28620. this.frameId ++;
  28621. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  28622. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  28623. this.lastTime = performance.now();
  28624. this.time += this.deltaTime;
  28625. }
  28626. }
  28627. class NodeFunctionInput {
  28628. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  28629. this.type = type;
  28630. this.name = name;
  28631. this.count = count;
  28632. this.qualifier = qualifier;
  28633. this.isConst = isConst;
  28634. }
  28635. }
  28636. NodeFunctionInput.isNodeFunctionInput = true;
  28637. class StructTypeNode extends Node {
  28638. constructor( types ) {
  28639. super();
  28640. this.types = types;
  28641. this.isStructTypeNode = true;
  28642. }
  28643. getMemberTypes() {
  28644. return this.types;
  28645. }
  28646. }
  28647. addNodeClass( 'StructTypeNode', StructTypeNode );
  28648. class OutputStructNode extends Node {
  28649. constructor( ...members ) {
  28650. super();
  28651. this.members = members;
  28652. this.isOutputStructNode = true;
  28653. }
  28654. setup( builder ) {
  28655. super.setup( builder );
  28656. const members = this.members;
  28657. const types = [];
  28658. for ( let i = 0; i < members.length; i ++ ) {
  28659. types.push( members[ i ].getNodeType( builder ) );
  28660. }
  28661. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  28662. }
  28663. generate( builder, output ) {
  28664. const propertyName = builder.getOutputStructName();
  28665. const members = this.members;
  28666. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  28667. for ( let i = 0; i < members.length; i ++ ) {
  28668. const snippet = members[ i ].build( builder, output );
  28669. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  28670. }
  28671. return propertyName;
  28672. }
  28673. }
  28674. const outputStruct = nodeProxy( OutputStructNode );
  28675. addNodeClass( 'OutputStructNode', OutputStructNode );
  28676. class HashNode extends Node {
  28677. constructor( seedNode ) {
  28678. super();
  28679. this.seedNode = seedNode;
  28680. }
  28681. setup( /*builder*/ ) {
  28682. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  28683. const state = this.seedNode.toUint().mul( 747796405 ).add( 2891336453 );
  28684. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  28685. const result = word.shiftRight( 22 ).bitXor( word );
  28686. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  28687. }
  28688. }
  28689. const hash = nodeProxy( HashNode );
  28690. addNodeElement( 'hash', hash );
  28691. addNodeClass( 'HashNode', HashNode );
  28692. // remapping functions https://iquilezles.org/articles/functions/
  28693. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  28694. 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 ) );
  28695. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  28696. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  28697. addNodeElement( 'parabola', parabola );
  28698. addNodeElement( 'gain', gain );
  28699. addNodeElement( 'pcurve', pcurve );
  28700. addNodeElement( 'sinc', sinc );
  28701. // https://github.com/cabbibo/glsl-tri-noise-3d
  28702. const tri = tslFn( ( [ x ] ) => {
  28703. return x.fract().sub( .5 ).abs();
  28704. } );
  28705. const tri3 = tslFn( ( [ p ] ) => {
  28706. 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. ) ) ) ) );
  28707. } );
  28708. const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => {
  28709. const p = vec3( p_immutable ).toVar();
  28710. const z = float( 1.4 ).toVar();
  28711. const rz = float( 0.0 ).toVar();
  28712. const bp = vec3( p ).toVar();
  28713. loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  28714. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  28715. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  28716. bp.mulAssign( 1.8 );
  28717. z.mulAssign( 1.5 );
  28718. p.mulAssign( 1.2 );
  28719. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  28720. rz.addAssign( t.div( z ) );
  28721. bp.addAssign( 0.14 );
  28722. } );
  28723. return rz;
  28724. } );
  28725. // layouts
  28726. tri.setLayout( {
  28727. name: 'tri',
  28728. type: 'float',
  28729. inputs: [
  28730. { name: 'x', type: 'float' }
  28731. ]
  28732. } );
  28733. tri3.setLayout( {
  28734. name: 'tri3',
  28735. type: 'vec3',
  28736. inputs: [
  28737. { name: 'p', type: 'vec3' }
  28738. ]
  28739. } );
  28740. triNoise3D.setLayout( {
  28741. name: 'triNoise3D',
  28742. type: 'float',
  28743. inputs: [
  28744. { name: 'p', type: 'vec3' },
  28745. { name: 'spd', type: 'float' },
  28746. { name: 'time', type: 'float' }
  28747. ]
  28748. } );
  28749. let discardExpression;
  28750. class DiscardNode extends CondNode {
  28751. constructor( condNode ) {
  28752. discardExpression = discardExpression || expression( 'discard' );
  28753. super( condNode, discardExpression );
  28754. }
  28755. }
  28756. const inlineDiscard = nodeProxy( DiscardNode );
  28757. const discard = ( condNode ) => inlineDiscard( condNode ).append();
  28758. const Return = () => expression( 'return' ).append();
  28759. addNodeElement( 'discard', discard ); // @TODO: Check... this cause a little confusing using in chaining
  28760. addNodeClass( 'DiscardNode', DiscardNode );
  28761. class FunctionOverloadingNode extends Node {
  28762. constructor( functionNodes = [], ...parametersNodes ) {
  28763. super();
  28764. this.functionNodes = functionNodes;
  28765. this.parametersNodes = parametersNodes;
  28766. this._candidateFnCall = null;
  28767. this.global = true;
  28768. }
  28769. getNodeType() {
  28770. return this.functionNodes[ 0 ].shaderNode.layout.type;
  28771. }
  28772. setup( builder ) {
  28773. const params = this.parametersNodes;
  28774. let candidateFnCall = this._candidateFnCall;
  28775. if ( candidateFnCall === null ) {
  28776. let candidateFn = null;
  28777. let candidateScore = - 1;
  28778. for ( const functionNode of this.functionNodes ) {
  28779. const shaderNode = functionNode.shaderNode;
  28780. const layout = shaderNode.layout;
  28781. if ( layout === null ) {
  28782. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  28783. }
  28784. const inputs = layout.inputs;
  28785. if ( params.length === inputs.length ) {
  28786. let score = 0;
  28787. for ( let i = 0; i < params.length; i ++ ) {
  28788. const param = params[ i ];
  28789. const input = inputs[ i ];
  28790. if ( param.getNodeType( builder ) === input.type ) {
  28791. score ++;
  28792. } else {
  28793. score = 0;
  28794. }
  28795. }
  28796. if ( score > candidateScore ) {
  28797. candidateFn = functionNode;
  28798. candidateScore = score;
  28799. }
  28800. }
  28801. }
  28802. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  28803. }
  28804. return candidateFnCall;
  28805. }
  28806. }
  28807. const overloadingBaseFn = nodeProxy( FunctionOverloadingNode );
  28808. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  28809. addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode );
  28810. class MatcapUVNode extends TempNode {
  28811. constructor() {
  28812. super( 'vec2' );
  28813. }
  28814. setup() {
  28815. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28816. const y = positionViewDirection.cross( x );
  28817. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28818. }
  28819. }
  28820. const matcapUV = nodeImmutable( MatcapUVNode );
  28821. addNodeClass( 'MatcapUVNode', MatcapUVNode );
  28822. class TimerNode extends UniformNode {
  28823. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  28824. super( value );
  28825. this.scope = scope;
  28826. this.scale = scale;
  28827. this.updateType = NodeUpdateType.FRAME;
  28828. }
  28829. /*
  28830. @TODO:
  28831. getNodeType( builder ) {
  28832. const scope = this.scope;
  28833. if ( scope === TimerNode.FRAME ) {
  28834. return 'uint';
  28835. }
  28836. return 'float';
  28837. }
  28838. */
  28839. update( frame ) {
  28840. const scope = this.scope;
  28841. const scale = this.scale;
  28842. if ( scope === TimerNode.LOCAL ) {
  28843. this.value += frame.deltaTime * scale;
  28844. } else if ( scope === TimerNode.DELTA ) {
  28845. this.value = frame.deltaTime * scale;
  28846. } else if ( scope === TimerNode.FRAME ) {
  28847. this.value = frame.frameId;
  28848. } else {
  28849. // global
  28850. this.value = frame.time * scale;
  28851. }
  28852. }
  28853. serialize( data ) {
  28854. super.serialize( data );
  28855. data.scope = this.scope;
  28856. data.scale = this.scale;
  28857. }
  28858. deserialize( data ) {
  28859. super.deserialize( data );
  28860. this.scope = data.scope;
  28861. this.scale = data.scale;
  28862. }
  28863. }
  28864. TimerNode.LOCAL = 'local';
  28865. TimerNode.GLOBAL = 'global';
  28866. TimerNode.DELTA = 'delta';
  28867. TimerNode.FRAME = 'frame';
  28868. // @TODO: add support to use node in timeScale
  28869. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  28870. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  28871. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  28872. const frameId = nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  28873. addNodeClass( 'TimerNode', TimerNode );
  28874. class OscNode extends Node {
  28875. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  28876. super();
  28877. this.method = method;
  28878. this.timeNode = timeNode;
  28879. }
  28880. getNodeType( builder ) {
  28881. return this.timeNode.getNodeType( builder );
  28882. }
  28883. setup() {
  28884. const method = this.method;
  28885. const timeNode = nodeObject( this.timeNode );
  28886. let outputNode = null;
  28887. if ( method === OscNode.SINE ) {
  28888. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  28889. } else if ( method === OscNode.SQUARE ) {
  28890. outputNode = timeNode.fract().round();
  28891. } else if ( method === OscNode.TRIANGLE ) {
  28892. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  28893. } else if ( method === OscNode.SAWTOOTH ) {
  28894. outputNode = timeNode.fract();
  28895. }
  28896. return outputNode;
  28897. }
  28898. serialize( data ) {
  28899. super.serialize( data );
  28900. data.method = this.method;
  28901. }
  28902. deserialize( data ) {
  28903. super.deserialize( data );
  28904. this.method = data.method;
  28905. }
  28906. }
  28907. OscNode.SINE = 'sine';
  28908. OscNode.SQUARE = 'square';
  28909. OscNode.TRIANGLE = 'triangle';
  28910. OscNode.SAWTOOTH = 'sawtooth';
  28911. const oscSine = nodeProxy( OscNode, OscNode.SINE );
  28912. const oscSquare = nodeProxy( OscNode, OscNode.SQUARE );
  28913. const oscTriangle = nodeProxy( OscNode, OscNode.TRIANGLE );
  28914. const oscSawtooth = nodeProxy( OscNode, OscNode.SAWTOOTH );
  28915. addNodeClass( 'OscNode', OscNode );
  28916. class PackingNode extends TempNode {
  28917. constructor( scope, node ) {
  28918. super();
  28919. this.scope = scope;
  28920. this.node = node;
  28921. }
  28922. getNodeType( builder ) {
  28923. return this.node.getNodeType( builder );
  28924. }
  28925. setup() {
  28926. const { scope, node } = this;
  28927. let result = null;
  28928. if ( scope === PackingNode.DIRECTION_TO_COLOR ) {
  28929. result = node.mul( 0.5 ).add( 0.5 );
  28930. } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) {
  28931. result = node.mul( 2.0 ).sub( 1 );
  28932. }
  28933. return result;
  28934. }
  28935. }
  28936. PackingNode.DIRECTION_TO_COLOR = 'directionToColor';
  28937. PackingNode.COLOR_TO_DIRECTION = 'colorToDirection';
  28938. const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR );
  28939. const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION );
  28940. addNodeElement( 'directionToColor', directionToColor );
  28941. addNodeElement( 'colorToDirection', colorToDirection );
  28942. addNodeClass( 'PackingNode', PackingNode );
  28943. class RemapNode extends Node {
  28944. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  28945. super();
  28946. this.node = node;
  28947. this.inLowNode = inLowNode;
  28948. this.inHighNode = inHighNode;
  28949. this.outLowNode = outLowNode;
  28950. this.outHighNode = outHighNode;
  28951. this.doClamp = true;
  28952. }
  28953. setup() {
  28954. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  28955. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  28956. if ( doClamp === true ) t = t.clamp();
  28957. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  28958. }
  28959. }
  28960. const remap = nodeProxy( RemapNode, null, null, { doClamp: false } );
  28961. const remapClamp = nodeProxy( RemapNode );
  28962. addNodeElement( 'remap', remap );
  28963. addNodeElement( 'remapClamp', remapClamp );
  28964. addNodeClass( 'RemapNode', RemapNode );
  28965. class RotateUVNode extends TempNode {
  28966. constructor( uvNode, rotationNode, centerNode = vec2( 0.5 ) ) {
  28967. super( 'vec2' );
  28968. this.uvNode = uvNode;
  28969. this.rotationNode = rotationNode;
  28970. this.centerNode = centerNode;
  28971. }
  28972. setup() {
  28973. const { uvNode, rotationNode, centerNode } = this;
  28974. const vector = uvNode.sub( centerNode );
  28975. return vector.rotate( rotationNode ).add( centerNode );
  28976. }
  28977. }
  28978. const rotateUV = nodeProxy( RotateUVNode );
  28979. addNodeElement( 'rotateUV', rotateUV );
  28980. addNodeClass( 'RotateUVNode', RotateUVNode );
  28981. class RotateNode extends TempNode {
  28982. constructor( positionNode, rotationNode ) {
  28983. super();
  28984. this.positionNode = positionNode;
  28985. this.rotationNode = rotationNode;
  28986. }
  28987. getNodeType( builder ) {
  28988. return this.positionNode.getNodeType( builder );
  28989. }
  28990. setup( builder ) {
  28991. const { rotationNode, positionNode } = this;
  28992. const nodeType = this.getNodeType( builder );
  28993. if ( nodeType === 'vec2' ) {
  28994. const cosAngle = rotationNode.cos();
  28995. const sinAngle = rotationNode.sin();
  28996. const rotationMatrix = mat2(
  28997. cosAngle, sinAngle,
  28998. sinAngle.negate(), cosAngle
  28999. );
  29000. return rotationMatrix.mul( positionNode );
  29001. } else {
  29002. const rotation = rotationNode;
  29003. 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 ) );
  29004. 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 ) );
  29005. 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 ) );
  29006. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29007. }
  29008. }
  29009. }
  29010. const rotate = nodeProxy( RotateNode );
  29011. addNodeElement( 'rotate', rotate );
  29012. addNodeClass( 'RotateNode', RotateNode );
  29013. class SpriteSheetUVNode extends Node {
  29014. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  29015. super( 'vec2' );
  29016. this.countNode = countNode;
  29017. this.uvNode = uvNode;
  29018. this.frameNode = frameNode;
  29019. }
  29020. setup() {
  29021. const { frameNode, uvNode, countNode } = this;
  29022. const { width, height } = countNode;
  29023. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  29024. const column = frameNum.mod( width );
  29025. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  29026. const scale = countNode.reciprocal();
  29027. const uvFrameOffset = vec2( column, row );
  29028. return uvNode.add( uvFrameOffset ).mul( scale );
  29029. }
  29030. }
  29031. const spritesheetUV = nodeProxy( SpriteSheetUVNode );
  29032. addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode );
  29033. class StorageArrayElementNode extends ArrayElementNode {
  29034. constructor( storageBufferNode, indexNode ) {
  29035. super( storageBufferNode, indexNode );
  29036. this.isStorageArrayElementNode = true;
  29037. }
  29038. set storageBufferNode( value ) {
  29039. this.node = value;
  29040. }
  29041. get storageBufferNode() {
  29042. return this.node;
  29043. }
  29044. setup( builder ) {
  29045. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29046. if ( ! this.node.instanceIndex && this.node.bufferObject === true ) {
  29047. builder.setupPBO( this.node );
  29048. }
  29049. }
  29050. return super.setup( builder );
  29051. }
  29052. generate( builder, output ) {
  29053. let snippet;
  29054. const isAssignContext = builder.context.assign;
  29055. //
  29056. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29057. const { node } = this;
  29058. if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) {
  29059. snippet = builder.generatePBO( this );
  29060. } else {
  29061. snippet = node.build( builder );
  29062. }
  29063. } else {
  29064. snippet = super.generate( builder );
  29065. }
  29066. if ( isAssignContext !== true ) {
  29067. const type = this.getNodeType( builder );
  29068. snippet = builder.format( snippet, type, output );
  29069. }
  29070. return snippet;
  29071. }
  29072. }
  29073. const storageElement = nodeProxy( StorageArrayElementNode );
  29074. addNodeElement( 'storageElement', storageElement );
  29075. addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode );
  29076. class TriplanarTexturesNode extends Node {
  29077. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  29078. super( 'vec4' );
  29079. this.textureXNode = textureXNode;
  29080. this.textureYNode = textureYNode;
  29081. this.textureZNode = textureZNode;
  29082. this.scaleNode = scaleNode;
  29083. this.positionNode = positionNode;
  29084. this.normalNode = normalNode;
  29085. }
  29086. setup() {
  29087. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  29088. // Ref: https://github.com/keijiro/StandardTriplanar
  29089. // Blending factor of triplanar mapping
  29090. let bf = normalNode.abs().normalize();
  29091. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  29092. // Triplanar mapping
  29093. const tx = positionNode.yz.mul( scaleNode );
  29094. const ty = positionNode.zx.mul( scaleNode );
  29095. const tz = positionNode.xy.mul( scaleNode );
  29096. // Base color
  29097. const textureX = textureXNode.value;
  29098. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  29099. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  29100. const cx = texture( textureX, tx ).mul( bf.x );
  29101. const cy = texture( textureY, ty ).mul( bf.y );
  29102. const cz = texture( textureZ, tz ).mul( bf.z );
  29103. return add( cx, cy, cz );
  29104. }
  29105. }
  29106. const triplanarTextures = nodeProxy( TriplanarTexturesNode );
  29107. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  29108. addNodeElement( 'triplanarTexture', triplanarTexture );
  29109. addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode );
  29110. const _reflectorPlane = new Plane();
  29111. const _normal = new Vector3();
  29112. const _reflectorWorldPosition = new Vector3();
  29113. const _cameraWorldPosition = new Vector3();
  29114. const _rotationMatrix = new Matrix4();
  29115. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  29116. const clipPlane = new Vector4();
  29117. const _view = new Vector3();
  29118. const _target = new Vector3();
  29119. const _q = new Vector4();
  29120. const _size$4 = new Vector2();
  29121. const _defaultRT = new RenderTarget();
  29122. const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y );
  29123. let _inReflector = false;
  29124. class ReflectorNode extends TextureNode {
  29125. constructor( parameters = {} ) {
  29126. super( _defaultRT.texture, _defaultUV );
  29127. const {
  29128. target = new Object3D(),
  29129. resolution = 1,
  29130. generateMipmaps = false,
  29131. bounces = true
  29132. } = parameters;
  29133. //
  29134. this.target = target;
  29135. this.resolution = resolution;
  29136. this.generateMipmaps = generateMipmaps;
  29137. this.bounces = bounces;
  29138. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  29139. this.virtualCameras = new WeakMap();
  29140. this.renderTargets = new WeakMap();
  29141. }
  29142. _updateResolution( renderTarget, renderer ) {
  29143. const resolution = this.resolution;
  29144. renderer.getDrawingBufferSize( _size$4 );
  29145. renderTarget.setSize( Math.round( _size$4.width * resolution ), Math.round( _size$4.height * resolution ) );
  29146. }
  29147. setup( builder ) {
  29148. this._updateResolution( _defaultRT, builder.renderer );
  29149. return super.setup( builder );
  29150. }
  29151. getTextureNode() {
  29152. return this.textureNode;
  29153. }
  29154. getVirtualCamera( camera ) {
  29155. let virtualCamera = this.virtualCameras.get( camera );
  29156. if ( virtualCamera === undefined ) {
  29157. virtualCamera = camera.clone();
  29158. this.virtualCameras.set( camera, virtualCamera );
  29159. }
  29160. return virtualCamera;
  29161. }
  29162. getRenderTarget( camera ) {
  29163. let renderTarget = this.renderTargets.get( camera );
  29164. if ( renderTarget === undefined ) {
  29165. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  29166. if ( this.generateMipmaps === true ) {
  29167. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  29168. renderTarget.texture.generateMipmaps = true;
  29169. }
  29170. this.renderTargets.set( camera, renderTarget );
  29171. }
  29172. return renderTarget;
  29173. }
  29174. updateBefore( frame ) {
  29175. if ( this.bounces === false && _inReflector ) return false;
  29176. _inReflector = true;
  29177. const { scene, camera, renderer, material } = frame;
  29178. const { target } = this;
  29179. const virtualCamera = this.getVirtualCamera( camera );
  29180. const renderTarget = this.getRenderTarget( virtualCamera );
  29181. renderer.getDrawingBufferSize( _size$4 );
  29182. this._updateResolution( renderTarget, renderer );
  29183. //
  29184. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  29185. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  29186. _rotationMatrix.extractRotation( target.matrixWorld );
  29187. _normal.set( 0, 0, 1 );
  29188. _normal.applyMatrix4( _rotationMatrix );
  29189. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  29190. // Avoid rendering when reflector is facing away
  29191. if ( _view.dot( _normal ) > 0 ) return;
  29192. _view.reflect( _normal ).negate();
  29193. _view.add( _reflectorWorldPosition );
  29194. _rotationMatrix.extractRotation( camera.matrixWorld );
  29195. _lookAtPosition.set( 0, 0, - 1 );
  29196. _lookAtPosition.applyMatrix4( _rotationMatrix );
  29197. _lookAtPosition.add( _cameraWorldPosition );
  29198. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  29199. _target.reflect( _normal ).negate();
  29200. _target.add( _reflectorWorldPosition );
  29201. //
  29202. virtualCamera.coordinateSystem = camera.coordinateSystem;
  29203. virtualCamera.position.copy( _view );
  29204. virtualCamera.up.set( 0, 1, 0 );
  29205. virtualCamera.up.applyMatrix4( _rotationMatrix );
  29206. virtualCamera.up.reflect( _normal );
  29207. virtualCamera.lookAt( _target );
  29208. virtualCamera.near = camera.near;
  29209. virtualCamera.far = camera.far;
  29210. virtualCamera.updateMatrixWorld();
  29211. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  29212. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  29213. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  29214. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  29215. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  29216. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  29217. const projectionMatrix = virtualCamera.projectionMatrix;
  29218. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  29219. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  29220. _q.z = - 1.0;
  29221. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  29222. // Calculate the scaled plane vector
  29223. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  29224. const clipBias = 0;
  29225. // Replacing the third row of the projection matrix
  29226. projectionMatrix.elements[ 2 ] = clipPlane.x;
  29227. projectionMatrix.elements[ 6 ] = clipPlane.y;
  29228. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  29229. projectionMatrix.elements[ 14 ] = clipPlane.w;
  29230. //
  29231. this.value = renderTarget.texture;
  29232. material.visible = false;
  29233. const currentRenderTarget = renderer.getRenderTarget();
  29234. renderer.setRenderTarget( renderTarget );
  29235. renderer.render( scene, virtualCamera );
  29236. renderer.setRenderTarget( currentRenderTarget );
  29237. material.visible = true;
  29238. _inReflector = false;
  29239. }
  29240. }
  29241. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  29242. // Helper for passes that need to fill the viewport with a single quad.
  29243. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  29244. // https://github.com/mrdoob/three.js/pull/21358
  29245. class QuadGeometry extends BufferGeometry {
  29246. constructor( flipY = false ) {
  29247. super();
  29248. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  29249. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  29250. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  29251. }
  29252. }
  29253. const _geometry = new QuadGeometry();
  29254. class QuadMesh extends Mesh {
  29255. constructor( material = null ) {
  29256. super( _geometry, material );
  29257. this.camera = _camera;
  29258. }
  29259. renderAsync( renderer ) {
  29260. return renderer.renderAsync( this, _camera );
  29261. }
  29262. render( renderer ) {
  29263. renderer.render( this, _camera );
  29264. }
  29265. }
  29266. const _size$3 = new Vector2();
  29267. class RTTNode extends TextureNode {
  29268. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  29269. const renderTarget = new RenderTarget( width, height, options );
  29270. super( renderTarget.texture, uv() );
  29271. this.node = node;
  29272. this.width = width;
  29273. this.height = height;
  29274. this.renderTarget = renderTarget;
  29275. this.textureNeedsUpdate = true;
  29276. this.autoUpdate = true;
  29277. this.updateMap = new WeakMap();
  29278. this._rttNode = null;
  29279. this._quadMesh = new QuadMesh( new NodeMaterial() );
  29280. this.updateBeforeType = NodeUpdateType.RENDER;
  29281. }
  29282. get autoSize() {
  29283. return this.width === null;
  29284. }
  29285. setup( builder ) {
  29286. this._rttNode = this.node.context( builder.getSharedContext() );
  29287. this._quadMesh.material.needsUpdate = true;
  29288. return super.setup( builder );
  29289. }
  29290. setSize( width, height ) {
  29291. this.width = width;
  29292. this.height = height;
  29293. const effectiveWidth = width * this.pixelRatio;
  29294. const effectiveHeight = height * this.pixelRatio;
  29295. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  29296. this.textureNeedsUpdate = true;
  29297. }
  29298. setPixelRatio( pixelRatio ) {
  29299. this.pixelRatio = pixelRatio;
  29300. this.setSize( this.width, this.height );
  29301. }
  29302. updateBefore( { renderer } ) {
  29303. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  29304. this.textureNeedsUpdate = false;
  29305. //
  29306. if ( this.autoSize === true ) {
  29307. this.pixelRatio = renderer.getPixelRatio();
  29308. const size = renderer.getSize( _size$3 );
  29309. this.setSize( size.width, size.height );
  29310. }
  29311. //
  29312. this._quadMesh.material.fragmentNode = this._rttNode;
  29313. //
  29314. const currentRenderTarget = renderer.getRenderTarget();
  29315. renderer.setRenderTarget( this.renderTarget );
  29316. this._quadMesh.render( renderer );
  29317. renderer.setRenderTarget( currentRenderTarget );
  29318. }
  29319. clone() {
  29320. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  29321. newNode.sampler = this.sampler;
  29322. newNode.referenceNode = this;
  29323. return newNode;
  29324. }
  29325. }
  29326. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  29327. addNodeElement( 'toTexture', ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ) );
  29328. addNodeClass( 'RTTNode', RTTNode );
  29329. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  29330. const bitangentGeometry = /*#__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  29331. const bitangentLocal = /*#__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  29332. const bitangentView = /*#__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  29333. const bitangentWorld = /*#__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  29334. const transformedBitangentView = /*#__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  29335. const transformedBitangentWorld = /*#__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  29336. const TBNViewMatrix = mat3( tangentView, bitangentView, normalView );
  29337. const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  29338. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  29339. const transformedBentNormalView = ( () => {
  29340. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  29341. let bentNormal = anisotropyB.cross( positionViewDirection );
  29342. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  29343. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  29344. return bentNormal;
  29345. } )();
  29346. class VertexColorNode extends AttributeNode {
  29347. constructor( index = 0 ) {
  29348. super( null, 'vec4' );
  29349. this.isVertexColorNode = true;
  29350. this.index = index;
  29351. }
  29352. getAttributeName( /*builder*/ ) {
  29353. const index = this.index;
  29354. return 'color' + ( index > 0 ? index : '' );
  29355. }
  29356. generate( builder ) {
  29357. const attributeName = this.getAttributeName( builder );
  29358. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  29359. let result;
  29360. if ( geometryAttribute === true ) {
  29361. result = super.generate( builder );
  29362. } else {
  29363. // Vertex color fallback should be white
  29364. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  29365. }
  29366. return result;
  29367. }
  29368. serialize( data ) {
  29369. super.serialize( data );
  29370. data.index = this.index;
  29371. }
  29372. deserialize( data ) {
  29373. super.deserialize( data );
  29374. this.index = data.index;
  29375. }
  29376. }
  29377. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  29378. addNodeClass( 'VertexColorNode', VertexColorNode );
  29379. class RendererReferenceNode extends ReferenceNode {
  29380. constructor( property, inputType, renderer = null ) {
  29381. super( property, inputType, renderer );
  29382. this.renderer = renderer;
  29383. }
  29384. updateReference( state ) {
  29385. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  29386. return this.reference;
  29387. }
  29388. }
  29389. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  29390. addNodeClass( 'RendererReferenceNode', RendererReferenceNode );
  29391. // Mipped Bicubic Texture Filtering by N8
  29392. // https://www.shadertoy.com/view/Dl2SDW
  29393. const bC = 1.0 / 6.0;
  29394. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  29395. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  29396. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  29397. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  29398. const g0 = ( a ) => w0( a ).add( w1( a ) );
  29399. const g1 = ( a ) => w2( a ).add( w3( a ) );
  29400. // h0 and h1 are the two offset functions
  29401. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  29402. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  29403. const bicubic = ( textureNode, texelSize, lod ) => {
  29404. const uv = textureNode.uvNode;
  29405. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  29406. const iuv = floor( uvScaled );
  29407. const fuv = fract( uvScaled );
  29408. const g0x = g0( fuv.x );
  29409. const g1x = g1( fuv.x );
  29410. const h0x = h0( fuv.x );
  29411. const h1x = h1( fuv.x );
  29412. const h0y = h0( fuv.y );
  29413. const h1y = h1( fuv.y );
  29414. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29415. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29416. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29417. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29418. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  29419. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  29420. return a.add( b );
  29421. };
  29422. const textureBicubicMethod = ( textureNode, lodNode ) => {
  29423. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  29424. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  29425. const fLodSizeInv = div( 1.0, fLodSize );
  29426. const cLodSizeInv = div( 1.0, cLodSize );
  29427. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  29428. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  29429. return fract( lodNode ).mix( fSample, cSample );
  29430. };
  29431. class TextureBicubicNode extends TempNode {
  29432. constructor( textureNode, blurNode = float( 3 ) ) {
  29433. super( 'vec4' );
  29434. this.textureNode = textureNode;
  29435. this.blurNode = blurNode;
  29436. }
  29437. setup() {
  29438. return textureBicubicMethod( this.textureNode, this.blurNode );
  29439. }
  29440. }
  29441. const textureBicubic = nodeProxy( TextureBicubicNode );
  29442. addNodeElement( 'bicubic', textureBicubic );
  29443. addNodeClass( 'TextureBicubicNode', TextureBicubicNode );
  29444. class PointUVNode extends Node {
  29445. constructor() {
  29446. super( 'vec2' );
  29447. this.isPointUVNode = true;
  29448. }
  29449. generate( /*builder*/ ) {
  29450. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  29451. }
  29452. }
  29453. const pointUV = nodeImmutable( PointUVNode );
  29454. addNodeClass( 'PointUVNode', PointUVNode );
  29455. class SceneNode extends Node {
  29456. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  29457. super();
  29458. this.scope = scope;
  29459. this.scene = scene;
  29460. }
  29461. setup( builder ) {
  29462. const scope = this.scope;
  29463. const scene = this.scene !== null ? this.scene : builder.scene;
  29464. let output;
  29465. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  29466. output = reference( 'backgroundBlurriness', 'float', scene );
  29467. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  29468. output = reference( 'backgroundIntensity', 'float', scene );
  29469. } else {
  29470. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  29471. }
  29472. return output;
  29473. }
  29474. }
  29475. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  29476. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  29477. const backgroundBlurriness = nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  29478. const backgroundIntensity = nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  29479. addNodeClass( 'SceneNode', SceneNode );
  29480. const GPUPrimitiveTopology = {
  29481. PointList: 'point-list',
  29482. LineList: 'line-list',
  29483. LineStrip: 'line-strip',
  29484. TriangleList: 'triangle-list',
  29485. TriangleStrip: 'triangle-strip',
  29486. };
  29487. const GPUCompareFunction = {
  29488. Never: 'never',
  29489. Less: 'less',
  29490. Equal: 'equal',
  29491. LessEqual: 'less-equal',
  29492. Greater: 'greater',
  29493. NotEqual: 'not-equal',
  29494. GreaterEqual: 'greater-equal',
  29495. Always: 'always'
  29496. };
  29497. const GPUStoreOp = {
  29498. Store: 'store',
  29499. Discard: 'discard'
  29500. };
  29501. const GPULoadOp = {
  29502. Load: 'load',
  29503. Clear: 'clear'
  29504. };
  29505. const GPUFrontFace = {
  29506. CCW: 'ccw',
  29507. CW: 'cw'
  29508. };
  29509. const GPUCullMode = {
  29510. None: 'none',
  29511. Front: 'front',
  29512. Back: 'back'
  29513. };
  29514. const GPUIndexFormat = {
  29515. Uint16: 'uint16',
  29516. Uint32: 'uint32'
  29517. };
  29518. const GPUTextureFormat = {
  29519. // 8-bit formats
  29520. R8Unorm: 'r8unorm',
  29521. R8Snorm: 'r8snorm',
  29522. R8Uint: 'r8uint',
  29523. R8Sint: 'r8sint',
  29524. // 16-bit formats
  29525. R16Uint: 'r16uint',
  29526. R16Sint: 'r16sint',
  29527. R16Float: 'r16float',
  29528. RG8Unorm: 'rg8unorm',
  29529. RG8Snorm: 'rg8snorm',
  29530. RG8Uint: 'rg8uint',
  29531. RG8Sint: 'rg8sint',
  29532. // 32-bit formats
  29533. R32Uint: 'r32uint',
  29534. R32Sint: 'r32sint',
  29535. R32Float: 'r32float',
  29536. RG16Uint: 'rg16uint',
  29537. RG16Sint: 'rg16sint',
  29538. RG16Float: 'rg16float',
  29539. RGBA8Unorm: 'rgba8unorm',
  29540. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  29541. RGBA8Snorm: 'rgba8snorm',
  29542. RGBA8Uint: 'rgba8uint',
  29543. RGBA8Sint: 'rgba8sint',
  29544. BGRA8Unorm: 'bgra8unorm',
  29545. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  29546. // Packed 32-bit formats
  29547. RGB9E5UFloat: 'rgb9e5ufloat',
  29548. RGB10A2Unorm: 'rgb10a2unorm',
  29549. RG11B10uFloat: 'rgb10a2unorm',
  29550. // 64-bit formats
  29551. RG32Uint: 'rg32uint',
  29552. RG32Sint: 'rg32sint',
  29553. RG32Float: 'rg32float',
  29554. RGBA16Uint: 'rgba16uint',
  29555. RGBA16Sint: 'rgba16sint',
  29556. RGBA16Float: 'rgba16float',
  29557. // 128-bit formats
  29558. RGBA32Uint: 'rgba32uint',
  29559. RGBA32Sint: 'rgba32sint',
  29560. RGBA32Float: 'rgba32float',
  29561. // Depth and stencil formats
  29562. Stencil8: 'stencil8',
  29563. Depth16Unorm: 'depth16unorm',
  29564. Depth24Plus: 'depth24plus',
  29565. Depth24PlusStencil8: 'depth24plus-stencil8',
  29566. Depth32Float: 'depth32float',
  29567. // 'depth32float-stencil8' extension
  29568. Depth32FloatStencil8: 'depth32float-stencil8',
  29569. // BC compressed formats usable if 'texture-compression-bc' is both
  29570. // supported by the device/user agent and enabled in requestDevice.
  29571. BC1RGBAUnorm: 'bc1-rgba-unorm',
  29572. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  29573. BC2RGBAUnorm: 'bc2-rgba-unorm',
  29574. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  29575. BC3RGBAUnorm: 'bc3-rgba-unorm',
  29576. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  29577. BC4RUnorm: 'bc4-r-unorm',
  29578. BC4RSnorm: 'bc4-r-snorm',
  29579. BC5RGUnorm: 'bc5-rg-unorm',
  29580. BC5RGSnorm: 'bc5-rg-snorm',
  29581. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  29582. BC6HRGBFloat: 'bc6h-rgb-float',
  29583. BC7RGBAUnorm: 'bc7-rgba-unorm',
  29584. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  29585. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  29586. // supported by the device/user agent and enabled in requestDevice.
  29587. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  29588. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  29589. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  29590. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  29591. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  29592. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  29593. EACR11Unorm: 'eac-r11unorm',
  29594. EACR11Snorm: 'eac-r11snorm',
  29595. EACRG11Unorm: 'eac-rg11unorm',
  29596. EACRG11Snorm: 'eac-rg11snorm',
  29597. // ASTC compressed formats usable if 'texture-compression-astc' is both
  29598. // supported by the device/user agent and enabled in requestDevice.
  29599. ASTC4x4Unorm: 'astc-4x4-unorm',
  29600. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  29601. ASTC5x4Unorm: 'astc-5x4-unorm',
  29602. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  29603. ASTC5x5Unorm: 'astc-5x5-unorm',
  29604. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  29605. ASTC6x5Unorm: 'astc-6x5-unorm',
  29606. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  29607. ASTC6x6Unorm: 'astc-6x6-unorm',
  29608. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  29609. ASTC8x5Unorm: 'astc-8x5-unorm',
  29610. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  29611. ASTC8x6Unorm: 'astc-8x6-unorm',
  29612. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  29613. ASTC8x8Unorm: 'astc-8x8-unorm',
  29614. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  29615. ASTC10x5Unorm: 'astc-10x5-unorm',
  29616. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  29617. ASTC10x6Unorm: 'astc-10x6-unorm',
  29618. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  29619. ASTC10x8Unorm: 'astc-10x8-unorm',
  29620. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  29621. ASTC10x10Unorm: 'astc-10x10-unorm',
  29622. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  29623. ASTC12x10Unorm: 'astc-12x10-unorm',
  29624. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  29625. ASTC12x12Unorm: 'astc-12x12-unorm',
  29626. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  29627. };
  29628. const GPUAddressMode = {
  29629. ClampToEdge: 'clamp-to-edge',
  29630. Repeat: 'repeat',
  29631. MirrorRepeat: 'mirror-repeat'
  29632. };
  29633. const GPUFilterMode = {
  29634. Linear: 'linear',
  29635. Nearest: 'nearest'
  29636. };
  29637. const GPUBlendFactor = {
  29638. Zero: 'zero',
  29639. One: 'one',
  29640. Src: 'src',
  29641. OneMinusSrc: 'one-minus-src',
  29642. SrcAlpha: 'src-alpha',
  29643. OneMinusSrcAlpha: 'one-minus-src-alpha',
  29644. Dst: 'dst',
  29645. OneMinusDstColor: 'one-minus-dst',
  29646. DstAlpha: 'dst-alpha',
  29647. OneMinusDstAlpha: 'one-minus-dst-alpha',
  29648. SrcAlphaSaturated: 'src-alpha-saturated',
  29649. Constant: 'constant',
  29650. OneMinusConstant: 'one-minus-constant'
  29651. };
  29652. const GPUBlendOperation = {
  29653. Add: 'add',
  29654. Subtract: 'subtract',
  29655. ReverseSubtract: 'reverse-subtract',
  29656. Min: 'min',
  29657. Max: 'max'
  29658. };
  29659. const GPUColorWriteFlags = {
  29660. None: 0,
  29661. Red: 0x1,
  29662. Green: 0x2,
  29663. Blue: 0x4,
  29664. Alpha: 0x8,
  29665. All: 0xF
  29666. };
  29667. const GPUStencilOperation = {
  29668. Keep: 'keep',
  29669. Zero: 'zero',
  29670. Replace: 'replace',
  29671. Invert: 'invert',
  29672. IncrementClamp: 'increment-clamp',
  29673. DecrementClamp: 'decrement-clamp',
  29674. IncrementWrap: 'increment-wrap',
  29675. DecrementWrap: 'decrement-wrap'
  29676. };
  29677. const GPUBufferBindingType = {
  29678. Uniform: 'uniform',
  29679. Storage: 'storage',
  29680. ReadOnlyStorage: 'read-only-storage'
  29681. };
  29682. const GPUStorageTextureAccess = {
  29683. WriteOnly: 'write-only',
  29684. ReadOnly: 'read-only',
  29685. ReadWrite: 'read-write',
  29686. };
  29687. const GPUTextureSampleType = {
  29688. Float: 'float',
  29689. UnfilterableFloat: 'unfilterable-float',
  29690. Depth: 'depth',
  29691. SInt: 'sint',
  29692. UInt: 'uint'
  29693. };
  29694. const GPUTextureDimension = {
  29695. OneD: '1d',
  29696. TwoD: '2d',
  29697. ThreeD: '3d'
  29698. };
  29699. const GPUTextureViewDimension = {
  29700. OneD: '1d',
  29701. TwoD: '2d',
  29702. TwoDArray: '2d-array',
  29703. Cube: 'cube',
  29704. CubeArray: 'cube-array',
  29705. ThreeD: '3d'
  29706. };
  29707. const GPUTextureAspect = {
  29708. All: 'all',
  29709. StencilOnly: 'stencil-only',
  29710. DepthOnly: 'depth-only'
  29711. };
  29712. const GPUInputStepMode = {
  29713. Vertex: 'vertex',
  29714. Instance: 'instance'
  29715. };
  29716. const GPUFeatureName = {
  29717. DepthClipControl: 'depth-clip-control',
  29718. Depth32FloatStencil8: 'depth32float-stencil8',
  29719. TextureCompressionBC: 'texture-compression-bc',
  29720. TextureCompressionETC2: 'texture-compression-etc2',
  29721. TextureCompressionASTC: 'texture-compression-astc',
  29722. TimestampQuery: 'timestamp-query',
  29723. IndirectFirstInstance: 'indirect-first-instance',
  29724. ShaderF16: 'shader-f16',
  29725. RG11B10UFloat: 'rg11b10ufloat-renderable',
  29726. BGRA8UNormStorage: 'bgra8unorm-storage',
  29727. Float32Filterable: 'float32-filterable'
  29728. };
  29729. class StorageBufferNode extends BufferNode {
  29730. constructor( value, bufferType, bufferCount = 0 ) {
  29731. super( value, bufferType, bufferCount );
  29732. this.isStorageBufferNode = true;
  29733. this.access = GPUBufferBindingType.Storage;
  29734. this.bufferObject = false;
  29735. this.bufferCount = bufferCount;
  29736. this._attribute = null;
  29737. this._varying = null;
  29738. this.global = true;
  29739. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  29740. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  29741. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  29742. else value.isStorageBufferAttribute = true;
  29743. }
  29744. }
  29745. getHash( builder ) {
  29746. if ( this.bufferCount === 0 ) {
  29747. let bufferData = builder.globalCache.getData( this.value );
  29748. if ( bufferData === undefined ) {
  29749. bufferData = {
  29750. node: this
  29751. };
  29752. builder.globalCache.setData( this.value, bufferData );
  29753. }
  29754. return bufferData.node.uuid;
  29755. }
  29756. return this.uuid;
  29757. }
  29758. getInputType( /*builder*/ ) {
  29759. return 'storageBuffer';
  29760. }
  29761. element( indexNode ) {
  29762. return storageElement( this, indexNode );
  29763. }
  29764. setBufferObject( value ) {
  29765. this.bufferObject = value;
  29766. return this;
  29767. }
  29768. setAccess( value ) {
  29769. this.access = value;
  29770. return this;
  29771. }
  29772. toReadOnly() {
  29773. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  29774. }
  29775. generate( builder ) {
  29776. if ( builder.isAvailable( 'storageBuffer' ) ) {
  29777. return super.generate( builder );
  29778. }
  29779. const nodeType = this.getNodeType( builder );
  29780. if ( this._attribute === null ) {
  29781. this._attribute = bufferAttribute( this.value );
  29782. this._varying = varying( this._attribute );
  29783. }
  29784. const output = this._varying.build( builder, nodeType );
  29785. builder.registerTransform( output, this._attribute );
  29786. return output;
  29787. }
  29788. }
  29789. // Read-Write Storage
  29790. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  29791. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  29792. addNodeClass( 'StorageBufferNode', StorageBufferNode );
  29793. class StorageTextureNode extends TextureNode {
  29794. constructor( value, uvNode, storeNode = null ) {
  29795. super( value, uvNode );
  29796. this.storeNode = storeNode;
  29797. this.isStorageTextureNode = true;
  29798. this.access = GPUStorageTextureAccess.WriteOnly;
  29799. }
  29800. getInputType( /*builder*/ ) {
  29801. return 'storageTexture';
  29802. }
  29803. setup( builder ) {
  29804. super.setup( builder );
  29805. const properties = builder.getNodeProperties( this );
  29806. properties.storeNode = this.storeNode;
  29807. }
  29808. setAccess( value ) {
  29809. this.access = value;
  29810. return this;
  29811. }
  29812. generate( builder, output ) {
  29813. let snippet;
  29814. if ( this.storeNode !== null ) {
  29815. snippet = this.generateStore( builder );
  29816. } else {
  29817. snippet = super.generate( builder, output );
  29818. }
  29819. return snippet;
  29820. }
  29821. toReadOnly() {
  29822. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  29823. }
  29824. toWriteOnly() {
  29825. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  29826. }
  29827. generateStore( builder ) {
  29828. const properties = builder.getNodeProperties( this );
  29829. const { uvNode, storeNode } = properties;
  29830. const textureProperty = super.generate( builder, 'property' );
  29831. const uvSnippet = uvNode.build( builder, 'uvec2' );
  29832. const storeSnippet = storeNode.build( builder, 'vec4' );
  29833. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  29834. builder.addLineFlowCode( snippet );
  29835. }
  29836. }
  29837. const storageTexture = nodeProxy( StorageTextureNode );
  29838. const textureStore = ( value, uvNode, storeNode ) => {
  29839. const node = storageTexture( value, uvNode, storeNode );
  29840. if ( storeNode !== null ) node.append();
  29841. return node;
  29842. };
  29843. addNodeClass( 'StorageTextureNode', StorageTextureNode );
  29844. const normal = tslFn( ( { texture, uv } ) => {
  29845. const epsilon = 0.0001;
  29846. const ret = vec3().temp();
  29847. If( uv.x.lessThan( epsilon ), () => {
  29848. ret.assign( vec3( 1, 0, 0 ) );
  29849. } ).elseif( uv.y.lessThan( epsilon ), () => {
  29850. ret.assign( vec3( 0, 1, 0 ) );
  29851. } ).elseif( uv.z.lessThan( epsilon ), () => {
  29852. ret.assign( vec3( 0, 0, 1 ) );
  29853. } ).elseif( uv.x.greaterThan( 1 - epsilon ), () => {
  29854. ret.assign( vec3( - 1, 0, 0 ) );
  29855. } ).elseif( uv.y.greaterThan( 1 - epsilon ), () => {
  29856. ret.assign( vec3( 0, - 1, 0 ) );
  29857. } ).elseif( uv.z.greaterThan( 1 - epsilon ), () => {
  29858. ret.assign( vec3( 0, 0, - 1 ) );
  29859. } ).else( () => {
  29860. const step = 0.01;
  29861. 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 );
  29862. 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 );
  29863. 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 );
  29864. ret.assign( vec3( x, y, z ) );
  29865. } );
  29866. return ret.normalize();
  29867. } );
  29868. class Texture3DNode extends TextureNode {
  29869. constructor( value, uvNode = null, levelNode = null ) {
  29870. super( value, uvNode, levelNode );
  29871. this.isTexture3DNode = true;
  29872. }
  29873. getInputType( /*builder*/ ) {
  29874. return 'texture3D';
  29875. }
  29876. getDefaultUV() {
  29877. return vec3( 0.5, 0.5, 0.5 );
  29878. }
  29879. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  29880. setupUV( builder, uvNode ) {
  29881. return uvNode;
  29882. }
  29883. generateUV( builder, uvNode ) {
  29884. return uvNode.build( builder, 'vec3' );
  29885. }
  29886. normal( uvNode ) {
  29887. return normal( { texture: this, uv: uvNode } );
  29888. }
  29889. }
  29890. const texture3D = nodeProxy( Texture3DNode );
  29891. addNodeClass( 'Texture3DNode', Texture3DNode );
  29892. class UserDataNode extends ReferenceNode {
  29893. constructor( property, inputType, userData = null ) {
  29894. super( property, inputType, userData );
  29895. this.userData = userData;
  29896. }
  29897. update( frame ) {
  29898. this.reference = this.userData !== null ? this.userData : frame.object.userData;
  29899. super.update( frame );
  29900. }
  29901. }
  29902. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  29903. addNodeClass( 'UserDataNode', UserDataNode );
  29904. const BurnNode = tslFn( ( { base, blend } ) => {
  29905. const fn = ( c ) => blend[ c ].lessThan( EPSILON ).cond( blend[ c ], base[ c ].oneMinus().div( blend[ c ] ).oneMinus().max( 0 ) );
  29906. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  29907. } ).setLayout( {
  29908. name: 'burnColor',
  29909. type: 'vec3',
  29910. inputs: [
  29911. { name: 'base', type: 'vec3' },
  29912. { name: 'blend', type: 'vec3' }
  29913. ]
  29914. } );
  29915. const DodgeNode = tslFn( ( { base, blend } ) => {
  29916. const fn = ( c ) => blend[ c ].equal( 1.0 ).cond( blend[ c ], base[ c ].div( blend[ c ].oneMinus() ).max( 0 ) );
  29917. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  29918. } ).setLayout( {
  29919. name: 'dodgeColor',
  29920. type: 'vec3',
  29921. inputs: [
  29922. { name: 'base', type: 'vec3' },
  29923. { name: 'blend', type: 'vec3' }
  29924. ]
  29925. } );
  29926. const ScreenNode = tslFn( ( { base, blend } ) => {
  29927. const fn = ( c ) => base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus();
  29928. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  29929. } ).setLayout( {
  29930. name: 'screenColor',
  29931. type: 'vec3',
  29932. inputs: [
  29933. { name: 'base', type: 'vec3' },
  29934. { name: 'blend', type: 'vec3' }
  29935. ]
  29936. } );
  29937. const OverlayNode = tslFn( ( { base, blend } ) => {
  29938. const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() );
  29939. //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) );
  29940. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  29941. } ).setLayout( {
  29942. name: 'overlayColor',
  29943. type: 'vec3',
  29944. inputs: [
  29945. { name: 'base', type: 'vec3' },
  29946. { name: 'blend', type: 'vec3' }
  29947. ]
  29948. } );
  29949. class BlendModeNode extends TempNode {
  29950. constructor( blendMode, baseNode, blendNode ) {
  29951. super();
  29952. this.blendMode = blendMode;
  29953. this.baseNode = baseNode;
  29954. this.blendNode = blendNode;
  29955. }
  29956. setup() {
  29957. const { blendMode, baseNode, blendNode } = this;
  29958. const params = { base: baseNode, blend: blendNode };
  29959. let outputNode = null;
  29960. if ( blendMode === BlendModeNode.BURN ) {
  29961. outputNode = BurnNode( params );
  29962. } else if ( blendMode === BlendModeNode.DODGE ) {
  29963. outputNode = DodgeNode( params );
  29964. } else if ( blendMode === BlendModeNode.SCREEN ) {
  29965. outputNode = ScreenNode( params );
  29966. } else if ( blendMode === BlendModeNode.OVERLAY ) {
  29967. outputNode = OverlayNode( params );
  29968. }
  29969. return outputNode;
  29970. }
  29971. }
  29972. BlendModeNode.BURN = 'burn';
  29973. BlendModeNode.DODGE = 'dodge';
  29974. BlendModeNode.SCREEN = 'screen';
  29975. BlendModeNode.OVERLAY = 'overlay';
  29976. const burn = nodeProxy( BlendModeNode, BlendModeNode.BURN );
  29977. const dodge = nodeProxy( BlendModeNode, BlendModeNode.DODGE );
  29978. const overlay = nodeProxy( BlendModeNode, BlendModeNode.OVERLAY );
  29979. const screen = nodeProxy( BlendModeNode, BlendModeNode.SCREEN );
  29980. addNodeElement( 'burn', burn );
  29981. addNodeElement( 'dodge', dodge );
  29982. addNodeElement( 'overlay', overlay );
  29983. addNodeElement( 'screen', screen );
  29984. addNodeClass( 'BlendModeNode', BlendModeNode );
  29985. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  29986. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  29987. const dHdxy_fwd = tslFn( ( { textureNode, bumpScale } ) => {
  29988. // It's used to preserve the same TextureNode instance
  29989. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  29990. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  29991. return vec2(
  29992. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  29993. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  29994. ).mul( bumpScale );
  29995. } );
  29996. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  29997. const perturbNormalArb = tslFn( ( inputs ) => {
  29998. const { surf_pos, surf_norm, dHdxy } = inputs;
  29999. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  30000. const vSigmaX = surf_pos.dFdx().normalize();
  30001. const vSigmaY = surf_pos.dFdy().normalize();
  30002. const vN = surf_norm; // normalized
  30003. const R1 = vSigmaY.cross( vN );
  30004. const R2 = vN.cross( vSigmaX );
  30005. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  30006. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  30007. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  30008. } );
  30009. class BumpMapNode extends TempNode {
  30010. constructor( textureNode, scaleNode = null ) {
  30011. super( 'vec3' );
  30012. this.textureNode = textureNode;
  30013. this.scaleNode = scaleNode;
  30014. }
  30015. setup() {
  30016. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  30017. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  30018. return perturbNormalArb( {
  30019. surf_pos: positionView,
  30020. surf_norm: normalView,
  30021. dHdxy
  30022. } );
  30023. }
  30024. }
  30025. const bumpMap = nodeProxy( BumpMapNode );
  30026. addNodeElement( 'bumpMap', bumpMap );
  30027. addNodeClass( 'BumpMapNode', BumpMapNode );
  30028. const saturationNode = tslFn( ( { color, adjustment } ) => {
  30029. return adjustment.mix( luminance( color.rgb ), color.rgb );
  30030. } );
  30031. const vibranceNode = tslFn( ( { color, adjustment } ) => {
  30032. const average = add( color.r, color.g, color.b ).div( 3.0 );
  30033. const mx = color.r.max( color.g.max( color.b ) );
  30034. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  30035. return mix( color.rgb, mx, amt );
  30036. } );
  30037. const hueNode = tslFn( ( { color, adjustment } ) => {
  30038. const k = vec3( 0.57735, 0.57735, 0.57735 );
  30039. const cosAngle = adjustment.cos();
  30040. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  30041. } );
  30042. class ColorAdjustmentNode extends TempNode {
  30043. constructor( method, colorNode, adjustmentNode = float( 1 ) ) {
  30044. super( 'vec3' );
  30045. this.method = method;
  30046. this.colorNode = colorNode;
  30047. this.adjustmentNode = adjustmentNode;
  30048. }
  30049. setup() {
  30050. const { method, colorNode, adjustmentNode } = this;
  30051. const callParams = { color: colorNode, adjustment: adjustmentNode };
  30052. let outputNode = null;
  30053. if ( method === ColorAdjustmentNode.SATURATION ) {
  30054. outputNode = saturationNode( callParams );
  30055. } else if ( method === ColorAdjustmentNode.VIBRANCE ) {
  30056. outputNode = vibranceNode( callParams );
  30057. } else if ( method === ColorAdjustmentNode.HUE ) {
  30058. outputNode = hueNode( callParams );
  30059. } else {
  30060. console.error( `${ this.type }: Method "${ this.method }" not supported!` );
  30061. }
  30062. return outputNode;
  30063. }
  30064. }
  30065. ColorAdjustmentNode.SATURATION = 'saturation';
  30066. ColorAdjustmentNode.VIBRANCE = 'vibrance';
  30067. ColorAdjustmentNode.HUE = 'hue';
  30068. const saturation = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.SATURATION );
  30069. const vibrance = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.VIBRANCE );
  30070. const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE );
  30071. const lumaCoeffs = vec3( 0.2125, 0.7154, 0.0721 );
  30072. const luminance = ( color, luma = lumaCoeffs ) => dot( color, luma );
  30073. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  30074. addNodeElement( 'saturation', saturation );
  30075. addNodeElement( 'vibrance', vibrance );
  30076. addNodeElement( 'hue', hue );
  30077. addNodeElement( 'threshold', threshold );
  30078. addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode );
  30079. // Normal Mapping Without Precomputed Tangents
  30080. // http://www.thetenthplanet.de/archives/1180
  30081. const perturbNormal2Arb = tslFn( ( inputs ) => {
  30082. const { eye_pos, surf_norm, mapN, uv } = inputs;
  30083. const q0 = eye_pos.dFdx();
  30084. const q1 = eye_pos.dFdy();
  30085. const st0 = uv.dFdx();
  30086. const st1 = uv.dFdy();
  30087. const N = surf_norm; // normalized
  30088. const q1perp = q1.cross( N );
  30089. const q0perp = N.cross( q0 );
  30090. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  30091. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  30092. const det = T.dot( T ).max( B.dot( B ) );
  30093. const scale = faceDirection.mul( det.inverseSqrt() );
  30094. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  30095. } );
  30096. class NormalMapNode extends TempNode {
  30097. constructor( node, scaleNode = null ) {
  30098. super( 'vec3' );
  30099. this.node = node;
  30100. this.scaleNode = scaleNode;
  30101. this.normalMapType = TangentSpaceNormalMap;
  30102. }
  30103. setup( builder ) {
  30104. const { normalMapType, scaleNode } = this;
  30105. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  30106. if ( scaleNode !== null ) {
  30107. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  30108. }
  30109. let outputNode = null;
  30110. if ( normalMapType === ObjectSpaceNormalMap ) {
  30111. outputNode = modelNormalMatrix.mul( normalMap ).normalize();
  30112. } else if ( normalMapType === TangentSpaceNormalMap ) {
  30113. const tangent = builder.hasGeometryAttribute( 'tangent' );
  30114. if ( tangent === true ) {
  30115. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  30116. } else {
  30117. outputNode = perturbNormal2Arb( {
  30118. eye_pos: positionView,
  30119. surf_norm: normalView,
  30120. mapN: normalMap,
  30121. uv: uv()
  30122. } );
  30123. }
  30124. }
  30125. return outputNode;
  30126. }
  30127. }
  30128. const normalMap = nodeProxy( NormalMapNode );
  30129. addNodeElement( 'normalMap', normalMap );
  30130. addNodeClass( 'NormalMapNode', NormalMapNode );
  30131. class PosterizeNode extends TempNode {
  30132. constructor( sourceNode, stepsNode ) {
  30133. super();
  30134. this.sourceNode = sourceNode;
  30135. this.stepsNode = stepsNode;
  30136. }
  30137. setup() {
  30138. const { sourceNode, stepsNode } = this;
  30139. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  30140. }
  30141. }
  30142. const posterize = nodeProxy( PosterizeNode );
  30143. addNodeElement( 'posterize', posterize );
  30144. addNodeClass( 'PosterizeNode', PosterizeNode );
  30145. // exposure only
  30146. const LinearToneMappingNode = tslFn( ( { color, exposure } ) => {
  30147. return color.mul( exposure ).clamp();
  30148. } );
  30149. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  30150. const ReinhardToneMappingNode = tslFn( ( { color, exposure } ) => {
  30151. color = color.mul( exposure );
  30152. return color.div( color.add( 1.0 ) ).clamp();
  30153. } );
  30154. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  30155. const OptimizedCineonToneMappingNode = tslFn( ( { color, exposure } ) => {
  30156. // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
  30157. color = color.mul( exposure );
  30158. color = color.sub( 0.004 ).max( 0.0 );
  30159. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  30160. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  30161. return a.div( b ).pow( 2.2 );
  30162. } );
  30163. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30164. const RRTAndODTFit = tslFn( ( { color } ) => {
  30165. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  30166. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  30167. return a.div( b );
  30168. } );
  30169. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30170. const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => {
  30171. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  30172. const ACESInputMat = mat3(
  30173. 0.59719, 0.35458, 0.04823,
  30174. 0.07600, 0.90834, 0.01566,
  30175. 0.02840, 0.13383, 0.83777
  30176. );
  30177. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  30178. const ACESOutputMat = mat3(
  30179. 1.60475, - 0.53108, - 0.07367,
  30180. - 0.10208, 1.10813, - 0.00605,
  30181. - 0.00327, - 0.07276, 1.07602
  30182. );
  30183. color = color.mul( exposure ).div( 0.6 );
  30184. color = ACESInputMat.mul( color );
  30185. // Apply RRT and ODT
  30186. color = RRTAndODTFit( { color } );
  30187. color = ACESOutputMat.mul( color );
  30188. // Clamp to [0, 1]
  30189. return color.clamp();
  30190. } );
  30191. 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 ) );
  30192. 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 ) );
  30193. const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => {
  30194. const x = vec3( x_immutable ).toVar();
  30195. const x2 = vec3( x.mul( x ) ).toVar();
  30196. const x4 = vec3( x2.mul( x2 ) ).toVar();
  30197. 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 ) ) ) );
  30198. } );
  30199. const AGXToneMappingNode = tslFn( ( { color, exposure } ) => {
  30200. const colortone = vec3( color ).toVar();
  30201. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  30202. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  30203. const AgxMinEv = float( - 12.47393 );
  30204. const AgxMaxEv = float( 4.026069 );
  30205. colortone.mulAssign( exposure );
  30206. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  30207. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  30208. colortone.assign( max$1( colortone, 1e-10 ) );
  30209. colortone.assign( log2( colortone ) );
  30210. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  30211. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30212. colortone.assign( agxDefaultContrastApprox( colortone ) );
  30213. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  30214. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  30215. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  30216. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30217. return colortone;
  30218. } );
  30219. // https://modelviewer.dev/examples/tone-mapping
  30220. const NeutralToneMappingNode = tslFn( ( { color, exposure } ) => {
  30221. const StartCompression = float( 0.8 - 0.04 );
  30222. const Desaturation = float( 0.15 );
  30223. color = color.mul( exposure );
  30224. const x = min$1( color.r, min$1( color.g, color.b ) );
  30225. const offset = cond( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  30226. color.subAssign( offset );
  30227. const peak = max$1( color.r, max$1( color.g, color.b ) );
  30228. If( peak.lessThan( StartCompression ), () => {
  30229. return color;
  30230. } );
  30231. const d = sub( 1, StartCompression );
  30232. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  30233. color.mulAssign( newPeak.div( peak ) );
  30234. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  30235. return mix( color, vec3( newPeak ), g );
  30236. } ).setLayout( {
  30237. name: 'NeutralToneMapping',
  30238. type: 'vec3',
  30239. inputs: [
  30240. { name: 'color', type: 'vec3' },
  30241. { name: 'exposure', type: 'float' }
  30242. ]
  30243. } );
  30244. const toneMappingLib = {
  30245. [ LinearToneMapping ]: LinearToneMappingNode,
  30246. [ ReinhardToneMapping ]: ReinhardToneMappingNode,
  30247. [ CineonToneMapping ]: OptimizedCineonToneMappingNode,
  30248. [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode,
  30249. [ AgXToneMapping ]: AGXToneMappingNode,
  30250. [ NeutralToneMapping ]: NeutralToneMappingNode
  30251. };
  30252. class ToneMappingNode extends TempNode {
  30253. constructor( toneMapping = NoToneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  30254. super( 'vec3' );
  30255. this.toneMapping = toneMapping;
  30256. this.exposureNode = exposureNode;
  30257. this.colorNode = colorNode;
  30258. }
  30259. getCacheKey() {
  30260. let cacheKey = super.getCacheKey();
  30261. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  30262. return cacheKey;
  30263. }
  30264. setup( builder ) {
  30265. const colorNode = this.colorNode || builder.context.color;
  30266. const toneMapping = this.toneMapping;
  30267. if ( toneMapping === NoToneMapping ) return colorNode;
  30268. const toneMappingParams = { exposure: this.exposureNode, color: colorNode };
  30269. const toneMappingNode = toneMappingLib[ toneMapping ];
  30270. let outputNode = null;
  30271. if ( toneMappingNode ) {
  30272. outputNode = toneMappingNode( toneMappingParams );
  30273. } else {
  30274. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  30275. outputNode = colorNode;
  30276. }
  30277. return outputNode;
  30278. }
  30279. }
  30280. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  30281. const toneMappingExposure = rendererReference( 'toneMappingExposure', 'float' );
  30282. addNodeElement( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  30283. addNodeClass( 'ToneMappingNode', ToneMappingNode );
  30284. let _sharedFramebuffer = null;
  30285. class ViewportSharedTextureNode extends ViewportTextureNode {
  30286. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  30287. if ( _sharedFramebuffer === null ) {
  30288. _sharedFramebuffer = new FramebufferTexture();
  30289. }
  30290. super( uvNode, levelNode, _sharedFramebuffer );
  30291. }
  30292. updateReference() {
  30293. return this;
  30294. }
  30295. }
  30296. const viewportSharedTexture = nodeProxy( ViewportSharedTextureNode );
  30297. addNodeElement( 'viewportSharedTexture', viewportSharedTexture );
  30298. addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode );
  30299. const _size$2 = new Vector2();
  30300. class PassTextureNode extends TextureNode {
  30301. constructor( passNode, texture ) {
  30302. super( texture );
  30303. this.passNode = passNode;
  30304. this.setUpdateMatrix( false );
  30305. }
  30306. setup( builder ) {
  30307. this.passNode.build( builder );
  30308. return super.setup( builder );
  30309. }
  30310. clone() {
  30311. return new this.constructor( this.passNode, this.value );
  30312. }
  30313. }
  30314. class PassNode extends TempNode {
  30315. constructor( scope, scene, camera, options = {} ) {
  30316. super( 'vec4' );
  30317. this.scope = scope;
  30318. this.scene = scene;
  30319. this.camera = camera;
  30320. this.options = options;
  30321. this._pixelRatio = 1;
  30322. this._width = 1;
  30323. this._height = 1;
  30324. const depthTexture = new DepthTexture();
  30325. depthTexture.isRenderTargetTexture = true;
  30326. //depthTexture.type = FloatType;
  30327. depthTexture.name = 'PostProcessingDepth';
  30328. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options } );
  30329. renderTarget.texture.name = 'PostProcessing';
  30330. renderTarget.depthTexture = depthTexture;
  30331. this.renderTarget = renderTarget;
  30332. this.updateBeforeType = NodeUpdateType.FRAME;
  30333. this._textureNode = nodeObject( new PassTextureNode( this, renderTarget.texture ) );
  30334. this._depthTextureNode = nodeObject( new PassTextureNode( this, depthTexture ) );
  30335. this._linearDepthNode = null;
  30336. this._viewZNode = null;
  30337. this._cameraNear = uniform( 0 );
  30338. this._cameraFar = uniform( 0 );
  30339. this.isPassNode = true;
  30340. }
  30341. isGlobal() {
  30342. return true;
  30343. }
  30344. getTextureNode() {
  30345. return this._textureNode;
  30346. }
  30347. getTextureDepthNode() {
  30348. return this._depthTextureNode;
  30349. }
  30350. getViewZNode() {
  30351. if ( this._viewZNode === null ) {
  30352. const cameraNear = this._cameraNear;
  30353. const cameraFar = this._cameraFar;
  30354. this._viewZNode = perspectiveDepthToViewZ( this._depthTextureNode, cameraNear, cameraFar );
  30355. }
  30356. return this._viewZNode;
  30357. }
  30358. getLinearDepthNode() {
  30359. if ( this._linearDepthNode === null ) {
  30360. const cameraNear = this._cameraNear;
  30361. const cameraFar = this._cameraFar;
  30362. // TODO: just if ( builder.camera.isPerspectiveCamera )
  30363. this._linearDepthNode = viewZToOrthographicDepth( this.getViewZNode(), cameraNear, cameraFar );
  30364. }
  30365. return this._linearDepthNode;
  30366. }
  30367. setup( { renderer } ) {
  30368. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  30369. // Disable MSAA for WebGL backend for now
  30370. if ( renderer.backend.isWebGLBackend === true ) {
  30371. this.renderTarget.samples = 0;
  30372. }
  30373. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  30374. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  30375. }
  30376. updateBefore( frame ) {
  30377. const { renderer } = frame;
  30378. const { scene, camera } = this;
  30379. this._pixelRatio = renderer.getPixelRatio();
  30380. const size = renderer.getSize( _size$2 );
  30381. this.setSize( size.width, size.height );
  30382. const currentRenderTarget = renderer.getRenderTarget();
  30383. this._cameraNear.value = camera.near;
  30384. this._cameraFar.value = camera.far;
  30385. renderer.setRenderTarget( this.renderTarget );
  30386. renderer.render( scene, camera );
  30387. renderer.setRenderTarget( currentRenderTarget );
  30388. }
  30389. setSize( width, height ) {
  30390. this._width = width;
  30391. this._height = height;
  30392. const effectiveWidth = this._width * this._pixelRatio;
  30393. const effectiveHeight = this._height * this._pixelRatio;
  30394. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  30395. }
  30396. setPixelRatio( pixelRatio ) {
  30397. this._pixelRatio = pixelRatio;
  30398. this.setSize( this._width, this._height );
  30399. }
  30400. dispose() {
  30401. this.renderTarget.dispose();
  30402. }
  30403. }
  30404. PassNode.COLOR = 'color';
  30405. PassNode.DEPTH = 'depth';
  30406. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  30407. const texturePass = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  30408. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  30409. addNodeClass( 'PassNode', PassNode );
  30410. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  30411. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  30412. const quadMesh1 = new QuadMesh();
  30413. const quadMesh2 = new QuadMesh();
  30414. class GaussianBlurNode extends TempNode {
  30415. constructor( textureNode, directionNode = null, sigma = 2 ) {
  30416. super( 'vec4' );
  30417. this.textureNode = textureNode;
  30418. this.directionNode = directionNode;
  30419. this.sigma = sigma;
  30420. this._invSize = uniform( new Vector2() );
  30421. this._passDirection = uniform( new Vector2() );
  30422. this._horizontalRT = new RenderTarget();
  30423. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  30424. this._verticalRT = new RenderTarget();
  30425. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  30426. this._textureNode = texturePass( this, this._verticalRT.texture );
  30427. this.updateBeforeType = NodeUpdateType.RENDER;
  30428. this.resolution = new Vector2( 1, 1 );
  30429. }
  30430. setSize( width, height ) {
  30431. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30432. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30433. this._invSize.value.set( 1 / width, 1 / height );
  30434. this._horizontalRT.setSize( width, height );
  30435. this._verticalRT.setSize( width, height );
  30436. }
  30437. updateBefore( frame ) {
  30438. const { renderer } = frame;
  30439. const textureNode = this.textureNode;
  30440. const map = textureNode.value;
  30441. const currentRenderTarget = renderer.getRenderTarget();
  30442. const currentTexture = textureNode.value;
  30443. quadMesh1.material = this._material;
  30444. quadMesh2.material = this._material;
  30445. this.setSize( map.image.width, map.image.height );
  30446. const textureType = map.type;
  30447. this._horizontalRT.texture.type = textureType;
  30448. this._verticalRT.texture.type = textureType;
  30449. // horizontal
  30450. renderer.setRenderTarget( this._horizontalRT );
  30451. this._passDirection.value.set( 1, 0 );
  30452. quadMesh1.render( renderer );
  30453. // vertical
  30454. textureNode.value = this._horizontalRT.texture;
  30455. renderer.setRenderTarget( this._verticalRT );
  30456. this._passDirection.value.set( 0, 1 );
  30457. quadMesh2.render( renderer );
  30458. // restore
  30459. renderer.setRenderTarget( currentRenderTarget );
  30460. textureNode.value = currentTexture;
  30461. }
  30462. getTextureNode() {
  30463. return this._textureNode;
  30464. }
  30465. setup( builder ) {
  30466. const textureNode = this.textureNode;
  30467. if ( textureNode.isTextureNode !== true ) {
  30468. console.error( 'GaussianBlurNode requires a TextureNode.' );
  30469. return vec4();
  30470. }
  30471. //
  30472. const uvNode = textureNode.uvNode || uv();
  30473. const directionNode = vec2( this.directionNode || 1 );
  30474. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30475. const blur = tslFn( () => {
  30476. const kernelSize = 3 + ( 2 * this.sigma );
  30477. const gaussianCoefficients = this._getCoefficients( kernelSize );
  30478. const invSize = this._invSize;
  30479. const direction = directionNode.mul( this._passDirection );
  30480. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  30481. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  30482. for ( let i = 1; i < kernelSize; i ++ ) {
  30483. const x = float( i );
  30484. const w = float( gaussianCoefficients[ i ] );
  30485. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  30486. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  30487. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  30488. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  30489. weightSum.addAssign( mul( 2.0, w ) );
  30490. }
  30491. return diffuseSum.div( weightSum );
  30492. } );
  30493. //
  30494. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30495. material.fragmentNode = blur().context( builder.getSharedContext() );
  30496. material.needsUpdate = true;
  30497. //
  30498. const properties = builder.getNodeProperties( this );
  30499. properties.textureNode = textureNode;
  30500. //
  30501. return this._textureNode;
  30502. }
  30503. _getCoefficients( kernelRadius ) {
  30504. const coefficients = [];
  30505. for ( let i = 0; i < kernelRadius; i ++ ) {
  30506. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  30507. }
  30508. return coefficients;
  30509. }
  30510. }
  30511. const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( nodeObject( node ).toTexture(), directionNode, sigma ) );
  30512. addNodeElement( 'gaussianBlur', gaussianBlur );
  30513. const _size$1 = new Vector2();
  30514. const quadMeshComp = new QuadMesh();
  30515. class AfterImageNode extends TempNode {
  30516. constructor( textureNode, damp = 0.96 ) {
  30517. super( textureNode );
  30518. this.textureNode = textureNode;
  30519. this.textureNodeOld = texture();
  30520. this.damp = uniform( damp );
  30521. this._compRT = new RenderTarget();
  30522. this._compRT.texture.name = 'AfterImageNode.comp';
  30523. this._oldRT = new RenderTarget();
  30524. this._oldRT.texture.name = 'AfterImageNode.old';
  30525. this._textureNode = texturePass( this, this._compRT.texture );
  30526. this.updateBeforeType = NodeUpdateType.RENDER;
  30527. }
  30528. getTextureNode() {
  30529. return this._textureNode;
  30530. }
  30531. setSize( width, height ) {
  30532. this._compRT.setSize( width, height );
  30533. this._oldRT.setSize( width, height );
  30534. }
  30535. updateBefore( frame ) {
  30536. const { renderer } = frame;
  30537. const textureNode = this.textureNode;
  30538. const map = textureNode.value;
  30539. const textureType = map.type;
  30540. this._compRT.texture.type = textureType;
  30541. this._oldRT.texture.type = textureType;
  30542. renderer.getDrawingBufferSize( _size$1 );
  30543. this.setSize( _size$1.x, _size$1.y );
  30544. const currentRenderTarget = renderer.getRenderTarget();
  30545. const currentTexture = textureNode.value;
  30546. this.textureNodeOld.value = this._oldRT.texture;
  30547. // comp
  30548. renderer.setRenderTarget( this._compRT );
  30549. quadMeshComp.render( renderer );
  30550. // Swap the textures
  30551. const temp = this._oldRT;
  30552. this._oldRT = this._compRT;
  30553. this._compRT = temp;
  30554. renderer.setRenderTarget( currentRenderTarget );
  30555. textureNode.value = currentTexture;
  30556. }
  30557. setup( builder ) {
  30558. const textureNode = this.textureNode;
  30559. const textureNodeOld = this.textureNodeOld;
  30560. //
  30561. const uvNode = textureNode.uvNode || uv();
  30562. textureNodeOld.uvNode = uvNode;
  30563. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30564. const when_gt = tslFn( ( [ x_immutable, y_immutable ] ) => {
  30565. const y = float( y_immutable ).toVar();
  30566. const x = vec4( x_immutable ).toVar();
  30567. return max$1( sign( x.sub( y ) ), 0.0 );
  30568. } );
  30569. const afterImg = tslFn( () => {
  30570. const texelOld = vec4( textureNodeOld );
  30571. const texelNew = vec4( sampleTexture( uvNode ) );
  30572. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  30573. return max$1( texelNew, texelOld );
  30574. } );
  30575. //
  30576. const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() );
  30577. materialComposed.fragmentNode = afterImg();
  30578. quadMeshComp.material = materialComposed;
  30579. //
  30580. const properties = builder.getNodeProperties( this );
  30581. properties.textureNode = textureNode;
  30582. //
  30583. return this._textureNode;
  30584. }
  30585. }
  30586. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( node ).toTexture(), damp ) );
  30587. addNodeElement( 'afterImage', afterImage );
  30588. const quadMesh$1 = new QuadMesh();
  30589. class AnamorphicNode extends TempNode {
  30590. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  30591. super( 'vec4' );
  30592. this.textureNode = textureNode;
  30593. this.tresholdNode = tresholdNode;
  30594. this.scaleNode = scaleNode;
  30595. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  30596. this.samples = samples;
  30597. this.resolution = new Vector2( 1, 1 );
  30598. this._renderTarget = new RenderTarget();
  30599. this._renderTarget.texture.name = 'anamorphic';
  30600. this._invSize = uniform( new Vector2() );
  30601. this._textureNode = texturePass( this, this._renderTarget.texture );
  30602. this.updateBeforeType = NodeUpdateType.RENDER;
  30603. }
  30604. getTextureNode() {
  30605. return this._textureNode;
  30606. }
  30607. setSize( width, height ) {
  30608. this._invSize.value.set( 1 / width, 1 / height );
  30609. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30610. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30611. this._renderTarget.setSize( width, height );
  30612. }
  30613. updateBefore( frame ) {
  30614. const { renderer } = frame;
  30615. const textureNode = this.textureNode;
  30616. const map = textureNode.value;
  30617. this._renderTarget.texture.type = map.type;
  30618. const currentRenderTarget = renderer.getRenderTarget();
  30619. const currentTexture = textureNode.value;
  30620. quadMesh$1.material = this._material;
  30621. this.setSize( map.image.width, map.image.height );
  30622. // render
  30623. renderer.setRenderTarget( this._renderTarget );
  30624. quadMesh$1.render( renderer );
  30625. // restore
  30626. renderer.setRenderTarget( currentRenderTarget );
  30627. textureNode.value = currentTexture;
  30628. }
  30629. setup( builder ) {
  30630. const textureNode = this.textureNode;
  30631. const uvNode = textureNode.uvNode || uv();
  30632. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30633. const anamorph = tslFn( () => {
  30634. const samples = this.samples;
  30635. const halfSamples = Math.floor( samples / 2 );
  30636. const total = vec3( 0 ).toVar();
  30637. loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  30638. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  30639. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  30640. const color = sampleTexture( uv );
  30641. const pass = threshold( color, this.tresholdNode ).mul( softness );
  30642. total.addAssign( pass );
  30643. } );
  30644. return total.mul( this.colorNode );
  30645. } );
  30646. //
  30647. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30648. material.fragmentNode = anamorph();
  30649. //
  30650. const properties = builder.getNodeProperties( this );
  30651. properties.textureNode = textureNode;
  30652. //
  30653. return this._textureNode;
  30654. }
  30655. }
  30656. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ).toTexture(), nodeObject( threshold ), nodeObject( scale ), samples ) );
  30657. addNodeElement( 'anamorphic', anamorphic );
  30658. class SobelOperatorNode extends TempNode {
  30659. constructor( textureNode ) {
  30660. super();
  30661. this.textureNode = textureNode;
  30662. this.updateBeforeType = NodeUpdateType.RENDER;
  30663. this._invSize = uniform( new Vector2() );
  30664. }
  30665. updateBefore() {
  30666. const map = this.textureNode.value;
  30667. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  30668. }
  30669. setup() {
  30670. const { textureNode } = this;
  30671. const uvNode = textureNode.uvNode || uv();
  30672. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30673. const sobel = tslFn( () => {
  30674. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  30675. const texel = this._invSize;
  30676. // kernel definition (in glsl matrices are filled in column-major order)
  30677. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  30678. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  30679. // fetch the 3x3 neighbourhood of a fragment
  30680. // first column
  30681. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  30682. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  30683. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  30684. // second column
  30685. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  30686. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  30687. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  30688. // third column
  30689. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  30690. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  30691. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  30692. // gradient value in x direction
  30693. const valueGx = add(
  30694. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  30695. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  30696. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  30697. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  30698. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  30699. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  30700. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  30701. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  30702. Gx[ 2 ][ 2 ].mul( tx2y2 )
  30703. );
  30704. // gradient value in y direction
  30705. const valueGy = add(
  30706. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  30707. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  30708. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  30709. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  30710. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  30711. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  30712. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  30713. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  30714. Gy[ 2 ][ 2 ].mul( tx2y2 )
  30715. );
  30716. // magnitute of the total gradient
  30717. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  30718. return vec4( vec3( G ), 1 );
  30719. } );
  30720. const outputNode = sobel();
  30721. return outputNode;
  30722. }
  30723. }
  30724. const sobel = ( node ) => nodeObject( new SobelOperatorNode( nodeObject( node ).toTexture() ) );
  30725. addNodeElement( 'sobel', sobel );
  30726. class DepthOfFieldNode extends TempNode {
  30727. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  30728. super();
  30729. this.textureNode = textureNode;
  30730. this.viewZNode = viewZNode;
  30731. this.focusNode = focusNode;
  30732. this.apertureNode = apertureNode;
  30733. this.maxblurNode = maxblurNode;
  30734. this._aspect = uniform( 0 );
  30735. this.updateBeforeType = NodeUpdateType.RENDER;
  30736. }
  30737. updateBefore() {
  30738. const map = this.textureNode.value;
  30739. this._aspect.value = map.image.width / map.image.height;
  30740. }
  30741. setup() {
  30742. const textureNode = this.textureNode;
  30743. const uvNode = textureNode.uvNode || uv();
  30744. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30745. const dof = tslFn( () => {
  30746. const aspectcorrect = vec2( 1.0, this._aspect );
  30747. const factor = this.focusNode.add( this.viewZNode );
  30748. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  30749. const dofblur9 = dofblur.mul( 0.9 );
  30750. const dofblur7 = dofblur.mul( 0.7 );
  30751. const dofblur4 = dofblur.mul( 0.4 );
  30752. let col = vec4( 0.0 );
  30753. col = col.add( sampleTexture( uvNode ) );
  30754. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30755. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30756. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30757. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30758. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30759. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30760. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30761. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30762. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30763. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30764. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30765. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30766. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30767. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30768. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30769. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30770. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30771. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30772. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30773. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30774. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30775. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30776. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30777. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30778. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30779. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30780. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30781. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30782. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30783. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30784. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30785. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30786. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30787. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30788. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30789. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30790. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30791. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30792. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30793. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30794. col = col.div( 41 );
  30795. col.a = 1;
  30796. return vec4( col );
  30797. } );
  30798. const outputNode = dof();
  30799. return outputNode;
  30800. }
  30801. }
  30802. 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 ) ) );
  30803. addNodeElement( 'dof', dof );
  30804. class DotScreenNode extends TempNode {
  30805. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  30806. super( 'vec4' );
  30807. this.inputNode = inputNode;
  30808. this.center = uniform( center );
  30809. this.angle = uniform( angle );
  30810. this.scale = uniform( scale );
  30811. this._size = uniform( new Vector2() );
  30812. this.updateBeforeType = NodeUpdateType.RENDER;
  30813. }
  30814. updateBefore() {
  30815. const map = this.inputNode.value;
  30816. this._size.value.set( map.image.width, map.image.height );
  30817. }
  30818. setup() {
  30819. const inputNode = this.inputNode;
  30820. const pattern = tslFn( () => {
  30821. const s = sin( this.angle );
  30822. const c = cos( this.angle );
  30823. const tex = uv().mul( this._size ).sub( this.center );
  30824. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  30825. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  30826. } );
  30827. const dotScreen = tslFn( () => {
  30828. const color = inputNode;
  30829. const average = add( color.r, color.g, color.b ).div( 3 );
  30830. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  30831. } );
  30832. const outputNode = dotScreen();
  30833. return outputNode;
  30834. }
  30835. }
  30836. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  30837. addNodeElement( 'dotScreen', dotScreen );
  30838. class RGBShiftNode extends TempNode {
  30839. constructor( textureNode, amount = 0.005, angle = 0 ) {
  30840. super( 'vec4' );
  30841. this.textureNode = textureNode;
  30842. this.amount = uniform( amount );
  30843. this.angle = uniform( angle );
  30844. }
  30845. setup() {
  30846. const { textureNode } = this;
  30847. const uvNode = textureNode.uvNode || uv();
  30848. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30849. const rgbShift = tslFn( () => {
  30850. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  30851. const cr = sampleTexture( uvNode.add( offset ) );
  30852. const cga = sampleTexture( uvNode );
  30853. const cb = sampleTexture( uvNode.sub( offset ) );
  30854. return vec4( cr.r, cga.g, cb.b, cga.a );
  30855. } );
  30856. return rgbShift();
  30857. }
  30858. }
  30859. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( nodeObject( node ).toTexture(), amount, angle ) );
  30860. addNodeElement( 'rgbShift', rgbShift );
  30861. class FilmNode extends TempNode {
  30862. constructor( inputNode, intensityNode = null, uvNode = null ) {
  30863. super();
  30864. this.inputNode = inputNode;
  30865. this.intensityNode = intensityNode;
  30866. this.uvNode = uvNode;
  30867. }
  30868. setup() {
  30869. const uvNode = this.uvNode || uv();
  30870. const film = tslFn( () => {
  30871. const base = this.inputNode.rgb;
  30872. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  30873. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  30874. if ( this.intensityNode !== null ) {
  30875. color = mix( base, color, this.intensityNode );
  30876. }
  30877. return vec4( color, this.inputNode.a );
  30878. } );
  30879. const outputNode = film();
  30880. return outputNode;
  30881. }
  30882. }
  30883. const film = nodeProxy( FilmNode );
  30884. addNodeElement( 'film', film );
  30885. class Lut3DNode extends TempNode {
  30886. constructor( inputNode, lutNode, size, intensityNode ) {
  30887. super();
  30888. this.inputNode = inputNode;
  30889. this.lutNode = lutNode;
  30890. this.size = uniform( size );
  30891. this.intensityNode = intensityNode;
  30892. }
  30893. setup() {
  30894. const { inputNode, lutNode } = this;
  30895. const sampleLut = ( uv ) => lutNode.uv( uv );
  30896. const lut3D = tslFn( () => {
  30897. const base = inputNode;
  30898. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  30899. const pixelWidth = float( 1.0 ).div( this.size );
  30900. const halfPixelWidth = float( 0.5 ).div( this.size );
  30901. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  30902. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  30903. return vec4( mix( base, lutValue, this.intensityNode ) );
  30904. } );
  30905. const outputNode = lut3D();
  30906. return outputNode;
  30907. }
  30908. }
  30909. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  30910. addNodeElement( 'lut3D', lut3D );
  30911. class RenderOutputNode extends TempNode {
  30912. constructor( colorNode, toneMapping, outputColorSpace ) {
  30913. super( 'vec4' );
  30914. this.colorNode = colorNode;
  30915. this.toneMapping = toneMapping;
  30916. this.outputColorSpace = outputColorSpace;
  30917. this.isRenderOutput = true;
  30918. }
  30919. setup( { context } ) {
  30920. let outputNode = this.colorNode || context.color;
  30921. // tone mapping
  30922. const toneMapping = this.toneMapping !== null ? this.toneMapping : context.toneMapping;
  30923. const outputColorSpace = this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace;
  30924. if ( toneMapping !== NoToneMapping ) {
  30925. outputNode = outputNode.toneMapping( toneMapping );
  30926. }
  30927. // output color space
  30928. if ( outputColorSpace === SRGBColorSpace ) {
  30929. outputNode = outputNode.linearToColorSpace( outputColorSpace );
  30930. }
  30931. return outputNode;
  30932. }
  30933. }
  30934. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  30935. addNodeElement( 'renderOutput', renderOutput );
  30936. addNodeClass( 'RenderOutputNode', RenderOutputNode );
  30937. class FunctionCallNode extends TempNode {
  30938. constructor( functionNode = null, parameters = {} ) {
  30939. super();
  30940. this.functionNode = functionNode;
  30941. this.parameters = parameters;
  30942. }
  30943. setParameters( parameters ) {
  30944. this.parameters = parameters;
  30945. return this;
  30946. }
  30947. getParameters() {
  30948. return this.parameters;
  30949. }
  30950. getNodeType( builder ) {
  30951. return this.functionNode.getNodeType( builder );
  30952. }
  30953. generate( builder ) {
  30954. const params = [];
  30955. const functionNode = this.functionNode;
  30956. const inputs = functionNode.getInputs( builder );
  30957. const parameters = this.parameters;
  30958. if ( Array.isArray( parameters ) ) {
  30959. for ( let i = 0; i < parameters.length; i ++ ) {
  30960. const inputNode = inputs[ i ];
  30961. const node = parameters[ i ];
  30962. params.push( node.build( builder, inputNode.type ) );
  30963. }
  30964. } else {
  30965. for ( const inputNode of inputs ) {
  30966. const node = parameters[ inputNode.name ];
  30967. if ( node !== undefined ) {
  30968. params.push( node.build( builder, inputNode.type ) );
  30969. } else {
  30970. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  30971. }
  30972. }
  30973. }
  30974. const functionName = functionNode.build( builder, 'property' );
  30975. return `${functionName}( ${params.join( ', ' )} )`;
  30976. }
  30977. }
  30978. const call = ( func, ...params ) => {
  30979. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  30980. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  30981. };
  30982. addNodeElement( 'call', call );
  30983. addNodeClass( 'FunctionCallNode', FunctionCallNode );
  30984. class ScriptableValueNode extends Node {
  30985. constructor( value = null ) {
  30986. super();
  30987. this._value = value;
  30988. this._cache = null;
  30989. this.inputType = null;
  30990. this.outpuType = null;
  30991. this.events = new EventDispatcher();
  30992. this.isScriptableValueNode = true;
  30993. }
  30994. get isScriptableOutputNode() {
  30995. return this.outputType !== null;
  30996. }
  30997. set value( val ) {
  30998. if ( this._value === val ) return;
  30999. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  31000. URL.revokeObjectURL( this._cache );
  31001. this._cache = null;
  31002. }
  31003. this._value = val;
  31004. this.events.dispatchEvent( { type: 'change' } );
  31005. this.refresh();
  31006. }
  31007. get value() {
  31008. return this._value;
  31009. }
  31010. refresh() {
  31011. this.events.dispatchEvent( { type: 'refresh' } );
  31012. }
  31013. getValue() {
  31014. const value = this.value;
  31015. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  31016. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  31017. } else if ( value && value.value !== null && value.value !== undefined && (
  31018. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  31019. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  31020. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  31021. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  31022. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  31023. ( this.inputType === 'Color' && value.value.isColor ) ||
  31024. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  31025. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  31026. ) ) {
  31027. return value.value;
  31028. }
  31029. return this._cache || value;
  31030. }
  31031. getNodeType( builder ) {
  31032. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  31033. }
  31034. setup() {
  31035. return this.value && this.value.isNode ? this.value : float();
  31036. }
  31037. serialize( data ) {
  31038. super.serialize( data );
  31039. if ( this.value !== null ) {
  31040. if ( this.inputType === 'ArrayBuffer' ) {
  31041. data.value = arrayBufferToBase64( this.value );
  31042. } else {
  31043. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  31044. }
  31045. } else {
  31046. data.value = null;
  31047. }
  31048. data.inputType = this.inputType;
  31049. data.outputType = this.outputType;
  31050. }
  31051. deserialize( data ) {
  31052. super.deserialize( data );
  31053. let value = null;
  31054. if ( data.value !== null ) {
  31055. if ( data.inputType === 'ArrayBuffer' ) {
  31056. value = base64ToArrayBuffer( data.value );
  31057. } else if ( data.inputType === 'Texture' ) {
  31058. value = data.meta.textures[ data.value ];
  31059. } else {
  31060. value = data.meta.nodes[ data.value ] || null;
  31061. }
  31062. }
  31063. this.value = value;
  31064. this.inputType = data.inputType;
  31065. this.outputType = data.outputType;
  31066. }
  31067. }
  31068. const scriptableValue = nodeProxy( ScriptableValueNode );
  31069. addNodeElement( 'scriptableValue', scriptableValue );
  31070. addNodeClass( 'ScriptableValueNode', ScriptableValueNode );
  31071. class Resources extends Map {
  31072. get( key, callback = null, ...params ) {
  31073. if ( this.has( key ) ) return super.get( key );
  31074. if ( callback !== null ) {
  31075. const value = callback( ...params );
  31076. this.set( key, value );
  31077. return value;
  31078. }
  31079. }
  31080. }
  31081. class Parameters {
  31082. constructor( scriptableNode ) {
  31083. this.scriptableNode = scriptableNode;
  31084. }
  31085. get parameters() {
  31086. return this.scriptableNode.parameters;
  31087. }
  31088. get layout() {
  31089. return this.scriptableNode.getLayout();
  31090. }
  31091. getInputLayout( id ) {
  31092. return this.scriptableNode.getInputLayout( id );
  31093. }
  31094. get( name ) {
  31095. const param = this.parameters[ name ];
  31096. const value = param ? param.getValue() : null;
  31097. return value;
  31098. }
  31099. }
  31100. const global = new Resources();
  31101. class ScriptableNode extends Node {
  31102. constructor( codeNode = null, parameters = {} ) {
  31103. super();
  31104. this.codeNode = codeNode;
  31105. this.parameters = parameters;
  31106. this._local = new Resources();
  31107. this._output = scriptableValue();
  31108. this._outputs = {};
  31109. this._source = this.source;
  31110. this._method = null;
  31111. this._object = null;
  31112. this._value = null;
  31113. this._needsOutputUpdate = true;
  31114. this.onRefresh = this.onRefresh.bind( this );
  31115. this.isScriptableNode = true;
  31116. }
  31117. get source() {
  31118. return this.codeNode ? this.codeNode.code : '';
  31119. }
  31120. setLocal( name, value ) {
  31121. return this._local.set( name, value );
  31122. }
  31123. getLocal( name ) {
  31124. return this._local.get( name );
  31125. }
  31126. onRefresh() {
  31127. this._refresh();
  31128. }
  31129. getInputLayout( id ) {
  31130. for ( const element of this.getLayout() ) {
  31131. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  31132. return element;
  31133. }
  31134. }
  31135. }
  31136. getOutputLayout( id ) {
  31137. for ( const element of this.getLayout() ) {
  31138. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  31139. return element;
  31140. }
  31141. }
  31142. }
  31143. setOutput( name, value ) {
  31144. const outputs = this._outputs;
  31145. if ( outputs[ name ] === undefined ) {
  31146. outputs[ name ] = scriptableValue( value );
  31147. } else {
  31148. outputs[ name ].value = value;
  31149. }
  31150. return this;
  31151. }
  31152. getOutput( name ) {
  31153. return this._outputs[ name ];
  31154. }
  31155. getParameter( name ) {
  31156. return this.parameters[ name ];
  31157. }
  31158. setParameter( name, value ) {
  31159. const parameters = this.parameters;
  31160. if ( value && value.isScriptableNode ) {
  31161. this.deleteParameter( name );
  31162. parameters[ name ] = value;
  31163. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  31164. } else if ( value && value.isScriptableValueNode ) {
  31165. this.deleteParameter( name );
  31166. parameters[ name ] = value;
  31167. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31168. } else if ( parameters[ name ] === undefined ) {
  31169. parameters[ name ] = scriptableValue( value );
  31170. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31171. } else {
  31172. parameters[ name ].value = value;
  31173. }
  31174. return this;
  31175. }
  31176. getValue() {
  31177. return this.getDefaultOutput().getValue();
  31178. }
  31179. deleteParameter( name ) {
  31180. let valueNode = this.parameters[ name ];
  31181. if ( valueNode ) {
  31182. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31183. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  31184. }
  31185. return this;
  31186. }
  31187. clearParameters() {
  31188. for ( const name of Object.keys( this.parameters ) ) {
  31189. this.deleteParameter( name );
  31190. }
  31191. this.needsUpdate = true;
  31192. return this;
  31193. }
  31194. call( name, ...params ) {
  31195. const object = this.getObject();
  31196. const method = object[ name ];
  31197. if ( typeof method === 'function' ) {
  31198. return method( ...params );
  31199. }
  31200. }
  31201. async callAsync( name, ...params ) {
  31202. const object = this.getObject();
  31203. const method = object[ name ];
  31204. if ( typeof method === 'function' ) {
  31205. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  31206. }
  31207. }
  31208. getNodeType( builder ) {
  31209. return this.getDefaultOutputNode().getNodeType( builder );
  31210. }
  31211. refresh( output = null ) {
  31212. if ( output !== null ) {
  31213. this.getOutput( output ).refresh();
  31214. } else {
  31215. this._refresh();
  31216. }
  31217. }
  31218. getObject() {
  31219. if ( this.needsUpdate ) this.dispose();
  31220. if ( this._object !== null ) return this._object;
  31221. //
  31222. const refresh = () => this.refresh();
  31223. const setOutput = ( id, value ) => this.setOutput( id, value );
  31224. const parameters = new Parameters( this );
  31225. const THREE = global.get( 'THREE' );
  31226. const TSL = global.get( 'TSL' );
  31227. const method = this.getMethod( this.codeNode );
  31228. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  31229. this._object = method( ...params );
  31230. const layout = this._object.layout;
  31231. if ( layout ) {
  31232. if ( layout.cache === false ) {
  31233. this._local.clear();
  31234. }
  31235. // default output
  31236. this._output.outputType = layout.outputType || null;
  31237. if ( Array.isArray( layout.elements ) ) {
  31238. for ( const element of layout.elements ) {
  31239. const id = element.id || element.name;
  31240. if ( element.inputType ) {
  31241. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  31242. this.getParameter( id ).inputType = element.inputType;
  31243. }
  31244. if ( element.outputType ) {
  31245. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  31246. this.getOutput( id ).outputType = element.outputType;
  31247. }
  31248. }
  31249. }
  31250. }
  31251. return this._object;
  31252. }
  31253. deserialize( data ) {
  31254. super.deserialize( data );
  31255. for ( const name in this.parameters ) {
  31256. let valueNode = this.parameters[ name ];
  31257. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31258. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  31259. }
  31260. }
  31261. getLayout() {
  31262. return this.getObject().layout;
  31263. }
  31264. getDefaultOutputNode() {
  31265. const output = this.getDefaultOutput().value;
  31266. if ( output && output.isNode ) {
  31267. return output;
  31268. }
  31269. return float();
  31270. }
  31271. getDefaultOutput() {
  31272. return this._exec()._output;
  31273. }
  31274. getMethod() {
  31275. if ( this.needsUpdate ) this.dispose();
  31276. if ( this._method !== null ) return this._method;
  31277. //
  31278. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  31279. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  31280. const properties = interfaceProps.join( ', ' );
  31281. const declarations = 'var ' + properties + '; var output = {};\n';
  31282. const returns = '\nreturn { ...output, ' + properties + ' };';
  31283. const code = declarations + this.codeNode.code + returns;
  31284. //
  31285. this._method = new Function( ...parametersProps, code );
  31286. return this._method;
  31287. }
  31288. dispose() {
  31289. if ( this._method === null ) return;
  31290. if ( this._object && typeof this._object.dispose === 'function' ) {
  31291. this._object.dispose();
  31292. }
  31293. this._method = null;
  31294. this._object = null;
  31295. this._source = null;
  31296. this._value = null;
  31297. this._needsOutputUpdate = true;
  31298. this._output.value = null;
  31299. this._outputs = {};
  31300. }
  31301. setup() {
  31302. return this.getDefaultOutputNode();
  31303. }
  31304. set needsUpdate( value ) {
  31305. if ( value === true ) this.dispose();
  31306. }
  31307. get needsUpdate() {
  31308. return this.source !== this._source;
  31309. }
  31310. _exec() {
  31311. if ( this.codeNode === null ) return this;
  31312. if ( this._needsOutputUpdate === true ) {
  31313. this._value = this.call( 'main' );
  31314. this._needsOutputUpdate = false;
  31315. }
  31316. this._output.value = this._value;
  31317. return this;
  31318. }
  31319. _refresh() {
  31320. this.needsUpdate = true;
  31321. this._exec();
  31322. this._output.refresh();
  31323. }
  31324. }
  31325. const scriptable = nodeProxy( ScriptableNode );
  31326. addNodeElement( 'scriptable', scriptable );
  31327. addNodeClass( 'ScriptableNode', ScriptableNode );
  31328. class FogNode extends Node {
  31329. constructor( colorNode, factorNode ) {
  31330. super( 'float' );
  31331. this.isFogNode = true;
  31332. this.colorNode = colorNode;
  31333. this.factorNode = factorNode;
  31334. }
  31335. getViewZNode( builder ) {
  31336. let viewZ;
  31337. const getViewZ = builder.context.getViewZ;
  31338. if ( getViewZ !== undefined ) {
  31339. viewZ = getViewZ( this );
  31340. }
  31341. return ( viewZ || positionView.z ).negate();
  31342. }
  31343. setup() {
  31344. return this.factorNode;
  31345. }
  31346. }
  31347. const fog = nodeProxy( FogNode );
  31348. addNodeElement( 'fog', fog );
  31349. addNodeClass( 'FogNode', FogNode );
  31350. class FogRangeNode extends FogNode {
  31351. constructor( colorNode, nearNode, farNode ) {
  31352. super( colorNode );
  31353. this.isFogRangeNode = true;
  31354. this.nearNode = nearNode;
  31355. this.farNode = farNode;
  31356. }
  31357. setup( builder ) {
  31358. const viewZ = this.getViewZNode( builder );
  31359. return smoothstep( this.nearNode, this.farNode, viewZ );
  31360. }
  31361. }
  31362. const rangeFog = nodeProxy( FogRangeNode );
  31363. addNodeElement( 'rangeFog', rangeFog );
  31364. addNodeClass( 'FogRangeNode', FogRangeNode );
  31365. class FogExp2Node extends FogNode {
  31366. constructor( colorNode, densityNode ) {
  31367. super( colorNode );
  31368. this.isFogExp2Node = true;
  31369. this.densityNode = densityNode;
  31370. }
  31371. setup( builder ) {
  31372. const viewZ = this.getViewZNode( builder );
  31373. const density = this.densityNode;
  31374. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  31375. }
  31376. }
  31377. const densityFog = nodeProxy( FogExp2Node );
  31378. addNodeElement( 'densityFog', densityFog );
  31379. addNodeClass( 'FogExp2Node', FogExp2Node );
  31380. let min = null;
  31381. let max = null;
  31382. class RangeNode extends Node {
  31383. constructor( minNode = float(), maxNode = float() ) {
  31384. super();
  31385. this.minNode = minNode;
  31386. this.maxNode = maxNode;
  31387. }
  31388. getVectorLength( builder ) {
  31389. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  31390. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  31391. return minLength > maxLength ? minLength : maxLength;
  31392. }
  31393. getNodeType( builder ) {
  31394. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  31395. }
  31396. setup( builder ) {
  31397. const object = builder.object;
  31398. let output = null;
  31399. if ( object.count > 1 ) {
  31400. const minValue = this.minNode.value;
  31401. const maxValue = this.maxNode.value;
  31402. const minLength = builder.getTypeLength( getValueType( minValue ) );
  31403. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  31404. min = min || new Vector4();
  31405. max = max || new Vector4();
  31406. min.setScalar( 0 );
  31407. max.setScalar( 0 );
  31408. if ( minLength === 1 ) min.setScalar( minValue );
  31409. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  31410. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  31411. if ( maxLength === 1 ) max.setScalar( maxValue );
  31412. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  31413. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  31414. const stride = 4;
  31415. const length = stride * object.count;
  31416. const array = new Float32Array( length );
  31417. for ( let i = 0; i < length; i ++ ) {
  31418. const index = i % stride;
  31419. const minElementValue = min.getComponent( index );
  31420. const maxElementValue = max.getComponent( index );
  31421. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  31422. }
  31423. const nodeType = this.getNodeType( builder );
  31424. if ( object.count <= 4096 ) {
  31425. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  31426. } else {
  31427. // TODO: Improve anonymous buffer attribute creation removing this part
  31428. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  31429. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  31430. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  31431. }
  31432. } else {
  31433. output = float( 0 );
  31434. }
  31435. return output;
  31436. }
  31437. }
  31438. const range = nodeProxy( RangeNode );
  31439. addNodeClass( 'RangeNode', RangeNode );
  31440. class ComputeNode extends Node {
  31441. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  31442. super( 'void' );
  31443. this.isComputeNode = true;
  31444. this.computeNode = computeNode;
  31445. this.count = count;
  31446. this.workgroupSize = workgroupSize;
  31447. this.dispatchCount = 0;
  31448. this.version = 1;
  31449. this.updateBeforeType = NodeUpdateType.OBJECT;
  31450. this.updateDispatchCount();
  31451. }
  31452. dispose() {
  31453. this.dispatchEvent( { type: 'dispose' } );
  31454. }
  31455. set needsUpdate( value ) {
  31456. if ( value === true ) this.version ++;
  31457. }
  31458. updateDispatchCount() {
  31459. const { count, workgroupSize } = this;
  31460. let size = workgroupSize[ 0 ];
  31461. for ( let i = 1; i < workgroupSize.length; i ++ )
  31462. size *= workgroupSize[ i ];
  31463. this.dispatchCount = Math.ceil( count / size );
  31464. }
  31465. onInit() { }
  31466. updateBefore( { renderer } ) {
  31467. renderer.compute( this );
  31468. }
  31469. generate( builder ) {
  31470. const { shaderStage } = builder;
  31471. if ( shaderStage === 'compute' ) {
  31472. const snippet = this.computeNode.build( builder, 'void' );
  31473. if ( snippet !== '' ) {
  31474. builder.addLineFlowCode( snippet );
  31475. }
  31476. }
  31477. }
  31478. }
  31479. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  31480. addNodeElement( 'compute', compute );
  31481. addNodeClass( 'ComputeNode', ComputeNode );
  31482. class LightNode extends Node {
  31483. constructor( scope = LightNode.TARGET_DIRECTION, light = null ) {
  31484. super();
  31485. this.scope = scope;
  31486. this.light = light;
  31487. }
  31488. setup() {
  31489. const { scope, light } = this;
  31490. let output = null;
  31491. if ( scope === LightNode.TARGET_DIRECTION ) {
  31492. output = cameraViewMatrix.transformDirection( objectPosition( light ).sub( objectPosition( light.target ) ) );
  31493. }
  31494. return output;
  31495. }
  31496. serialize( data ) {
  31497. super.serialize( data );
  31498. data.scope = this.scope;
  31499. }
  31500. deserialize( data ) {
  31501. super.deserialize( data );
  31502. this.scope = data.scope;
  31503. }
  31504. }
  31505. LightNode.TARGET_DIRECTION = 'targetDirection';
  31506. const lightTargetDirection = nodeProxy( LightNode, LightNode.TARGET_DIRECTION );
  31507. addNodeClass( 'LightNode', LightNode );
  31508. const getDistanceAttenuation = tslFn( ( inputs ) => {
  31509. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  31510. // based upon Frostbite 3 Moving to Physically-based Rendering
  31511. // page 32, equation 26: E[window1]
  31512. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31513. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31514. return cutoffDistance.greaterThan( 0 ).cond(
  31515. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31516. distanceFalloff
  31517. );
  31518. } ); // validated
  31519. class PointLightNode extends AnalyticLightNode {
  31520. constructor( light = null ) {
  31521. super( light );
  31522. this.cutoffDistanceNode = uniform( 0 );
  31523. this.decayExponentNode = uniform( 0 );
  31524. }
  31525. update( frame ) {
  31526. const { light } = this;
  31527. super.update( frame );
  31528. this.cutoffDistanceNode.value = light.distance;
  31529. this.decayExponentNode.value = light.decay;
  31530. }
  31531. setup( builder ) {
  31532. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31533. const lightingModel = builder.context.lightingModel;
  31534. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31535. const lightDirection = lVector.normalize();
  31536. const lightDistance = lVector.length();
  31537. const lightAttenuation = getDistanceAttenuation( {
  31538. lightDistance,
  31539. cutoffDistance: cutoffDistanceNode,
  31540. decayExponent: decayExponentNode
  31541. } );
  31542. const lightColor = colorNode.mul( lightAttenuation );
  31543. const reflectedLight = builder.context.reflectedLight;
  31544. lightingModel.direct( {
  31545. lightDirection,
  31546. lightColor,
  31547. reflectedLight,
  31548. shadowMask: this.shadowMaskNode
  31549. }, builder.stack, builder );
  31550. }
  31551. }
  31552. addNodeClass( 'PointLightNode', PointLightNode );
  31553. addLightNode( PointLight, PointLightNode );
  31554. class DirectionalLightNode extends AnalyticLightNode {
  31555. constructor( light = null ) {
  31556. super( light );
  31557. }
  31558. setup( builder ) {
  31559. super.setup( builder );
  31560. const lightingModel = builder.context.lightingModel;
  31561. const lightColor = this.colorNode;
  31562. const lightDirection = lightTargetDirection( this.light );
  31563. const reflectedLight = builder.context.reflectedLight;
  31564. lightingModel.direct( {
  31565. lightDirection,
  31566. lightColor,
  31567. reflectedLight,
  31568. shadowMask: this.shadowMaskNode
  31569. }, builder.stack, builder );
  31570. }
  31571. }
  31572. addNodeClass( 'DirectionalLightNode', DirectionalLightNode );
  31573. addLightNode( DirectionalLight, DirectionalLightNode );
  31574. const _matrix41 = new Matrix4();
  31575. const _matrix42 = new Matrix4();
  31576. let ltcLib = null;
  31577. class RectAreaLightNode extends AnalyticLightNode {
  31578. constructor( light = null ) {
  31579. super( light );
  31580. this.halfHeight = uniform( new Vector3() );
  31581. this.halfWidth = uniform( new Vector3() );
  31582. }
  31583. update( frame ) {
  31584. super.update( frame );
  31585. const { light } = this;
  31586. const viewMatrix = frame.camera.matrixWorldInverse;
  31587. _matrix42.identity();
  31588. _matrix41.copy( light.matrixWorld );
  31589. _matrix41.premultiply( viewMatrix );
  31590. _matrix42.extractRotation( _matrix41 );
  31591. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31592. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31593. this.halfWidth.value.applyMatrix4( _matrix42 );
  31594. this.halfHeight.value.applyMatrix4( _matrix42 );
  31595. }
  31596. setup( builder ) {
  31597. super.setup( builder );
  31598. let ltc_1, ltc_2;
  31599. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31600. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  31601. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  31602. } else {
  31603. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  31604. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  31605. }
  31606. const { colorNode, light } = this;
  31607. const lightingModel = builder.context.lightingModel;
  31608. const lightPosition = objectViewPosition( light );
  31609. const reflectedLight = builder.context.reflectedLight;
  31610. lightingModel.directRectArea( {
  31611. lightColor: colorNode,
  31612. lightPosition,
  31613. halfWidth: this.halfWidth,
  31614. halfHeight: this.halfHeight,
  31615. reflectedLight,
  31616. ltc_1,
  31617. ltc_2
  31618. }, builder.stack, builder );
  31619. }
  31620. static setLTC( ltc ) {
  31621. ltcLib = ltc;
  31622. }
  31623. }
  31624. addNodeClass( 'RectAreaLightNode', RectAreaLightNode );
  31625. addLightNode( RectAreaLight, RectAreaLightNode );
  31626. class SpotLightNode extends AnalyticLightNode {
  31627. constructor( light = null ) {
  31628. super( light );
  31629. this.coneCosNode = uniform( 0 );
  31630. this.penumbraCosNode = uniform( 0 );
  31631. this.cutoffDistanceNode = uniform( 0 );
  31632. this.decayExponentNode = uniform( 0 );
  31633. }
  31634. update( frame ) {
  31635. super.update( frame );
  31636. const { light } = this;
  31637. this.coneCosNode.value = Math.cos( light.angle );
  31638. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31639. this.cutoffDistanceNode.value = light.distance;
  31640. this.decayExponentNode.value = light.decay;
  31641. }
  31642. getSpotAttenuation( angleCosine ) {
  31643. const { coneCosNode, penumbraCosNode } = this;
  31644. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31645. }
  31646. setup( builder ) {
  31647. super.setup( builder );
  31648. const lightingModel = builder.context.lightingModel;
  31649. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31650. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31651. const lightDirection = lVector.normalize();
  31652. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31653. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31654. const lightDistance = lVector.length();
  31655. const lightAttenuation = getDistanceAttenuation( {
  31656. lightDistance,
  31657. cutoffDistance: cutoffDistanceNode,
  31658. decayExponent: decayExponentNode
  31659. } );
  31660. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31661. const reflectedLight = builder.context.reflectedLight;
  31662. lightingModel.direct( {
  31663. lightDirection,
  31664. lightColor,
  31665. reflectedLight,
  31666. shadowMask: this.shadowMaskNode
  31667. }, builder.stack, builder );
  31668. }
  31669. }
  31670. addNodeClass( 'SpotLightNode', SpotLightNode );
  31671. addLightNode( SpotLight, SpotLightNode );
  31672. class IESSpotLight extends SpotLight {
  31673. constructor( color, intensity, distance, angle, penumbra, decay ) {
  31674. super( color, intensity, distance, angle, penumbra, decay );
  31675. this.iesMap = null;
  31676. }
  31677. copy( source, recursive ) {
  31678. super.copy( source, recursive );
  31679. this.iesMap = source.iesMap;
  31680. return this;
  31681. }
  31682. }
  31683. class IESSpotLightNode extends SpotLightNode {
  31684. getSpotAttenuation( angleCosine ) {
  31685. const iesMap = this.light.iesMap;
  31686. let spotAttenuation = null;
  31687. if ( iesMap && iesMap.isTexture === true ) {
  31688. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31689. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31690. } else {
  31691. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31692. }
  31693. return spotAttenuation;
  31694. }
  31695. }
  31696. addNodeClass( 'IESSpotLightNode', IESSpotLightNode );
  31697. addLightNode( IESSpotLight, IESSpotLightNode );
  31698. class AmbientLightNode extends AnalyticLightNode {
  31699. constructor( light = null ) {
  31700. super( light );
  31701. }
  31702. setup( { context } ) {
  31703. context.irradiance.addAssign( this.colorNode );
  31704. }
  31705. }
  31706. addNodeClass( 'AmbientLightNode', AmbientLightNode );
  31707. addLightNode( AmbientLight, AmbientLightNode );
  31708. class HemisphereLightNode extends AnalyticLightNode {
  31709. constructor( light = null ) {
  31710. super( light );
  31711. this.lightPositionNode = objectPosition( light );
  31712. this.lightDirectionNode = this.lightPositionNode.normalize();
  31713. this.groundColorNode = uniform( new Color() );
  31714. }
  31715. update( frame ) {
  31716. const { light } = this;
  31717. super.update( frame );
  31718. this.lightPositionNode.object3d = light;
  31719. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31720. }
  31721. setup( builder ) {
  31722. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31723. const dotNL = normalView.dot( lightDirectionNode );
  31724. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31725. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31726. builder.context.irradiance.addAssign( irradiance );
  31727. }
  31728. }
  31729. addNodeClass( 'HemisphereLightNode', HemisphereLightNode );
  31730. addLightNode( HemisphereLight, HemisphereLightNode );
  31731. let _generator = null;
  31732. const _cache = new WeakMap();
  31733. function _generateCubeUVSize( imageHeight ) {
  31734. const maxMip = Math.log2( imageHeight ) - 2;
  31735. const texelHeight = 1.0 / imageHeight;
  31736. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  31737. return { texelWidth, texelHeight, maxMip };
  31738. }
  31739. function _getPMREMFromTexture( texture ) {
  31740. let cacheTexture = _cache.get( texture );
  31741. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  31742. if ( pmremVersion !== texture.pmremVersion ) {
  31743. if ( texture.isCubeTexture ) {
  31744. if ( texture.source.data.some( ( texture ) => texture === undefined ) ) {
  31745. throw new Error( 'PMREMNode: Undefined texture in CubeTexture. Use onLoad callback or async loader' );
  31746. }
  31747. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  31748. } else {
  31749. if ( texture.image === undefined ) {
  31750. throw new Error( 'PMREMNode: Undefined image in Texture. Use onLoad callback or async loader' );
  31751. }
  31752. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  31753. }
  31754. cacheTexture.pmremVersion = texture.pmremVersion;
  31755. _cache.set( texture, cacheTexture );
  31756. }
  31757. return cacheTexture.texture;
  31758. }
  31759. class PMREMNode extends TempNode {
  31760. constructor( value, uvNode = null, levelNode = null ) {
  31761. super( 'vec3' );
  31762. this._value = value;
  31763. this._pmrem = null;
  31764. this.uvNode = uvNode;
  31765. this.levelNode = levelNode;
  31766. this._generator = null;
  31767. this._texture = texture( null );
  31768. this._width = uniform( 0 );
  31769. this._height = uniform( 0 );
  31770. this._maxMip = uniform( 0 );
  31771. this.updateBeforeType = NodeUpdateType.RENDER;
  31772. }
  31773. set value( value ) {
  31774. this._value = value;
  31775. this._pmrem = null;
  31776. }
  31777. get value() {
  31778. return this._value;
  31779. }
  31780. updateFromTexture( texture ) {
  31781. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  31782. this._texture.value = texture;
  31783. this._width.value = cubeUVSize.texelWidth;
  31784. this._height.value = cubeUVSize.texelHeight;
  31785. this._maxMip.value = cubeUVSize.maxMip;
  31786. }
  31787. updateBefore() {
  31788. let pmrem = this._pmrem;
  31789. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  31790. const texture = this._value;
  31791. if ( pmremVersion !== texture.pmremVersion ) {
  31792. if ( texture.isPMREMTexture === true ) {
  31793. pmrem = texture;
  31794. } else {
  31795. pmrem = _getPMREMFromTexture( texture );
  31796. }
  31797. this._pmrem = pmrem;
  31798. this.updateFromTexture( pmrem );
  31799. }
  31800. }
  31801. setup( builder ) {
  31802. if ( _generator === null ) {
  31803. _generator = builder.createPMREMGenerator();
  31804. }
  31805. //
  31806. this.updateBefore( builder );
  31807. //
  31808. let uvNode = this.uvNode;
  31809. if ( uvNode === null && builder.context.getUV ) {
  31810. uvNode = builder.context.getUV( this );
  31811. }
  31812. //
  31813. const texture = this.value;
  31814. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  31815. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  31816. }
  31817. //
  31818. let levelNode = this.levelNode;
  31819. if ( levelNode === null && builder.context.getTextureLevel ) {
  31820. levelNode = builder.context.getTextureLevel( this );
  31821. }
  31822. //
  31823. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  31824. }
  31825. }
  31826. const pmremTexture = nodeProxy( PMREMNode );
  31827. addNodeClass( 'PMREMNode', PMREMNode );
  31828. const envNodeCache = new WeakMap();
  31829. class EnvironmentNode extends LightingNode {
  31830. constructor( envNode = null ) {
  31831. super();
  31832. this.envNode = envNode;
  31833. }
  31834. setup( builder ) {
  31835. let envNode = this.envNode;
  31836. if ( envNode.isTextureNode ) {
  31837. let cacheEnvNode = envNodeCache.get( envNode.value );
  31838. if ( cacheEnvNode === undefined ) {
  31839. cacheEnvNode = pmremTexture( envNode.value );
  31840. envNodeCache.set( envNode.value, cacheEnvNode );
  31841. }
  31842. envNode = cacheEnvNode;
  31843. }
  31844. //
  31845. const { material } = builder;
  31846. const envMap = material.envMap;
  31847. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  31848. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  31849. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  31850. const radiance = context( envNode, createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  31851. const irradiance = context( envNode, createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  31852. const isolateRadiance = cache( radiance );
  31853. const isolateIrradiance = cache( irradiance );
  31854. //
  31855. builder.context.radiance.addAssign( isolateRadiance );
  31856. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  31857. //
  31858. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  31859. if ( clearcoatRadiance ) {
  31860. const clearcoatRadianceContext = context( envNode, createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  31861. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  31862. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  31863. }
  31864. }
  31865. }
  31866. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  31867. let reflectVec = null;
  31868. return {
  31869. getUV: () => {
  31870. if ( reflectVec === null ) {
  31871. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  31872. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  31873. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  31874. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  31875. }
  31876. return reflectVec;
  31877. },
  31878. getTextureLevel: () => {
  31879. return roughnessNode;
  31880. }
  31881. };
  31882. };
  31883. const createIrradianceContext = ( normalWorldNode ) => {
  31884. return {
  31885. getUV: () => {
  31886. return normalWorldNode;
  31887. },
  31888. getTextureLevel: () => {
  31889. return float( 1.0 );
  31890. }
  31891. };
  31892. };
  31893. addNodeClass( 'EnvironmentNode', EnvironmentNode );
  31894. class BasicEnvironmentNode extends LightingNode {
  31895. constructor( envNode = null ) {
  31896. super();
  31897. this.envNode = envNode;
  31898. }
  31899. setup( builder ) {
  31900. // environment property is used in the finish() method of BasicLightingModel
  31901. builder.context.environment = this.envNode;
  31902. }
  31903. }
  31904. addNodeClass( 'BasicEnvironmentNode', BasicEnvironmentNode );
  31905. const checkerShaderNode = tslFn( ( inputs ) => {
  31906. const uv = inputs.uv.mul( 2.0 );
  31907. const cx = uv.x.floor();
  31908. const cy = uv.y.floor();
  31909. const result = cx.add( cy ).mod( 2.0 );
  31910. return result.sign();
  31911. } );
  31912. class CheckerNode extends TempNode {
  31913. constructor( uvNode = uv() ) {
  31914. super( 'float' );
  31915. this.uvNode = uvNode;
  31916. }
  31917. setup() {
  31918. return checkerShaderNode( { uv: this.uvNode } );
  31919. }
  31920. }
  31921. const checker = nodeProxy( CheckerNode );
  31922. addNodeElement( 'checker', checker );
  31923. addNodeClass( 'CheckerNode', CheckerNode );
  31924. class NodeLoader extends Loader {
  31925. constructor( manager ) {
  31926. super( manager );
  31927. this.textures = {};
  31928. }
  31929. load( url, onLoad, onProgress, onError ) {
  31930. const loader = new FileLoader( this.manager );
  31931. loader.setPath( this.path );
  31932. loader.setRequestHeader( this.requestHeader );
  31933. loader.setWithCredentials( this.withCredentials );
  31934. loader.load( url, ( text ) => {
  31935. try {
  31936. onLoad( this.parse( JSON.parse( text ) ) );
  31937. } catch ( e ) {
  31938. if ( onError ) {
  31939. onError( e );
  31940. } else {
  31941. console.error( e );
  31942. }
  31943. this.manager.itemError( url );
  31944. }
  31945. }, onProgress, onError );
  31946. }
  31947. parseNodes( json ) {
  31948. const nodes = {};
  31949. if ( json !== undefined ) {
  31950. for ( const nodeJSON of json ) {
  31951. const { uuid, type } = nodeJSON;
  31952. nodes[ uuid ] = nodeObject( createNodeFromType( type ) ); // @TODO: Maybe nodeObjectify the node in createNodeFromType?
  31953. nodes[ uuid ].uuid = uuid;
  31954. }
  31955. const meta = { nodes, textures: this.textures };
  31956. for ( const nodeJSON of json ) {
  31957. nodeJSON.meta = meta;
  31958. const node = nodes[ nodeJSON.uuid ];
  31959. node.deserialize( nodeJSON );
  31960. delete nodeJSON.meta;
  31961. }
  31962. }
  31963. return nodes;
  31964. }
  31965. parse( json ) {
  31966. const node = nodeObject( createNodeFromType( json.type ) );
  31967. node.uuid = json.uuid;
  31968. const nodes = this.parseNodes( json.nodes );
  31969. const meta = { nodes, textures: this.textures };
  31970. json.meta = meta;
  31971. node.deserialize( json );
  31972. delete json.meta;
  31973. return node;
  31974. }
  31975. setTextures( value ) {
  31976. this.textures = value;
  31977. return this;
  31978. }
  31979. }
  31980. const defaultValues$e = new PointsMaterial();
  31981. class InstancedPointsNodeMaterial extends NodeMaterial {
  31982. constructor( params = {} ) {
  31983. super();
  31984. this.normals = false;
  31985. this.lights = false;
  31986. this.useAlphaToCoverage = true;
  31987. this.useColor = params.vertexColors;
  31988. this.pointWidth = 1;
  31989. this.pointColorNode = null;
  31990. this.setDefaultValues( defaultValues$e );
  31991. this.setupShaders();
  31992. this.setValues( params );
  31993. }
  31994. setupShaders() {
  31995. const useAlphaToCoverage = this.alphaToCoverage;
  31996. const useColor = this.useColor;
  31997. this.vertexNode = tslFn( () => {
  31998. //vUv = uv;
  31999. varying( vec2(), 'vUv' ).assign( uv() ); // @TODO: Analyze other way to do this
  32000. const instancePosition = attribute( 'instancePosition' );
  32001. // camera space
  32002. const mvPos = property( 'vec4', 'mvPos' );
  32003. mvPos.assign( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  32004. const aspect = viewport.z.div( viewport.w );
  32005. // clip space
  32006. const clipPos = cameraProjectionMatrix.mul( mvPos );
  32007. // offset in ndc space
  32008. const offset = property( 'vec2', 'offset' );
  32009. offset.assign( positionGeometry.xy );
  32010. offset.assign( offset.mul( materialPointWidth ) );
  32011. offset.assign( offset.div( viewport.z ) );
  32012. offset.y.assign( offset.y.mul( aspect ) );
  32013. // back to clip space
  32014. offset.assign( offset.mul( clipPos.w ) );
  32015. //clipPos.xy += offset;
  32016. clipPos.assign( clipPos.add( vec4( offset, 0, 0 ) ) );
  32017. return clipPos;
  32018. //vec4 mvPosition = mvPos; // this was used for somethihng...
  32019. } )();
  32020. this.fragmentNode = tslFn( () => {
  32021. const vUv = varying( vec2(), 'vUv' );
  32022. // force assignment into correct place in flow
  32023. const alpha = property( 'float', 'alpha' );
  32024. alpha.assign( 1 );
  32025. const a = vUv.x;
  32026. const b = vUv.y;
  32027. const len2 = a.mul( a ).add( b.mul( b ) );
  32028. if ( useAlphaToCoverage ) {
  32029. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  32030. const dlen = property( 'float', 'dlen' );
  32031. dlen.assign( len2.fwidth() );
  32032. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  32033. } else {
  32034. len2.greaterThan( 1.0 ).discard();
  32035. }
  32036. let pointColorNode;
  32037. if ( this.pointColorNode ) {
  32038. pointColorNode = this.pointColorNode;
  32039. } else {
  32040. if ( useColor ) {
  32041. const instanceColor = attribute( 'instanceColor' );
  32042. pointColorNode = instanceColor.mul( materialColor );
  32043. } else {
  32044. pointColorNode = materialColor;
  32045. }
  32046. }
  32047. return vec4( pointColorNode, alpha );
  32048. } )();
  32049. this.needsUpdate = true;
  32050. }
  32051. get alphaToCoverage() {
  32052. return this.useAlphaToCoverage;
  32053. }
  32054. set alphaToCoverage( value ) {
  32055. if ( this.useAlphaToCoverage !== value ) {
  32056. this.useAlphaToCoverage = value;
  32057. this.setupShaders();
  32058. }
  32059. }
  32060. }
  32061. addNodeMaterial( 'InstancedPointsNodeMaterial', InstancedPointsNodeMaterial );
  32062. const defaultValues$d = new LineBasicMaterial();
  32063. class LineBasicNodeMaterial extends NodeMaterial {
  32064. constructor( parameters ) {
  32065. super();
  32066. this.isLineBasicNodeMaterial = true;
  32067. this.lights = false;
  32068. this.normals = false;
  32069. this.setDefaultValues( defaultValues$d );
  32070. this.setValues( parameters );
  32071. }
  32072. }
  32073. addNodeMaterial( 'LineBasicNodeMaterial', LineBasicNodeMaterial );
  32074. const defaultValues$c = new LineDashedMaterial();
  32075. class LineDashedNodeMaterial extends NodeMaterial {
  32076. constructor( parameters ) {
  32077. super();
  32078. this.isLineDashedNodeMaterial = true;
  32079. this.lights = false;
  32080. this.normals = false;
  32081. this.setDefaultValues( defaultValues$c );
  32082. this.offsetNode = null;
  32083. this.dashScaleNode = null;
  32084. this.dashSizeNode = null;
  32085. this.gapSizeNode = null;
  32086. this.setValues( parameters );
  32087. }
  32088. setupVariants() {
  32089. const offsetNode = this.offsetNode;
  32090. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  32091. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  32092. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  32093. dashSize.assign( dashSizeNode );
  32094. gapSize.assign( gapSizeNode );
  32095. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  32096. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  32097. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  32098. }
  32099. }
  32100. addNodeMaterial( 'LineDashedNodeMaterial', LineDashedNodeMaterial );
  32101. const defaultValues$b = new LineDashedMaterial();
  32102. class Line2NodeMaterial extends NodeMaterial {
  32103. constructor( params = {} ) {
  32104. super();
  32105. this.normals = false;
  32106. this.lights = false;
  32107. this.setDefaultValues( defaultValues$b );
  32108. this.useAlphaToCoverage = true;
  32109. this.useColor = params.vertexColors;
  32110. this.useDash = params.dashed;
  32111. this.useWorldUnits = false;
  32112. this.dashOffset = 0;
  32113. this.lineWidth = 1;
  32114. this.lineColorNode = null;
  32115. this.offsetNode = null;
  32116. this.dashScaleNode = null;
  32117. this.dashSizeNode = null;
  32118. this.gapSizeNode = null;
  32119. this.setValues( params );
  32120. }
  32121. setup( builder ) {
  32122. this.setupShaders();
  32123. super.setup( builder );
  32124. }
  32125. setupShaders() {
  32126. const useAlphaToCoverage = this.alphaToCoverage;
  32127. const useColor = this.useColor;
  32128. const useDash = this.dashed;
  32129. const useWorldUnits = this.worldUnits;
  32130. const trimSegment = tslFn( ( { start, end } ) => {
  32131. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  32132. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  32133. const nearEstimate = b.mul( - 0.5 ).div( a );
  32134. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  32135. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  32136. } );
  32137. this.vertexNode = tslFn( () => {
  32138. varyingProperty( 'vec2', 'vUv' ).assign( uv() );
  32139. const instanceStart = attribute( 'instanceStart' );
  32140. const instanceEnd = attribute( 'instanceEnd' );
  32141. // camera space
  32142. const start = property( 'vec4', 'start' );
  32143. const end = property( 'vec4', 'end' );
  32144. start.assign( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ); // force assignment into correct place in flow
  32145. end.assign( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) );
  32146. if ( useWorldUnits ) {
  32147. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  32148. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  32149. }
  32150. const aspect = viewport.z.div( viewport.w );
  32151. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  32152. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  32153. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  32154. // perhaps there is a more elegant solution -- WestLangley
  32155. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  32156. If( perspective, () => {
  32157. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  32158. end.assign( trimSegment( { start: start, end: end } ) );
  32159. } ).elseif( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  32160. start.assign( trimSegment( { start: end, end: start } ) );
  32161. } );
  32162. } );
  32163. // clip space
  32164. const clipStart = cameraProjectionMatrix.mul( start );
  32165. const clipEnd = cameraProjectionMatrix.mul( end );
  32166. // ndc space
  32167. const ndcStart = clipStart.xyz.div( clipStart.w );
  32168. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  32169. // direction
  32170. const dir = ndcEnd.xy.sub( ndcStart.xy ).temp();
  32171. // account for clip-space aspect ratio
  32172. dir.x.assign( dir.x.mul( aspect ) );
  32173. dir.assign( dir.normalize() );
  32174. const clip = temp( vec4() );
  32175. if ( useWorldUnits ) {
  32176. // get the offset direction as perpendicular to the view vector
  32177. const worldDir = end.xyz.sub( start.xyz ).normalize();
  32178. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  32179. const worldUp = worldDir.cross( tmpFwd ).normalize();
  32180. const worldFwd = worldDir.cross( worldUp );
  32181. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  32182. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).cond( start, end ) );
  32183. // height offset
  32184. const hw = materialLineWidth.mul( 0.5 );
  32185. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).cond( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  32186. // don't extend the line if we're rendering dashes because we
  32187. // won't be rendering the endcaps
  32188. if ( ! useDash ) {
  32189. // cap extension
  32190. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).cond( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  32191. // add width to the box
  32192. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  32193. // endcaps
  32194. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  32195. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  32196. } );
  32197. }
  32198. // project the worldpos
  32199. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  32200. // shift the depth of the projected points so the line
  32201. // segments overlap neatly
  32202. const clipPose = temp( vec3() );
  32203. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).cond( ndcStart, ndcEnd ) );
  32204. clip.z.assign( clipPose.z.mul( clip.w ) );
  32205. } else {
  32206. const offset = property( 'vec2', 'offset' );
  32207. offset.assign( vec2( dir.y, dir.x.negate() ) );
  32208. // undo aspect ratio adjustment
  32209. dir.x.assign( dir.x.div( aspect ) );
  32210. offset.x.assign( offset.x.div( aspect ) );
  32211. // sign flip
  32212. offset.assign( positionGeometry.x.lessThan( 0.0 ).cond( offset.negate(), offset ) );
  32213. // endcaps
  32214. If( positionGeometry.y.lessThan( 0.0 ), () => {
  32215. offset.assign( offset.sub( dir ) );
  32216. } ).elseif( positionGeometry.y.greaterThan( 1.0 ), () => {
  32217. offset.assign( offset.add( dir ) );
  32218. } );
  32219. // adjust for linewidth
  32220. offset.assign( offset.mul( materialLineWidth ) );
  32221. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  32222. offset.assign( offset.div( viewport.w ) );
  32223. // select end
  32224. clip.assign( positionGeometry.y.lessThan( 0.5 ).cond( clipStart, clipEnd ) );
  32225. // back to clip space
  32226. offset.assign( offset.mul( clip.w ) );
  32227. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  32228. }
  32229. return clip;
  32230. } )();
  32231. const closestLineToLine = tslFn( ( { p1, p2, p3, p4 } ) => {
  32232. const p13 = p1.sub( p3 );
  32233. const p43 = p4.sub( p3 );
  32234. const p21 = p2.sub( p1 );
  32235. const d1343 = p13.dot( p43 );
  32236. const d4321 = p43.dot( p21 );
  32237. const d1321 = p13.dot( p21 );
  32238. const d4343 = p43.dot( p43 );
  32239. const d2121 = p21.dot( p21 );
  32240. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  32241. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  32242. const mua = numer.div( denom ).clamp();
  32243. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  32244. return vec2( mua, mub );
  32245. } );
  32246. this.fragmentNode = tslFn( () => {
  32247. const vUv = varyingProperty( 'vec2', 'vUv' );
  32248. if ( useDash ) {
  32249. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  32250. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  32251. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  32252. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  32253. dashSize.assign( dashSizeNode );
  32254. gapSize.assign( gapSizeNode );
  32255. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  32256. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  32257. const lineDistance = positionGeometry.y.lessThan( 0.5 ).cond( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  32258. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  32259. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  32260. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  32261. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  32262. }
  32263. // force assignment into correct place in flow
  32264. const alpha = property( 'float', 'alpha' );
  32265. alpha.assign( 1 );
  32266. if ( useWorldUnits ) {
  32267. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  32268. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  32269. // Find the closest points on the view ray and the line segment
  32270. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  32271. const lineDir = worldEnd.sub( worldStart );
  32272. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  32273. const p1 = worldStart.add( lineDir.mul( params.x ) );
  32274. const p2 = rayEnd.mul( params.y );
  32275. const delta = p1.sub( p2 );
  32276. const len = delta.length();
  32277. const norm = len.div( materialLineWidth );
  32278. if ( ! useDash ) {
  32279. if ( useAlphaToCoverage ) {
  32280. const dnorm = norm.fwidth();
  32281. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  32282. } else {
  32283. norm.greaterThan( 0.5 ).discard();
  32284. }
  32285. }
  32286. } else {
  32287. // round endcaps
  32288. if ( useAlphaToCoverage ) {
  32289. const a = vUv.x;
  32290. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32291. const len2 = a.mul( a ).add( b.mul( b ) );
  32292. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  32293. const dlen = property( 'float', 'dlen' );
  32294. dlen.assign( len2.fwidth() );
  32295. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32296. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  32297. } );
  32298. } else {
  32299. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32300. const a = vUv.x;
  32301. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32302. const len2 = a.mul( a ).add( b.mul( b ) );
  32303. len2.greaterThan( 1.0 ).discard();
  32304. } );
  32305. }
  32306. }
  32307. let lineColorNode;
  32308. if ( this.lineColorNode ) {
  32309. lineColorNode = this.lineColorNode;
  32310. } else {
  32311. if ( useColor ) {
  32312. const instanceColorStart = attribute( 'instanceColorStart' );
  32313. const instanceColorEnd = attribute( 'instanceColorEnd' );
  32314. const instanceColor = positionGeometry.y.lessThan( 0.5 ).cond( instanceColorStart, instanceColorEnd );
  32315. lineColorNode = instanceColor.mul( materialColor );
  32316. } else {
  32317. lineColorNode = materialColor;
  32318. }
  32319. }
  32320. return vec4( lineColorNode, alpha );
  32321. } )();
  32322. }
  32323. get worldUnits() {
  32324. return this.useWorldUnits;
  32325. }
  32326. set worldUnits( value ) {
  32327. if ( this.useWorldUnits !== value ) {
  32328. this.useWorldUnits = value;
  32329. this.needsUpdate = true;
  32330. }
  32331. }
  32332. get dashed() {
  32333. return this.useDash;
  32334. }
  32335. set dashed( value ) {
  32336. if ( this.useDash !== value ) {
  32337. this.useDash = value;
  32338. this.needsUpdate = true;
  32339. }
  32340. }
  32341. get alphaToCoverage() {
  32342. return this.useAlphaToCoverage;
  32343. }
  32344. set alphaToCoverage( value ) {
  32345. if ( this.useAlphaToCoverage !== value ) {
  32346. this.useAlphaToCoverage = value;
  32347. this.needsUpdate = true;
  32348. }
  32349. }
  32350. }
  32351. addNodeMaterial( 'Line2NodeMaterial', Line2NodeMaterial );
  32352. const defaultValues$a = new MeshNormalMaterial();
  32353. class MeshNormalNodeMaterial extends NodeMaterial {
  32354. constructor( parameters ) {
  32355. super();
  32356. this.lights = false;
  32357. this.isMeshNormalNodeMaterial = true;
  32358. this.setDefaultValues( defaultValues$a );
  32359. this.setValues( parameters );
  32360. }
  32361. setupDiffuseColor() {
  32362. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  32363. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  32364. }
  32365. }
  32366. addNodeMaterial( 'MeshNormalNodeMaterial', MeshNormalNodeMaterial );
  32367. class BasicLightingModel extends LightingModel {
  32368. constructor() {
  32369. super();
  32370. }
  32371. indirectDiffuse( { reflectedLight } ) {
  32372. reflectedLight.indirectDiffuse.assign( diffuseColor.rgb );
  32373. }
  32374. finish( context, stack, builder ) {
  32375. const material = builder.material;
  32376. const outgoingLight = context.outgoingLight;
  32377. const envNode = builder.context.environment;
  32378. if ( envNode ) {
  32379. switch ( material.combine ) {
  32380. case MultiplyOperation:
  32381. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  32382. break;
  32383. case MixOperation:
  32384. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  32385. break;
  32386. case AddOperation:
  32387. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  32388. break;
  32389. default:
  32390. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  32391. break;
  32392. }
  32393. }
  32394. }
  32395. }
  32396. const defaultValues$9 = new MeshBasicMaterial();
  32397. class MeshBasicNodeMaterial extends NodeMaterial {
  32398. constructor( parameters ) {
  32399. super();
  32400. this.isMeshBasicNodeMaterial = true;
  32401. this.lights = true;
  32402. //this.normals = false; @TODO: normals usage by context
  32403. this.setDefaultValues( defaultValues$9 );
  32404. this.setValues( parameters );
  32405. }
  32406. setupEnvironment( builder ) {
  32407. const envNode = super.setupEnvironment( builder );
  32408. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  32409. }
  32410. setupLightingModel() {
  32411. return new BasicLightingModel();
  32412. }
  32413. }
  32414. addNodeMaterial( 'MeshBasicNodeMaterial', MeshBasicNodeMaterial );
  32415. const F_Schlick = tslFn( ( { f0, f90, dotVH } ) => {
  32416. // Original approximation by Christophe Schlick '94
  32417. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  32418. // Optimized variant (presented by Epic at SIGGRAPH '13)
  32419. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  32420. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  32421. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  32422. } ); // validated
  32423. const BRDF_Lambert = tslFn( ( inputs ) => {
  32424. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  32425. } ); // validated
  32426. const G_BlinnPhong_Implicit = () => float( 0.25 );
  32427. const D_BlinnPhong = tslFn( ( { dotNH } ) => {
  32428. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  32429. } );
  32430. const BRDF_BlinnPhong = tslFn( ( { lightDirection } ) => {
  32431. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32432. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32433. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32434. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  32435. const G = G_BlinnPhong_Implicit();
  32436. const D = D_BlinnPhong( { dotNH } );
  32437. return F.mul( G ).mul( D );
  32438. } );
  32439. class PhongLightingModel extends BasicLightingModel {
  32440. constructor( specular = true ) {
  32441. super();
  32442. this.specular = specular;
  32443. }
  32444. direct( { lightDirection, lightColor, reflectedLight } ) {
  32445. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32446. const irradiance = dotNL.mul( lightColor );
  32447. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  32448. if ( this.specular === true ) {
  32449. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  32450. }
  32451. }
  32452. indirectDiffuse( { irradiance, reflectedLight } ) {
  32453. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  32454. }
  32455. }
  32456. const defaultValues$8 = new MeshLambertMaterial();
  32457. class MeshLambertNodeMaterial extends NodeMaterial {
  32458. constructor( parameters ) {
  32459. super();
  32460. this.isMeshLambertNodeMaterial = true;
  32461. this.lights = true;
  32462. this.setDefaultValues( defaultValues$8 );
  32463. this.setValues( parameters );
  32464. }
  32465. setupLightingModel( /*builder*/ ) {
  32466. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  32467. }
  32468. }
  32469. addNodeMaterial( 'MeshLambertNodeMaterial', MeshLambertNodeMaterial );
  32470. const defaultValues$7 = new MeshPhongMaterial();
  32471. class MeshPhongNodeMaterial extends NodeMaterial {
  32472. constructor( parameters ) {
  32473. super();
  32474. this.isMeshPhongNodeMaterial = true;
  32475. this.lights = true;
  32476. this.shininessNode = null;
  32477. this.specularNode = null;
  32478. this.setDefaultValues( defaultValues$7 );
  32479. this.setValues( parameters );
  32480. }
  32481. setupLightingModel( /*builder*/ ) {
  32482. return new PhongLightingModel();
  32483. }
  32484. setupVariants() {
  32485. // SHININESS
  32486. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  32487. shininess.assign( shininessNode );
  32488. // SPECULAR COLOR
  32489. const specularNode = this.specularNode || materialSpecular;
  32490. specularColor.assign( specularNode );
  32491. }
  32492. copy( source ) {
  32493. this.shininessNode = source.shininessNode;
  32494. this.specularNode = source.specularNode;
  32495. return super.copy( source );
  32496. }
  32497. }
  32498. addNodeMaterial( 'MeshPhongNodeMaterial', MeshPhongNodeMaterial );
  32499. const getGeometryRoughness = tslFn( () => {
  32500. const dxy = normalGeometry.dFdx().abs().max( normalGeometry.dFdy().abs() );
  32501. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  32502. return geometryRoughness;
  32503. } );
  32504. const getRoughness = tslFn( ( inputs ) => {
  32505. const { roughness } = inputs;
  32506. const geometryRoughness = getGeometryRoughness();
  32507. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  32508. roughnessFactor = roughnessFactor.add( geometryRoughness );
  32509. roughnessFactor = roughnessFactor.min( 1.0 );
  32510. return roughnessFactor;
  32511. } );
  32512. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  32513. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32514. const V_GGX_SmithCorrelated = tslFn( ( { alpha, dotNL, dotNV } ) => {
  32515. const a2 = alpha.pow2();
  32516. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  32517. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  32518. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  32519. } ).setLayout( {
  32520. name: 'V_GGX_SmithCorrelated',
  32521. type: 'float',
  32522. inputs: [
  32523. { name: 'alpha', type: 'float' },
  32524. { name: 'dotNL', type: 'float' },
  32525. { name: 'dotNV', type: 'float' }
  32526. ]
  32527. } ); // validated
  32528. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32529. const V_GGX_SmithCorrelated_Anisotropic = tslFn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  32530. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  32531. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  32532. const v = div( 0.5, gv.add( gl ) );
  32533. return v.saturate();
  32534. } ).setLayout( {
  32535. name: 'V_GGX_SmithCorrelated_Anisotropic',
  32536. type: 'float',
  32537. inputs: [
  32538. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32539. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32540. { name: 'dotTV', type: 'float', qualifier: 'in' },
  32541. { name: 'dotBV', type: 'float', qualifier: 'in' },
  32542. { name: 'dotTL', type: 'float', qualifier: 'in' },
  32543. { name: 'dotBL', type: 'float', qualifier: 'in' },
  32544. { name: 'dotNV', type: 'float', qualifier: 'in' },
  32545. { name: 'dotNL', type: 'float', qualifier: 'in' }
  32546. ]
  32547. } );
  32548. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  32549. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  32550. // alpha is "roughness squared" in Disney’s reparameterization
  32551. const D_GGX = tslFn( ( { alpha, dotNH } ) => {
  32552. const a2 = alpha.pow2();
  32553. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  32554. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  32555. } ).setLayout( {
  32556. name: 'D_GGX',
  32557. type: 'float',
  32558. inputs: [
  32559. { name: 'alpha', type: 'float' },
  32560. { name: 'dotNH', type: 'float' }
  32561. ]
  32562. } ); // validated
  32563. const RECIPROCAL_PI = float( 1 / Math.PI );
  32564. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32565. const D_GGX_Anisotropic = tslFn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  32566. const a2 = alphaT.mul( alphaB );
  32567. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  32568. const v2 = v.dot( v );
  32569. const w2 = a2.div( v2 );
  32570. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  32571. } ).setLayout( {
  32572. name: 'D_GGX_Anisotropic',
  32573. type: 'float',
  32574. inputs: [
  32575. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32576. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32577. { name: 'dotNH', type: 'float', qualifier: 'in' },
  32578. { name: 'dotTH', type: 'float', qualifier: 'in' },
  32579. { name: 'dotBH', type: 'float', qualifier: 'in' }
  32580. ]
  32581. } );
  32582. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  32583. const BRDF_GGX = tslFn( ( inputs ) => {
  32584. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  32585. const normalView = inputs.normalView || transformedNormalView;
  32586. const alpha = roughness.pow2(); // UE4's roughness
  32587. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32588. const dotNL = normalView.dot( lightDirection ).clamp();
  32589. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  32590. const dotNH = normalView.dot( halfDir ).clamp();
  32591. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32592. let F = F_Schlick( { f0, f90, dotVH } );
  32593. let V, D;
  32594. if ( defined( USE_IRIDESCENCE ) ) {
  32595. F = iridescence.mix( F, f );
  32596. }
  32597. if ( defined( USE_ANISOTROPY ) ) {
  32598. const dotTL = anisotropyT.dot( lightDirection );
  32599. const dotTV = anisotropyT.dot( positionViewDirection );
  32600. const dotTH = anisotropyT.dot( halfDir );
  32601. const dotBL = anisotropyB.dot( lightDirection );
  32602. const dotBV = anisotropyB.dot( positionViewDirection );
  32603. const dotBH = anisotropyB.dot( halfDir );
  32604. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  32605. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  32606. } else {
  32607. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  32608. D = D_GGX( { alpha, dotNH } );
  32609. }
  32610. return F.mul( V ).mul( D );
  32611. } ); // validated
  32612. // Analytical approximation of the DFG LUT, one half of the
  32613. // split-sum approximation used in indirect specular lighting.
  32614. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  32615. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  32616. const DFGApprox = tslFn( ( { roughness, dotNV } ) => {
  32617. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  32618. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  32619. const r = roughness.mul( c0 ).add( c1 );
  32620. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  32621. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  32622. return fab;
  32623. } ).setLayout( {
  32624. name: 'DFGApprox',
  32625. type: 'vec2',
  32626. inputs: [
  32627. { name: 'roughness', type: 'float' },
  32628. { name: 'dotNV', type: 'vec3' }
  32629. ]
  32630. } );
  32631. const EnvironmentBRDF = tslFn( ( inputs ) => {
  32632. const { dotNV, specularColor, specularF90, roughness } = inputs;
  32633. const fab = DFGApprox( { dotNV, roughness } );
  32634. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  32635. } );
  32636. const Schlick_to_F0 = tslFn( ( { f, f90, dotVH } ) => {
  32637. const x = dotVH.oneMinus().saturate();
  32638. const x2 = x.mul( x );
  32639. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  32640. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  32641. } ).setLayout( {
  32642. name: 'Schlick_to_F0',
  32643. type: 'vec3',
  32644. inputs: [
  32645. { name: 'f', type: 'vec3' },
  32646. { name: 'f90', type: 'float' },
  32647. { name: 'dotVH', type: 'float' }
  32648. ]
  32649. } );
  32650. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32651. const D_Charlie = tslFn( ( { roughness, dotNH } ) => {
  32652. const alpha = roughness.pow2();
  32653. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  32654. const invAlpha = float( 1.0 ).div( alpha );
  32655. const cos2h = dotNH.pow2();
  32656. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  32657. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  32658. } ).setLayout( {
  32659. name: 'D_Charlie',
  32660. type: 'float',
  32661. inputs: [
  32662. { name: 'roughness', type: 'float' },
  32663. { name: 'dotNH', type: 'float' }
  32664. ]
  32665. } );
  32666. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32667. const V_Neubelt = tslFn( ( { dotNV, dotNL } ) => {
  32668. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  32669. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  32670. } ).setLayout( {
  32671. name: 'V_Neubelt',
  32672. type: 'float',
  32673. inputs: [
  32674. { name: 'dotNV', type: 'float' },
  32675. { name: 'dotNL', type: 'float' }
  32676. ]
  32677. } );
  32678. const BRDF_Sheen = tslFn( ( { lightDirection } ) => {
  32679. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32680. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32681. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  32682. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32683. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  32684. const V = V_Neubelt( { dotNV, dotNL } );
  32685. return sheen.mul( D ).mul( V );
  32686. } );
  32687. // Rect Area Light
  32688. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  32689. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  32690. // code: https://github.com/selfshadow/ltc_code/
  32691. const LTC_Uv = tslFn( ( { N, V, roughness } ) => {
  32692. const LUT_SIZE = 64.0;
  32693. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  32694. const LUT_BIAS = 0.5 / LUT_SIZE;
  32695. const dotNV = N.dot( V ).saturate();
  32696. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  32697. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  32698. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  32699. return uv;
  32700. } ).setLayout( {
  32701. name: 'LTC_Uv',
  32702. type: 'vec2',
  32703. inputs: [
  32704. { name: 'N', type: 'vec3' },
  32705. { name: 'V', type: 'vec3' },
  32706. { name: 'roughness', type: 'float' }
  32707. ]
  32708. } );
  32709. const LTC_ClippedSphereFormFactor = tslFn( ( { f } ) => {
  32710. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  32711. // An approximation of the form factor of a horizon-clipped rectangle.
  32712. const l = f.length();
  32713. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  32714. } ).setLayout( {
  32715. name: 'LTC_ClippedSphereFormFactor',
  32716. type: 'float',
  32717. inputs: [
  32718. { name: 'f', type: 'vec3' }
  32719. ]
  32720. } );
  32721. const LTC_EdgeVectorFormFactor = tslFn( ( { v1, v2 } ) => {
  32722. const x = v1.dot( v2 );
  32723. const y = x.abs().toVar();
  32724. // rational polynomial approximation to theta / sin( theta ) / 2PI
  32725. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  32726. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  32727. const v = a.div( b );
  32728. const theta_sintheta = x.greaterThan( 0.0 ).cond( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  32729. return v1.cross( v2 ).mul( theta_sintheta );
  32730. } ).setLayout( {
  32731. name: 'LTC_EdgeVectorFormFactor',
  32732. type: 'vec3',
  32733. inputs: [
  32734. { name: 'v1', type: 'vec3' },
  32735. { name: 'v2', type: 'vec3' }
  32736. ]
  32737. } );
  32738. const LTC_Evaluate = tslFn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  32739. // bail if point is on back side of plane of light
  32740. // assumes ccw winding order of light vertices
  32741. const v1 = p1.sub( p0 ).toVar();
  32742. const v2 = p3.sub( p0 ).toVar();
  32743. const lightNormal = v1.cross( v2 );
  32744. const result = vec3().toVar();
  32745. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  32746. // construct orthonormal basis around N
  32747. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  32748. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  32749. // compute transform
  32750. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  32751. // transform rect
  32752. // & project rect onto sphere
  32753. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  32754. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  32755. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  32756. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  32757. // calculate vector form factor
  32758. const vectorFormFactor = vec3( 0 ).toVar();
  32759. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  32760. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  32761. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  32762. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  32763. // adjust for horizon clipping
  32764. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  32765. } );
  32766. return result;
  32767. } ).setLayout( {
  32768. name: 'LTC_Evaluate',
  32769. type: 'vec3',
  32770. inputs: [
  32771. { name: 'N', type: 'vec3' },
  32772. { name: 'V', type: 'vec3' },
  32773. { name: 'P', type: 'vec3' },
  32774. { name: 'mInv', type: 'mat3' },
  32775. { name: 'p0', type: 'vec3' },
  32776. { name: 'p1', type: 'vec3' },
  32777. { name: 'p2', type: 'vec3' },
  32778. { name: 'p3', type: 'vec3' }
  32779. ]
  32780. } );
  32781. //
  32782. // Transmission
  32783. //
  32784. const getVolumeTransmissionRay = tslFn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  32785. // Direction of refracted light.
  32786. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  32787. // Compute rotation-independant scaling of the model matrix.
  32788. const modelScale = vec3(
  32789. length( modelMatrix[ 0 ].xyz ),
  32790. length( modelMatrix[ 1 ].xyz ),
  32791. length( modelMatrix[ 2 ].xyz )
  32792. );
  32793. // The thickness is specified in local space.
  32794. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  32795. } ).setLayout( {
  32796. name: 'getVolumeTransmissionRay',
  32797. type: 'vec3',
  32798. inputs: [
  32799. { name: 'n', type: 'vec3' },
  32800. { name: 'v', type: 'vec3' },
  32801. { name: 'thickness', type: 'float' },
  32802. { name: 'ior', type: 'float' },
  32803. { name: 'modelMatrix', type: 'mat4' }
  32804. ]
  32805. } );
  32806. const applyIorToRoughness = tslFn( ( [ roughness, ior ] ) => {
  32807. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  32808. // an IOR of 1.5 results in the default amount of microfacet refraction.
  32809. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  32810. } ).setLayout( {
  32811. name: 'applyIorToRoughness',
  32812. type: 'float',
  32813. inputs: [
  32814. { name: 'roughness', type: 'float' },
  32815. { name: 'ior', type: 'float' }
  32816. ]
  32817. } );
  32818. const singleViewportMipTexture = viewportMipTexture();
  32819. const getTransmissionSample = tslFn( ( [ fragCoord, roughness, ior ] ) => {
  32820. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  32821. //const transmissionSample = viewportMipTexture( fragCoord );
  32822. const lod = log2( float( viewportResolution.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  32823. return transmissionSample.bicubic( lod );
  32824. } );
  32825. const volumeAttenuation = tslFn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  32826. If( attenuationDistance.notEqual( 0 ), () => {
  32827. // Compute light attenuation using Beer's law.
  32828. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  32829. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  32830. return transmittance;
  32831. } );
  32832. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  32833. return vec3( 1.0 );
  32834. } ).setLayout( {
  32835. name: 'volumeAttenuation',
  32836. type: 'vec3',
  32837. inputs: [
  32838. { name: 'transmissionDistance', type: 'float' },
  32839. { name: 'attenuationColor', type: 'vec3' },
  32840. { name: 'attenuationDistance', type: 'float' }
  32841. ]
  32842. } );
  32843. const getIBLVolumeRefraction = tslFn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  32844. let transmittedLight, transmittance;
  32845. if ( dispersion ) {
  32846. transmittedLight = vec4().toVar();
  32847. transmittance = vec3().toVar();
  32848. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  32849. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  32850. loop( { start: 0, end: 3 }, ( { i } ) => {
  32851. const ior = iors.element( i );
  32852. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  32853. const refractedRayExit = position.add( transmissionRay );
  32854. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  32855. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  32856. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  32857. refractionCoords.addAssign( 1.0 );
  32858. refractionCoords.divAssign( 2.0 );
  32859. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  32860. // Sample framebuffer to get pixel the refracted ray hits.
  32861. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  32862. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  32863. transmittedLight.a.addAssign( transmissionSample.a );
  32864. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  32865. } );
  32866. transmittedLight.a.divAssign( 3.0 );
  32867. } else {
  32868. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  32869. const refractedRayExit = position.add( transmissionRay );
  32870. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  32871. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  32872. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  32873. refractionCoords.addAssign( 1.0 );
  32874. refractionCoords.divAssign( 2.0 );
  32875. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  32876. // Sample framebuffer to get pixel the refracted ray hits.
  32877. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  32878. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  32879. }
  32880. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  32881. const dotNV = n.dot( v ).clamp();
  32882. // Get the specular component.
  32883. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  32884. dotNV,
  32885. specularColor,
  32886. specularF90,
  32887. roughness
  32888. } ) );
  32889. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  32890. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  32891. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  32892. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  32893. } );
  32894. //
  32895. // Iridescence
  32896. //
  32897. // XYZ to linear-sRGB color space
  32898. const XYZ_TO_REC709 = mat3(
  32899. 3.2404542, - 0.9692660, 0.0556434,
  32900. - 1.5371385, 1.8760108, - 0.2040259,
  32901. - 0.4985314, 0.0415560, 1.0572252
  32902. );
  32903. // Assume air interface for top
  32904. // Note: We don't handle the case fresnel0 == 1
  32905. const Fresnel0ToIor = ( fresnel0 ) => {
  32906. const sqrtF0 = fresnel0.sqrt();
  32907. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  32908. };
  32909. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  32910. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  32911. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  32912. };
  32913. // Fresnel equations for dielectric/dielectric interfaces.
  32914. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  32915. // Evaluation XYZ sensitivity curves in Fourier space
  32916. const evalSensitivity = ( OPD, shift ) => {
  32917. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  32918. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  32919. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  32920. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  32921. 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() );
  32922. 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() );
  32923. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  32924. const rgb = XYZ_TO_REC709.mul( xyz );
  32925. return rgb;
  32926. };
  32927. const evalIridescence = tslFn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  32928. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  32929. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  32930. // Evaluate the cosTheta on the base layer (Snell law)
  32931. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  32932. // Handle TIR:
  32933. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  32934. /*if ( cosTheta2Sq < 0.0 ) {
  32935. return vec3( 1.0 );
  32936. }*/
  32937. const cosTheta2 = cosTheta2Sq.sqrt();
  32938. // First interface
  32939. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  32940. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  32941. //const R21 = R12;
  32942. const T121 = R12.oneMinus();
  32943. const phi12 = iridescenceIOR.lessThan( outsideIOR ).cond( Math.PI, 0.0 );
  32944. const phi21 = float( Math.PI ).sub( phi12 );
  32945. // Second interface
  32946. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  32947. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  32948. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  32949. const phi23 = vec3(
  32950. baseIOR.x.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  32951. baseIOR.y.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  32952. baseIOR.z.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 )
  32953. );
  32954. // Phase shift
  32955. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  32956. const phi = vec3( phi21 ).add( phi23 );
  32957. // Compound terms
  32958. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  32959. const r123 = R123.sqrt();
  32960. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  32961. // Reflectance term for m = 0 (DC term amplitude)
  32962. const C0 = R12.add( Rs );
  32963. let I = C0;
  32964. // Reflectance term for m > 0 (pairs of diracs)
  32965. let Cm = Rs.sub( T121 );
  32966. for ( let m = 1; m <= 2; ++ m ) {
  32967. Cm = Cm.mul( r123 );
  32968. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  32969. I = I.add( Cm.mul( Sm ) );
  32970. }
  32971. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  32972. return I.max( vec3( 0.0 ) );
  32973. } ).setLayout( {
  32974. name: 'evalIridescence',
  32975. type: 'vec3',
  32976. inputs: [
  32977. { name: 'outsideIOR', type: 'float' },
  32978. { name: 'eta2', type: 'float' },
  32979. { name: 'cosTheta1', type: 'float' },
  32980. { name: 'thinFilmThickness', type: 'float' },
  32981. { name: 'baseF0', type: 'vec3' }
  32982. ]
  32983. } );
  32984. //
  32985. // Sheen
  32986. //
  32987. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  32988. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  32989. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  32990. const IBLSheenBRDF = tslFn( ( { normal, viewDir, roughness } ) => {
  32991. const dotNV = normal.dot( viewDir ).saturate();
  32992. const r2 = roughness.pow2();
  32993. const a = cond(
  32994. roughness.lessThan( 0.25 ),
  32995. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  32996. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  32997. );
  32998. const b = cond(
  32999. roughness.lessThan( 0.25 ),
  33000. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  33001. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  33002. );
  33003. const DG = cond( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  33004. return DG.mul( 1.0 / Math.PI ).saturate();
  33005. } );
  33006. const clearcoatF0 = vec3( 0.04 );
  33007. const clearcoatF90 = float( 1 );
  33008. //
  33009. class PhysicalLightingModel extends LightingModel {
  33010. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  33011. super();
  33012. this.clearcoat = clearcoat;
  33013. this.sheen = sheen;
  33014. this.iridescence = iridescence;
  33015. this.anisotropy = anisotropy;
  33016. this.transmission = transmission;
  33017. this.dispersion = dispersion;
  33018. this.clearcoatRadiance = null;
  33019. this.clearcoatSpecularDirect = null;
  33020. this.clearcoatSpecularIndirect = null;
  33021. this.sheenSpecularDirect = null;
  33022. this.sheenSpecularIndirect = null;
  33023. this.iridescenceFresnel = null;
  33024. this.iridescenceF0 = null;
  33025. }
  33026. start( context ) {
  33027. if ( this.clearcoat === true ) {
  33028. this.clearcoatRadiance = vec3().temp( 'clearcoatRadiance' );
  33029. this.clearcoatSpecularDirect = vec3().temp( 'clearcoatSpecularDirect' );
  33030. this.clearcoatSpecularIndirect = vec3().temp( 'clearcoatSpecularIndirect' );
  33031. }
  33032. if ( this.sheen === true ) {
  33033. this.sheenSpecularDirect = vec3().temp( 'sheenSpecularDirect' );
  33034. this.sheenSpecularIndirect = vec3().temp( 'sheenSpecularIndirect' );
  33035. }
  33036. if ( this.iridescence === true ) {
  33037. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  33038. this.iridescenceFresnel = evalIridescence( {
  33039. outsideIOR: float( 1.0 ),
  33040. eta2: iridescenceIOR,
  33041. cosTheta1: dotNVi,
  33042. thinFilmThickness: iridescenceThickness,
  33043. baseF0: specularColor
  33044. } );
  33045. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  33046. }
  33047. if ( this.transmission === true ) {
  33048. const position = positionWorld;
  33049. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  33050. const n = transformedNormalWorld;
  33051. context.backdrop = getIBLVolumeRefraction(
  33052. n,
  33053. v,
  33054. roughness,
  33055. diffuseColor,
  33056. specularColor,
  33057. specularF90, // specularF90
  33058. position, // positionWorld
  33059. modelWorldMatrix, // modelMatrix
  33060. cameraViewMatrix, // viewMatrix
  33061. cameraProjectionMatrix, // projMatrix
  33062. ior,
  33063. thickness,
  33064. attenuationColor,
  33065. attenuationDistance,
  33066. this.dispersion ? dispersion : null
  33067. );
  33068. context.backdropAlpha = transmission;
  33069. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  33070. }
  33071. }
  33072. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  33073. // Approximates multiscattering in order to preserve energy.
  33074. // http://www.jcgt.org/published/0008/01/03/
  33075. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  33076. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  33077. const fab = DFGApprox( { roughness, dotNV } );
  33078. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  33079. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  33080. const Ess = fab.x.add( fab.y );
  33081. const Ems = Ess.oneMinus();
  33082. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  33083. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  33084. singleScatter.addAssign( FssEss );
  33085. multiScatter.addAssign( Fms.mul( Ems ) );
  33086. }
  33087. direct( { lightDirection, lightColor, reflectedLight } ) {
  33088. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  33089. const irradiance = dotNL.mul( lightColor );
  33090. if ( this.sheen === true ) {
  33091. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  33092. }
  33093. if ( this.clearcoat === true ) {
  33094. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  33095. const ccIrradiance = dotNLcc.mul( lightColor );
  33096. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  33097. }
  33098. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33099. 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 } ) ) );
  33100. }
  33101. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  33102. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  33103. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  33104. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  33105. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  33106. const N = transformedNormalView;
  33107. const V = positionViewDirection;
  33108. const P = positionView.toVar();
  33109. const uv = LTC_Uv( { N, V, roughness } );
  33110. const t1 = ltc_1.uv( uv ).toVar();
  33111. const t2 = ltc_2.uv( uv ).toVar();
  33112. const mInv = mat3(
  33113. vec3( t1.x, 0, t1.y ),
  33114. vec3( 0, 1, 0 ),
  33115. vec3( t1.z, 0, t1.w )
  33116. ).toVar();
  33117. // LTC Fresnel Approximation by Stephen Hill
  33118. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  33119. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  33120. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  33121. 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 } ) ) );
  33122. }
  33123. indirectDiffuse( { irradiance, reflectedLight } ) {
  33124. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33125. }
  33126. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  33127. if ( this.sheen === true ) {
  33128. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  33129. sheen,
  33130. IBLSheenBRDF( {
  33131. normal: transformedNormalView,
  33132. viewDir: positionViewDirection,
  33133. roughness: sheenRoughness
  33134. } )
  33135. ) );
  33136. }
  33137. if ( this.clearcoat === true ) {
  33138. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  33139. const clearcoatEnv = EnvironmentBRDF( {
  33140. dotNV: dotNVcc,
  33141. specularColor: clearcoatF0,
  33142. specularF90: clearcoatF90,
  33143. roughness: clearcoatRoughness
  33144. } );
  33145. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  33146. }
  33147. // Both indirect specular and indirect diffuse light accumulate here
  33148. const singleScattering = vec3().temp( 'singleScattering' );
  33149. const multiScattering = vec3().temp( 'multiScattering' );
  33150. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  33151. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  33152. const totalScattering = singleScattering.add( multiScattering );
  33153. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  33154. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  33155. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  33156. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  33157. }
  33158. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  33159. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  33160. const aoNV = dotNV.add( ambientOcclusion );
  33161. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  33162. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  33163. if ( this.clearcoat === true ) {
  33164. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  33165. }
  33166. if ( this.sheen === true ) {
  33167. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  33168. }
  33169. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33170. reflectedLight.indirectSpecular.mulAssign( aoNode );
  33171. }
  33172. finish( context ) {
  33173. const { outgoingLight } = context;
  33174. if ( this.clearcoat === true ) {
  33175. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  33176. const Fcc = F_Schlick( {
  33177. dotVH: dotNVcc,
  33178. f0: clearcoatF0,
  33179. f90: clearcoatF90
  33180. } );
  33181. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  33182. outgoingLight.assign( clearcoatLight );
  33183. }
  33184. if ( this.sheen === true ) {
  33185. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  33186. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  33187. outgoingLight.assign( sheenLight );
  33188. }
  33189. }
  33190. }
  33191. const defaultValues$6 = new MeshStandardMaterial();
  33192. class MeshStandardNodeMaterial extends NodeMaterial {
  33193. constructor( parameters ) {
  33194. super();
  33195. this.isMeshStandardNodeMaterial = true;
  33196. this.emissiveNode = null;
  33197. this.metalnessNode = null;
  33198. this.roughnessNode = null;
  33199. this.setDefaultValues( defaultValues$6 );
  33200. this.setValues( parameters );
  33201. }
  33202. setupEnvironment( builder ) {
  33203. const envNode = super.setupEnvironment( builder );
  33204. return envNode ? new EnvironmentNode( envNode ) : null;
  33205. }
  33206. setupLightingModel( /*builder*/ ) {
  33207. return new PhysicalLightingModel();
  33208. }
  33209. setupSpecular() {
  33210. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  33211. specularColor.assign( specularColorNode );
  33212. specularF90.assign( 1.0 );
  33213. }
  33214. setupVariants() {
  33215. // METALNESS
  33216. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  33217. metalness.assign( metalnessNode );
  33218. // ROUGHNESS
  33219. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  33220. roughnessNode = getRoughness( { roughness: roughnessNode } );
  33221. roughness.assign( roughnessNode );
  33222. // SPECULAR COLOR
  33223. this.setupSpecular();
  33224. // DIFFUSE COLOR
  33225. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  33226. }
  33227. copy( source ) {
  33228. this.emissiveNode = source.emissiveNode;
  33229. this.metalnessNode = source.metalnessNode;
  33230. this.roughnessNode = source.roughnessNode;
  33231. return super.copy( source );
  33232. }
  33233. }
  33234. addNodeMaterial( 'MeshStandardNodeMaterial', MeshStandardNodeMaterial );
  33235. const defaultValues$5 = new MeshPhysicalMaterial();
  33236. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  33237. constructor( parameters ) {
  33238. super();
  33239. this.isMeshPhysicalNodeMaterial = true;
  33240. this.clearcoatNode = null;
  33241. this.clearcoatRoughnessNode = null;
  33242. this.clearcoatNormalNode = null;
  33243. this.sheenNode = null;
  33244. this.sheenRoughnessNode = null;
  33245. this.iridescenceNode = null;
  33246. this.iridescenceIORNode = null;
  33247. this.iridescenceThicknessNode = null;
  33248. this.specularIntensityNode = null;
  33249. this.specularColorNode = null;
  33250. this.iorNode = null;
  33251. this.transmissionNode = null;
  33252. this.thicknessNode = null;
  33253. this.attenuationDistanceNode = null;
  33254. this.attenuationColorNode = null;
  33255. this.dispersionNode = null;
  33256. this.anisotropyNode = null;
  33257. this.setDefaultValues( defaultValues$5 );
  33258. this.setValues( parameters );
  33259. }
  33260. get useClearcoat() {
  33261. return this.clearcoat > 0 || this.clearcoatNode !== null;
  33262. }
  33263. get useIridescence() {
  33264. return this.iridescence > 0 || this.iridescenceNode !== null;
  33265. }
  33266. get useSheen() {
  33267. return this.sheen > 0 || this.sheenNode !== null;
  33268. }
  33269. get useAnisotropy() {
  33270. return this.anisotropy > 0 || this.anisotropyNode !== null;
  33271. }
  33272. get useTransmission() {
  33273. return this.transmission > 0 || this.transmissionNode !== null;
  33274. }
  33275. get useDispersion() {
  33276. return this.dispersion > 0 || this.dispersionNode !== null;
  33277. }
  33278. setupSpecular() {
  33279. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  33280. ior.assign( iorNode );
  33281. 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 ) );
  33282. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  33283. }
  33284. setupLightingModel( /*builder*/ ) {
  33285. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  33286. }
  33287. setupVariants( builder ) {
  33288. super.setupVariants( builder );
  33289. // CLEARCOAT
  33290. if ( this.useClearcoat ) {
  33291. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  33292. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  33293. clearcoat.assign( clearcoatNode );
  33294. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  33295. }
  33296. // SHEEN
  33297. if ( this.useSheen ) {
  33298. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  33299. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  33300. sheen.assign( sheenNode );
  33301. sheenRoughness.assign( sheenRoughnessNode );
  33302. }
  33303. // IRIDESCENCE
  33304. if ( this.useIridescence ) {
  33305. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  33306. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  33307. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  33308. iridescence.assign( iridescenceNode );
  33309. iridescenceIOR.assign( iridescenceIORNode );
  33310. iridescenceThickness.assign( iridescenceThicknessNode );
  33311. }
  33312. // ANISOTROPY
  33313. if ( this.useAnisotropy ) {
  33314. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  33315. anisotropy.assign( anisotropyV.length() );
  33316. If( anisotropy.equal( 0.0 ), () => {
  33317. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  33318. } ).else( () => {
  33319. anisotropyV.divAssign( vec2( anisotropy ) );
  33320. anisotropy.assign( anisotropy.saturate() );
  33321. } );
  33322. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  33323. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  33324. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  33325. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  33326. }
  33327. // TRANSMISSION
  33328. if ( this.useTransmission ) {
  33329. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  33330. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  33331. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  33332. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  33333. transmission.assign( transmissionNode );
  33334. thickness.assign( thicknessNode );
  33335. attenuationDistance.assign( attenuationDistanceNode );
  33336. attenuationColor.assign( attenuationColorNode );
  33337. if ( this.useDispersion ) {
  33338. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  33339. dispersion.assign( dispersionNode );
  33340. }
  33341. }
  33342. }
  33343. setupNormal( builder ) {
  33344. super.setupNormal( builder );
  33345. // CLEARCOAT NORMAL
  33346. const clearcoatNormalNode = this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  33347. transformedClearcoatNormalView.assign( clearcoatNormalNode );
  33348. }
  33349. copy( source ) {
  33350. this.clearcoatNode = source.clearcoatNode;
  33351. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  33352. this.clearcoatNormalNode = source.clearcoatNormalNode;
  33353. this.sheenNode = source.sheenNode;
  33354. this.sheenRoughnessNode = source.sheenRoughnessNode;
  33355. this.iridescenceNode = source.iridescenceNode;
  33356. this.iridescenceIORNode = source.iridescenceIORNode;
  33357. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  33358. this.specularIntensityNode = source.specularIntensityNode;
  33359. this.specularColorNode = source.specularColorNode;
  33360. this.transmissionNode = source.transmissionNode;
  33361. this.thicknessNode = source.thicknessNode;
  33362. this.attenuationDistanceNode = source.attenuationDistanceNode;
  33363. this.attenuationColorNode = source.attenuationColorNode;
  33364. this.dispersionNode = source.dispersionNode;
  33365. this.anisotropyNode = source.anisotropyNode;
  33366. return super.copy( source );
  33367. }
  33368. }
  33369. addNodeMaterial( 'MeshPhysicalNodeMaterial', MeshPhysicalNodeMaterial );
  33370. class SSSLightingModel extends PhysicalLightingModel {
  33371. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  33372. super( useClearcoat, useSheen, useIridescence );
  33373. this.useSSS = useSSS;
  33374. }
  33375. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33376. if ( this.useSSS === true ) {
  33377. const material = builder.material;
  33378. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  33379. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  33380. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  33381. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  33382. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  33383. }
  33384. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  33385. }
  33386. }
  33387. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  33388. constructor( parameters ) {
  33389. super( parameters );
  33390. this.thicknessColorNode = null;
  33391. this.thicknessDistortionNode = float( 0.1 );
  33392. this.thicknessAmbientNode = float( 0.0 );
  33393. this.thicknessAttenuationNode = float( .1 );
  33394. this.thicknessPowerNode = float( 2.0 );
  33395. this.thicknessScaleNode = float( 10.0 );
  33396. }
  33397. get useSSS() {
  33398. return this.thicknessColorNode !== null;
  33399. }
  33400. setupLightingModel( /*builder*/ ) {
  33401. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  33402. }
  33403. copy( source ) {
  33404. this.thicknessColorNode = source.thicknessColorNode;
  33405. this.thicknessDistortionNode = source.thicknessDistortionNode;
  33406. this.thicknessAmbientNode = source.thicknessAmbientNode;
  33407. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  33408. this.thicknessPowerNode = source.thicknessPowerNode;
  33409. this.thicknessScaleNode = source.thicknessScaleNode;
  33410. return super.copy( source );
  33411. }
  33412. }
  33413. addNodeMaterial( 'MeshSSSNodeMaterial', MeshSSSNodeMaterial );
  33414. const getGradientIrradiance = tslFn( ( { normal, lightDirection, builder } ) => {
  33415. // dotNL will be from -1.0 to 1.0
  33416. const dotNL = normal.dot( lightDirection );
  33417. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  33418. if ( builder.material.gradientMap ) {
  33419. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  33420. return vec3( gradientMap.r );
  33421. } else {
  33422. const fw = coord.fwidth().mul( 0.5 );
  33423. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  33424. }
  33425. } );
  33426. class ToonLightingModel extends LightingModel {
  33427. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33428. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  33429. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33430. }
  33431. indirectDiffuse( { irradiance, reflectedLight } ) {
  33432. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33433. }
  33434. }
  33435. const defaultValues$4 = new MeshToonMaterial();
  33436. class MeshToonNodeMaterial extends NodeMaterial {
  33437. constructor( parameters ) {
  33438. super();
  33439. this.isMeshToonNodeMaterial = true;
  33440. this.lights = true;
  33441. this.setDefaultValues( defaultValues$4 );
  33442. this.setValues( parameters );
  33443. }
  33444. setupLightingModel( /*builder*/ ) {
  33445. return new ToonLightingModel();
  33446. }
  33447. }
  33448. addNodeMaterial( 'MeshToonNodeMaterial', MeshToonNodeMaterial );
  33449. const defaultValues$3 = new MeshMatcapMaterial();
  33450. class MeshMatcapNodeMaterial extends NodeMaterial {
  33451. constructor( parameters ) {
  33452. super();
  33453. this.lights = false;
  33454. this.isMeshMatcapNodeMaterial = true;
  33455. this.setDefaultValues( defaultValues$3 );
  33456. this.setValues( parameters );
  33457. }
  33458. setupVariants( builder ) {
  33459. const uv = matcapUV;
  33460. let matcapColor;
  33461. if ( builder.material.matcap ) {
  33462. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  33463. } else {
  33464. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  33465. }
  33466. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  33467. }
  33468. }
  33469. addNodeMaterial( 'MeshMatcapNodeMaterial', MeshMatcapNodeMaterial );
  33470. const defaultValues$2 = new PointsMaterial();
  33471. class PointsNodeMaterial extends NodeMaterial {
  33472. constructor( parameters ) {
  33473. super();
  33474. this.isPointsNodeMaterial = true;
  33475. this.lights = false;
  33476. this.normals = false;
  33477. this.transparent = true;
  33478. this.sizeNode = null;
  33479. this.setDefaultValues( defaultValues$2 );
  33480. this.setValues( parameters );
  33481. }
  33482. copy( source ) {
  33483. this.sizeNode = source.sizeNode;
  33484. return super.copy( source );
  33485. }
  33486. }
  33487. addNodeMaterial( 'PointsNodeMaterial', PointsNodeMaterial );
  33488. const defaultValues$1 = new SpriteMaterial();
  33489. class SpriteNodeMaterial extends NodeMaterial {
  33490. constructor( parameters ) {
  33491. super();
  33492. this.isSpriteNodeMaterial = true;
  33493. this.lights = false;
  33494. this.normals = false;
  33495. this.positionNode = null;
  33496. this.rotationNode = null;
  33497. this.scaleNode = null;
  33498. this.setDefaultValues( defaultValues$1 );
  33499. this.setValues( parameters );
  33500. }
  33501. setupPosition( { object, context } ) {
  33502. // < VERTEX STAGE >
  33503. const { positionNode, rotationNode, scaleNode } = this;
  33504. const vertex = positionLocal;
  33505. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  33506. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  33507. if ( scaleNode !== null ) {
  33508. scale = scale.mul( scaleNode );
  33509. }
  33510. let alignedPosition = vertex.xy;
  33511. if ( object.center && object.center.isVector2 === true ) {
  33512. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  33513. }
  33514. alignedPosition = alignedPosition.mul( scale );
  33515. const rotation = float( rotationNode || materialRotation );
  33516. const rotatedPosition = alignedPosition.rotate( rotation );
  33517. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  33518. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  33519. context.vertex = vertex;
  33520. return modelViewProjection;
  33521. }
  33522. copy( source ) {
  33523. this.positionNode = source.positionNode;
  33524. this.rotationNode = source.rotationNode;
  33525. this.scaleNode = source.scaleNode;
  33526. return super.copy( source );
  33527. }
  33528. }
  33529. addNodeMaterial( 'SpriteNodeMaterial', SpriteNodeMaterial );
  33530. class ShadowMaskModel extends LightingModel {
  33531. constructor() {
  33532. super();
  33533. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  33534. }
  33535. direct( { shadowMask } ) {
  33536. this.shadowNode.mulAssign( shadowMask );
  33537. }
  33538. finish( context ) {
  33539. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  33540. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  33541. }
  33542. }
  33543. const defaultValues = new ShadowMaterial();
  33544. class ShadowNodeMaterial extends NodeMaterial {
  33545. constructor( parameters ) {
  33546. super();
  33547. this.isShadowNodeMaterial = true;
  33548. this.lights = true;
  33549. this.setDefaultValues( defaultValues );
  33550. this.setValues( parameters );
  33551. }
  33552. setupLightingModel( /*builder*/ ) {
  33553. return new ShadowMaskModel();
  33554. }
  33555. }
  33556. addNodeMaterial( 'ShadowNodeMaterial', ShadowNodeMaterial );
  33557. class VolumeNodeMaterial extends NodeMaterial {
  33558. constructor( params = {} ) {
  33559. super();
  33560. this.normals = false;
  33561. this.lights = false;
  33562. this.isVolumeNodeMaterial = true;
  33563. this.testNode = null;
  33564. this.setValues( params );
  33565. }
  33566. setup( builder ) {
  33567. const map = texture3D( this.map, null, 0 );
  33568. const hitBox = tslFn( ( { orig, dir } ) => {
  33569. const box_min = vec3( - 0.5 );
  33570. const box_max = vec3( 0.5 );
  33571. const inv_dir = dir.reciprocal();
  33572. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  33573. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  33574. const tmin = min$1( tmin_tmp, tmax_tmp );
  33575. const tmax = max$1( tmin_tmp, tmax_tmp );
  33576. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  33577. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  33578. return vec2( t0, t1 );
  33579. } );
  33580. this.fragmentNode = tslFn( () => {
  33581. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  33582. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  33583. const rayDir = vDirection.normalize();
  33584. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  33585. bounds.x.greaterThan( bounds.y ).discard();
  33586. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  33587. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  33588. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  33589. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  33590. delta.divAssign( materialReference( 'steps', 'float' ) );
  33591. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  33592. loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  33593. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  33594. if ( this.testNode !== null ) {
  33595. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  33596. } else {
  33597. // default to show surface of mesh
  33598. ac.a.assign( 1 );
  33599. Break();
  33600. }
  33601. p.addAssign( rayDir.mul( delta ) );
  33602. } );
  33603. ac.a.equal( 0 ).discard();
  33604. return vec4( ac );
  33605. } )();
  33606. super.setup( builder );
  33607. }
  33608. }
  33609. addNodeMaterial( 'VolumeNodeMaterial', VolumeNodeMaterial );
  33610. const superFromTypeFunction = MaterialLoader.createMaterialFromType;
  33611. MaterialLoader.createMaterialFromType = function ( type ) {
  33612. const material = createNodeMaterialFromType( type );
  33613. if ( material !== undefined ) {
  33614. return material;
  33615. }
  33616. return superFromTypeFunction.call( this, type );
  33617. };
  33618. class NodeMaterialLoader extends MaterialLoader {
  33619. constructor( manager ) {
  33620. super( manager );
  33621. this.nodes = {};
  33622. }
  33623. parse( json ) {
  33624. const material = super.parse( json );
  33625. const nodes = this.nodes;
  33626. const inputNodes = json.inputNodes;
  33627. for ( const property in inputNodes ) {
  33628. const uuid = inputNodes[ property ];
  33629. material[ property ] = nodes[ uuid ];
  33630. }
  33631. return material;
  33632. }
  33633. setNodes( value ) {
  33634. this.nodes = value;
  33635. return this;
  33636. }
  33637. }
  33638. class NodeObjectLoader extends ObjectLoader {
  33639. constructor( manager ) {
  33640. super( manager );
  33641. this._nodesJSON = null;
  33642. }
  33643. parse( json, onLoad ) {
  33644. this._nodesJSON = json.nodes;
  33645. const data = super.parse( json, onLoad );
  33646. this._nodesJSON = null; // dispose
  33647. return data;
  33648. }
  33649. parseNodes( json, textures ) {
  33650. if ( json !== undefined ) {
  33651. const loader = new NodeLoader();
  33652. loader.setTextures( textures );
  33653. return loader.parseNodes( json );
  33654. }
  33655. return {};
  33656. }
  33657. parseMaterials( json, textures ) {
  33658. const materials = {};
  33659. if ( json !== undefined ) {
  33660. const nodes = this.parseNodes( this._nodesJSON, textures );
  33661. const loader = new NodeMaterialLoader();
  33662. loader.setTextures( textures );
  33663. loader.setNodes( nodes );
  33664. for ( let i = 0, l = json.length; i < l; i ++ ) {
  33665. const data = json[ i ];
  33666. materials[ data.uuid ] = loader.parse( data );
  33667. }
  33668. }
  33669. return materials;
  33670. }
  33671. }
  33672. class NodeParser {
  33673. parseFunction( /*source*/ ) {
  33674. console.warn( 'Abstract function.' );
  33675. }
  33676. }
  33677. class NodeFunction {
  33678. constructor( type, inputs, name = '', precision = '' ) {
  33679. this.type = type;
  33680. this.inputs = inputs;
  33681. this.name = name;
  33682. this.precision = precision;
  33683. }
  33684. getCode( /*name = this.name*/ ) {
  33685. console.warn( 'Abstract function.' );
  33686. }
  33687. }
  33688. NodeFunction.isNodeFunction = true;
  33689. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  33690. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  33691. const pragmaMain = '#pragma main';
  33692. const parse$1 = ( source ) => {
  33693. source = source.trim();
  33694. const pragmaMainIndex = source.indexOf( pragmaMain );
  33695. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  33696. const declaration = mainCode.match( declarationRegexp$1 );
  33697. if ( declaration !== null && declaration.length === 5 ) {
  33698. // tokenizer
  33699. const inputsCode = declaration[ 4 ];
  33700. const propsMatches = [];
  33701. let nameMatch = null;
  33702. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  33703. propsMatches.push( nameMatch );
  33704. }
  33705. // parser
  33706. const inputs = [];
  33707. let i = 0;
  33708. while ( i < propsMatches.length ) {
  33709. const isConst = propsMatches[ i ][ 0 ] === 'const';
  33710. if ( isConst === true ) {
  33711. i ++;
  33712. }
  33713. let qualifier = propsMatches[ i ][ 0 ];
  33714. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  33715. i ++;
  33716. } else {
  33717. qualifier = '';
  33718. }
  33719. const type = propsMatches[ i ++ ][ 0 ];
  33720. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  33721. if ( Number.isNaN( count ) === false ) i ++;
  33722. else count = null;
  33723. const name = propsMatches[ i ++ ][ 0 ];
  33724. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  33725. }
  33726. //
  33727. const blockCode = mainCode.substring( declaration[ 0 ].length );
  33728. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  33729. const type = declaration[ 2 ];
  33730. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  33731. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  33732. return {
  33733. type,
  33734. inputs,
  33735. name,
  33736. precision,
  33737. inputsCode,
  33738. blockCode,
  33739. headerCode
  33740. };
  33741. } else {
  33742. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  33743. }
  33744. };
  33745. class GLSLNodeFunction extends NodeFunction {
  33746. constructor( source ) {
  33747. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  33748. super( type, inputs, name, precision );
  33749. this.inputsCode = inputsCode;
  33750. this.blockCode = blockCode;
  33751. this.headerCode = headerCode;
  33752. }
  33753. getCode( name = this.name ) {
  33754. let code;
  33755. const blockCode = this.blockCode;
  33756. if ( blockCode !== '' ) {
  33757. const { type, inputsCode, headerCode, precision } = this;
  33758. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  33759. if ( precision !== '' ) {
  33760. declarationCode = `${ precision } ${ declarationCode }`;
  33761. }
  33762. code = headerCode + declarationCode + blockCode;
  33763. } else {
  33764. // interface function
  33765. code = '';
  33766. }
  33767. return code;
  33768. }
  33769. }
  33770. class GLSLNodeParser extends NodeParser {
  33771. parseFunction( source ) {
  33772. return new GLSLNodeFunction( source );
  33773. }
  33774. }
  33775. // Three.js Transpiler
  33776. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33777. const mx_select = /*#__PURE__*/ tslFn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33778. const f = float( f_immutable ).toVar();
  33779. const t = float( t_immutable ).toVar();
  33780. const b = bool( b_immutable ).toVar();
  33781. return cond( b, t, f );
  33782. } ).setLayout( {
  33783. name: 'mx_select',
  33784. type: 'float',
  33785. inputs: [
  33786. { name: 'b', type: 'bool' },
  33787. { name: 't', type: 'float' },
  33788. { name: 'f', type: 'float' }
  33789. ]
  33790. } );
  33791. const mx_negate_if = /*#__PURE__*/ tslFn( ( [ val_immutable, b_immutable ] ) => {
  33792. const b = bool( b_immutable ).toVar();
  33793. const val = float( val_immutable ).toVar();
  33794. return cond( b, val.negate(), val );
  33795. } ).setLayout( {
  33796. name: 'mx_negate_if',
  33797. type: 'float',
  33798. inputs: [
  33799. { name: 'val', type: 'float' },
  33800. { name: 'b', type: 'bool' }
  33801. ]
  33802. } );
  33803. const mx_floor = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  33804. const x = float( x_immutable ).toVar();
  33805. return int( floor( x ) );
  33806. } ).setLayout( {
  33807. name: 'mx_floor',
  33808. type: 'int',
  33809. inputs: [
  33810. { name: 'x', type: 'float' }
  33811. ]
  33812. } );
  33813. const mx_floorfrac = /*#__PURE__*/ tslFn( ( [ x_immutable, i ] ) => {
  33814. const x = float( x_immutable ).toVar();
  33815. i.assign( mx_floor( x ) );
  33816. return x.sub( float( i ) );
  33817. } );
  33818. const mx_bilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33819. const t = float( t_immutable ).toVar();
  33820. const s = float( s_immutable ).toVar();
  33821. const v3 = float( v3_immutable ).toVar();
  33822. const v2 = float( v2_immutable ).toVar();
  33823. const v1 = float( v1_immutable ).toVar();
  33824. const v0 = float( v0_immutable ).toVar();
  33825. const s1 = float( sub( 1.0, s ) ).toVar();
  33826. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33827. } ).setLayout( {
  33828. name: 'mx_bilerp_0',
  33829. type: 'float',
  33830. inputs: [
  33831. { name: 'v0', type: 'float' },
  33832. { name: 'v1', type: 'float' },
  33833. { name: 'v2', type: 'float' },
  33834. { name: 'v3', type: 'float' },
  33835. { name: 's', type: 'float' },
  33836. { name: 't', type: 'float' }
  33837. ]
  33838. } );
  33839. const mx_bilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33840. const t = float( t_immutable ).toVar();
  33841. const s = float( s_immutable ).toVar();
  33842. const v3 = vec3( v3_immutable ).toVar();
  33843. const v2 = vec3( v2_immutable ).toVar();
  33844. const v1 = vec3( v1_immutable ).toVar();
  33845. const v0 = vec3( v0_immutable ).toVar();
  33846. const s1 = float( sub( 1.0, s ) ).toVar();
  33847. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33848. } ).setLayout( {
  33849. name: 'mx_bilerp_1',
  33850. type: 'vec3',
  33851. inputs: [
  33852. { name: 'v0', type: 'vec3' },
  33853. { name: 'v1', type: 'vec3' },
  33854. { name: 'v2', type: 'vec3' },
  33855. { name: 'v3', type: 'vec3' },
  33856. { name: 's', type: 'float' },
  33857. { name: 't', type: 'float' }
  33858. ]
  33859. } );
  33860. const mx_bilerp = /*#__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  33861. 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 ] ) => {
  33862. const r = float( r_immutable ).toVar();
  33863. const t = float( t_immutable ).toVar();
  33864. const s = float( s_immutable ).toVar();
  33865. const v7 = float( v7_immutable ).toVar();
  33866. const v6 = float( v6_immutable ).toVar();
  33867. const v5 = float( v5_immutable ).toVar();
  33868. const v4 = float( v4_immutable ).toVar();
  33869. const v3 = float( v3_immutable ).toVar();
  33870. const v2 = float( v2_immutable ).toVar();
  33871. const v1 = float( v1_immutable ).toVar();
  33872. const v0 = float( v0_immutable ).toVar();
  33873. const s1 = float( sub( 1.0, s ) ).toVar();
  33874. const t1 = float( sub( 1.0, t ) ).toVar();
  33875. const r1 = float( sub( 1.0, r ) ).toVar();
  33876. 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 ) ) ) ) ) );
  33877. } ).setLayout( {
  33878. name: 'mx_trilerp_0',
  33879. type: 'float',
  33880. inputs: [
  33881. { name: 'v0', type: 'float' },
  33882. { name: 'v1', type: 'float' },
  33883. { name: 'v2', type: 'float' },
  33884. { name: 'v3', type: 'float' },
  33885. { name: 'v4', type: 'float' },
  33886. { name: 'v5', type: 'float' },
  33887. { name: 'v6', type: 'float' },
  33888. { name: 'v7', type: 'float' },
  33889. { name: 's', type: 'float' },
  33890. { name: 't', type: 'float' },
  33891. { name: 'r', type: 'float' }
  33892. ]
  33893. } );
  33894. 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 ] ) => {
  33895. const r = float( r_immutable ).toVar();
  33896. const t = float( t_immutable ).toVar();
  33897. const s = float( s_immutable ).toVar();
  33898. const v7 = vec3( v7_immutable ).toVar();
  33899. const v6 = vec3( v6_immutable ).toVar();
  33900. const v5 = vec3( v5_immutable ).toVar();
  33901. const v4 = vec3( v4_immutable ).toVar();
  33902. const v3 = vec3( v3_immutable ).toVar();
  33903. const v2 = vec3( v2_immutable ).toVar();
  33904. const v1 = vec3( v1_immutable ).toVar();
  33905. const v0 = vec3( v0_immutable ).toVar();
  33906. const s1 = float( sub( 1.0, s ) ).toVar();
  33907. const t1 = float( sub( 1.0, t ) ).toVar();
  33908. const r1 = float( sub( 1.0, r ) ).toVar();
  33909. 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 ) ) ) ) ) );
  33910. } ).setLayout( {
  33911. name: 'mx_trilerp_1',
  33912. type: 'vec3',
  33913. inputs: [
  33914. { name: 'v0', type: 'vec3' },
  33915. { name: 'v1', type: 'vec3' },
  33916. { name: 'v2', type: 'vec3' },
  33917. { name: 'v3', type: 'vec3' },
  33918. { name: 'v4', type: 'vec3' },
  33919. { name: 'v5', type: 'vec3' },
  33920. { name: 'v6', type: 'vec3' },
  33921. { name: 'v7', type: 'vec3' },
  33922. { name: 's', type: 'float' },
  33923. { name: 't', type: 'float' },
  33924. { name: 'r', type: 'float' }
  33925. ]
  33926. } );
  33927. const mx_trilerp = /*#__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  33928. const mx_gradient_float_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33929. const y = float( y_immutable ).toVar();
  33930. const x = float( x_immutable ).toVar();
  33931. const hash = uint( hash_immutable ).toVar();
  33932. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  33933. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  33934. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  33935. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33936. } ).setLayout( {
  33937. name: 'mx_gradient_float_0',
  33938. type: 'float',
  33939. inputs: [
  33940. { name: 'hash', type: 'uint' },
  33941. { name: 'x', type: 'float' },
  33942. { name: 'y', type: 'float' }
  33943. ]
  33944. } );
  33945. const mx_gradient_float_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33946. const z = float( z_immutable ).toVar();
  33947. const y = float( y_immutable ).toVar();
  33948. const x = float( x_immutable ).toVar();
  33949. const hash = uint( hash_immutable ).toVar();
  33950. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  33951. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  33952. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  33953. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33954. } ).setLayout( {
  33955. name: 'mx_gradient_float_1',
  33956. type: 'float',
  33957. inputs: [
  33958. { name: 'hash', type: 'uint' },
  33959. { name: 'x', type: 'float' },
  33960. { name: 'y', type: 'float' },
  33961. { name: 'z', type: 'float' }
  33962. ]
  33963. } );
  33964. const mx_gradient_float = /*#__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  33965. const mx_gradient_vec3_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33966. const y = float( y_immutable ).toVar();
  33967. const x = float( x_immutable ).toVar();
  33968. const hash = uvec3( hash_immutable ).toVar();
  33969. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  33970. } ).setLayout( {
  33971. name: 'mx_gradient_vec3_0',
  33972. type: 'vec3',
  33973. inputs: [
  33974. { name: 'hash', type: 'uvec3' },
  33975. { name: 'x', type: 'float' },
  33976. { name: 'y', type: 'float' }
  33977. ]
  33978. } );
  33979. const mx_gradient_vec3_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33980. const z = float( z_immutable ).toVar();
  33981. const y = float( y_immutable ).toVar();
  33982. const x = float( x_immutable ).toVar();
  33983. const hash = uvec3( hash_immutable ).toVar();
  33984. 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 ) );
  33985. } ).setLayout( {
  33986. name: 'mx_gradient_vec3_1',
  33987. type: 'vec3',
  33988. inputs: [
  33989. { name: 'hash', type: 'uvec3' },
  33990. { name: 'x', type: 'float' },
  33991. { name: 'y', type: 'float' },
  33992. { name: 'z', type: 'float' }
  33993. ]
  33994. } );
  33995. const mx_gradient_vec3 = /*#__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  33996. const mx_gradient_scale2d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  33997. const v = float( v_immutable ).toVar();
  33998. return mul( 0.6616, v );
  33999. } ).setLayout( {
  34000. name: 'mx_gradient_scale2d_0',
  34001. type: 'float',
  34002. inputs: [
  34003. { name: 'v', type: 'float' }
  34004. ]
  34005. } );
  34006. const mx_gradient_scale3d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  34007. const v = float( v_immutable ).toVar();
  34008. return mul( 0.9820, v );
  34009. } ).setLayout( {
  34010. name: 'mx_gradient_scale3d_0',
  34011. type: 'float',
  34012. inputs: [
  34013. { name: 'v', type: 'float' }
  34014. ]
  34015. } );
  34016. const mx_gradient_scale2d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  34017. const v = vec3( v_immutable ).toVar();
  34018. return mul( 0.6616, v );
  34019. } ).setLayout( {
  34020. name: 'mx_gradient_scale2d_1',
  34021. type: 'vec3',
  34022. inputs: [
  34023. { name: 'v', type: 'vec3' }
  34024. ]
  34025. } );
  34026. const mx_gradient_scale2d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  34027. const mx_gradient_scale3d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  34028. const v = vec3( v_immutable ).toVar();
  34029. return mul( 0.9820, v );
  34030. } ).setLayout( {
  34031. name: 'mx_gradient_scale3d_1',
  34032. type: 'vec3',
  34033. inputs: [
  34034. { name: 'v', type: 'vec3' }
  34035. ]
  34036. } );
  34037. const mx_gradient_scale3d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  34038. const mx_rotl32 = /*#__PURE__*/ tslFn( ( [ x_immutable, k_immutable ] ) => {
  34039. const k = int( k_immutable ).toVar();
  34040. const x = uint( x_immutable ).toVar();
  34041. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  34042. } ).setLayout( {
  34043. name: 'mx_rotl32',
  34044. type: 'uint',
  34045. inputs: [
  34046. { name: 'x', type: 'uint' },
  34047. { name: 'k', type: 'int' }
  34048. ]
  34049. } );
  34050. const mx_bjmix = /*#__PURE__*/ tslFn( ( [ a, b, c ] ) => {
  34051. a.subAssign( c );
  34052. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  34053. c.addAssign( b );
  34054. b.subAssign( a );
  34055. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  34056. a.addAssign( c );
  34057. c.subAssign( b );
  34058. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  34059. b.addAssign( a );
  34060. a.subAssign( c );
  34061. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  34062. c.addAssign( b );
  34063. b.subAssign( a );
  34064. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  34065. a.addAssign( c );
  34066. c.subAssign( b );
  34067. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  34068. b.addAssign( a );
  34069. } );
  34070. const mx_bjfinal = /*#__PURE__*/ tslFn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  34071. const c = uint( c_immutable ).toVar();
  34072. const b = uint( b_immutable ).toVar();
  34073. const a = uint( a_immutable ).toVar();
  34074. c.bitXorAssign( b );
  34075. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  34076. a.bitXorAssign( c );
  34077. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  34078. b.bitXorAssign( a );
  34079. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  34080. c.bitXorAssign( b );
  34081. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  34082. a.bitXorAssign( c );
  34083. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  34084. b.bitXorAssign( a );
  34085. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  34086. c.bitXorAssign( b );
  34087. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  34088. return c;
  34089. } ).setLayout( {
  34090. name: 'mx_bjfinal',
  34091. type: 'uint',
  34092. inputs: [
  34093. { name: 'a', type: 'uint' },
  34094. { name: 'b', type: 'uint' },
  34095. { name: 'c', type: 'uint' }
  34096. ]
  34097. } );
  34098. const mx_bits_to_01 = /*#__PURE__*/ tslFn( ( [ bits_immutable ] ) => {
  34099. const bits = uint( bits_immutable ).toVar();
  34100. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  34101. } ).setLayout( {
  34102. name: 'mx_bits_to_01',
  34103. type: 'float',
  34104. inputs: [
  34105. { name: 'bits', type: 'uint' }
  34106. ]
  34107. } );
  34108. const mx_fade = /*#__PURE__*/ tslFn( ( [ t_immutable ] ) => {
  34109. const t = float( t_immutable ).toVar();
  34110. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  34111. } ).setLayout( {
  34112. name: 'mx_fade',
  34113. type: 'float',
  34114. inputs: [
  34115. { name: 't', type: 'float' }
  34116. ]
  34117. } );
  34118. const mx_hash_int_0 = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  34119. const x = int( x_immutable ).toVar();
  34120. const len = uint( uint( 1 ) ).toVar();
  34121. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  34122. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  34123. } ).setLayout( {
  34124. name: 'mx_hash_int_0',
  34125. type: 'uint',
  34126. inputs: [
  34127. { name: 'x', type: 'int' }
  34128. ]
  34129. } );
  34130. const mx_hash_int_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  34131. const y = int( y_immutable ).toVar();
  34132. const x = int( x_immutable ).toVar();
  34133. const len = uint( uint( 2 ) ).toVar();
  34134. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34135. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34136. a.addAssign( uint( x ) );
  34137. b.addAssign( uint( y ) );
  34138. return mx_bjfinal( a, b, c );
  34139. } ).setLayout( {
  34140. name: 'mx_hash_int_1',
  34141. type: 'uint',
  34142. inputs: [
  34143. { name: 'x', type: 'int' },
  34144. { name: 'y', type: 'int' }
  34145. ]
  34146. } );
  34147. const mx_hash_int_2 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34148. const z = int( z_immutable ).toVar();
  34149. const y = int( y_immutable ).toVar();
  34150. const x = int( x_immutable ).toVar();
  34151. const len = uint( uint( 3 ) ).toVar();
  34152. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34153. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34154. a.addAssign( uint( x ) );
  34155. b.addAssign( uint( y ) );
  34156. c.addAssign( uint( z ) );
  34157. return mx_bjfinal( a, b, c );
  34158. } ).setLayout( {
  34159. name: 'mx_hash_int_2',
  34160. type: 'uint',
  34161. inputs: [
  34162. { name: 'x', type: 'int' },
  34163. { name: 'y', type: 'int' },
  34164. { name: 'z', type: 'int' }
  34165. ]
  34166. } );
  34167. const mx_hash_int_3 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  34168. const xx = int( xx_immutable ).toVar();
  34169. const z = int( z_immutable ).toVar();
  34170. const y = int( y_immutable ).toVar();
  34171. const x = int( x_immutable ).toVar();
  34172. const len = uint( uint( 4 ) ).toVar();
  34173. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34174. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34175. a.addAssign( uint( x ) );
  34176. b.addAssign( uint( y ) );
  34177. c.addAssign( uint( z ) );
  34178. mx_bjmix( a, b, c );
  34179. a.addAssign( uint( xx ) );
  34180. return mx_bjfinal( a, b, c );
  34181. } ).setLayout( {
  34182. name: 'mx_hash_int_3',
  34183. type: 'uint',
  34184. inputs: [
  34185. { name: 'x', type: 'int' },
  34186. { name: 'y', type: 'int' },
  34187. { name: 'z', type: 'int' },
  34188. { name: 'xx', type: 'int' }
  34189. ]
  34190. } );
  34191. const mx_hash_int_4 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  34192. const yy = int( yy_immutable ).toVar();
  34193. const xx = int( xx_immutable ).toVar();
  34194. const z = int( z_immutable ).toVar();
  34195. const y = int( y_immutable ).toVar();
  34196. const x = int( x_immutable ).toVar();
  34197. const len = uint( uint( 5 ) ).toVar();
  34198. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34199. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34200. a.addAssign( uint( x ) );
  34201. b.addAssign( uint( y ) );
  34202. c.addAssign( uint( z ) );
  34203. mx_bjmix( a, b, c );
  34204. a.addAssign( uint( xx ) );
  34205. b.addAssign( uint( yy ) );
  34206. return mx_bjfinal( a, b, c );
  34207. } ).setLayout( {
  34208. name: 'mx_hash_int_4',
  34209. type: 'uint',
  34210. inputs: [
  34211. { name: 'x', type: 'int' },
  34212. { name: 'y', type: 'int' },
  34213. { name: 'z', type: 'int' },
  34214. { name: 'xx', type: 'int' },
  34215. { name: 'yy', type: 'int' }
  34216. ]
  34217. } );
  34218. 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 ] );
  34219. const mx_hash_vec3_0 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  34220. const y = int( y_immutable ).toVar();
  34221. const x = int( x_immutable ).toVar();
  34222. const h = uint( mx_hash_int( x, y ) ).toVar();
  34223. const result = uvec3().toVar();
  34224. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34225. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34226. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34227. return result;
  34228. } ).setLayout( {
  34229. name: 'mx_hash_vec3_0',
  34230. type: 'uvec3',
  34231. inputs: [
  34232. { name: 'x', type: 'int' },
  34233. { name: 'y', type: 'int' }
  34234. ]
  34235. } );
  34236. const mx_hash_vec3_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34237. const z = int( z_immutable ).toVar();
  34238. const y = int( y_immutable ).toVar();
  34239. const x = int( x_immutable ).toVar();
  34240. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  34241. const result = uvec3().toVar();
  34242. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34243. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34244. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34245. return result;
  34246. } ).setLayout( {
  34247. name: 'mx_hash_vec3_1',
  34248. type: 'uvec3',
  34249. inputs: [
  34250. { name: 'x', type: 'int' },
  34251. { name: 'y', type: 'int' },
  34252. { name: 'z', type: 'int' }
  34253. ]
  34254. } );
  34255. const mx_hash_vec3 = /*#__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  34256. const mx_perlin_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34257. const p = vec2( p_immutable ).toVar();
  34258. const X = int().toVar(), Y = int().toVar();
  34259. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34260. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34261. const u = float( mx_fade( fx ) ).toVar();
  34262. const v = float( mx_fade( fy ) ).toVar();
  34263. 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();
  34264. return mx_gradient_scale2d( result );
  34265. } ).setLayout( {
  34266. name: 'mx_perlin_noise_float_0',
  34267. type: 'float',
  34268. inputs: [
  34269. { name: 'p', type: 'vec2' }
  34270. ]
  34271. } );
  34272. const mx_perlin_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34273. const p = vec3( p_immutable ).toVar();
  34274. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34275. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34276. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34277. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34278. const u = float( mx_fade( fx ) ).toVar();
  34279. const v = float( mx_fade( fy ) ).toVar();
  34280. const w = float( mx_fade( fz ) ).toVar();
  34281. 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();
  34282. return mx_gradient_scale3d( result );
  34283. } ).setLayout( {
  34284. name: 'mx_perlin_noise_float_1',
  34285. type: 'float',
  34286. inputs: [
  34287. { name: 'p', type: 'vec3' }
  34288. ]
  34289. } );
  34290. const mx_perlin_noise_float = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  34291. const mx_perlin_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34292. const p = vec2( p_immutable ).toVar();
  34293. const X = int().toVar(), Y = int().toVar();
  34294. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34295. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34296. const u = float( mx_fade( fx ) ).toVar();
  34297. const v = float( mx_fade( fy ) ).toVar();
  34298. 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();
  34299. return mx_gradient_scale2d( result );
  34300. } ).setLayout( {
  34301. name: 'mx_perlin_noise_vec3_0',
  34302. type: 'vec3',
  34303. inputs: [
  34304. { name: 'p', type: 'vec2' }
  34305. ]
  34306. } );
  34307. const mx_perlin_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34308. const p = vec3( p_immutable ).toVar();
  34309. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34310. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34311. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34312. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34313. const u = float( mx_fade( fx ) ).toVar();
  34314. const v = float( mx_fade( fy ) ).toVar();
  34315. const w = float( mx_fade( fz ) ).toVar();
  34316. 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();
  34317. return mx_gradient_scale3d( result );
  34318. } ).setLayout( {
  34319. name: 'mx_perlin_noise_vec3_1',
  34320. type: 'vec3',
  34321. inputs: [
  34322. { name: 'p', type: 'vec3' }
  34323. ]
  34324. } );
  34325. const mx_perlin_noise_vec3 = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  34326. const mx_cell_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34327. const p = float( p_immutable ).toVar();
  34328. const ix = int( mx_floor( p ) ).toVar();
  34329. return mx_bits_to_01( mx_hash_int( ix ) );
  34330. } ).setLayout( {
  34331. name: 'mx_cell_noise_float_0',
  34332. type: 'float',
  34333. inputs: [
  34334. { name: 'p', type: 'float' }
  34335. ]
  34336. } );
  34337. const mx_cell_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34338. const p = vec2( p_immutable ).toVar();
  34339. const ix = int( mx_floor( p.x ) ).toVar();
  34340. const iy = int( mx_floor( p.y ) ).toVar();
  34341. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  34342. } ).setLayout( {
  34343. name: 'mx_cell_noise_float_1',
  34344. type: 'float',
  34345. inputs: [
  34346. { name: 'p', type: 'vec2' }
  34347. ]
  34348. } );
  34349. const mx_cell_noise_float_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34350. const p = vec3( p_immutable ).toVar();
  34351. const ix = int( mx_floor( p.x ) ).toVar();
  34352. const iy = int( mx_floor( p.y ) ).toVar();
  34353. const iz = int( mx_floor( p.z ) ).toVar();
  34354. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  34355. } ).setLayout( {
  34356. name: 'mx_cell_noise_float_2',
  34357. type: 'float',
  34358. inputs: [
  34359. { name: 'p', type: 'vec3' }
  34360. ]
  34361. } );
  34362. const mx_cell_noise_float_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34363. const p = vec4( p_immutable ).toVar();
  34364. const ix = int( mx_floor( p.x ) ).toVar();
  34365. const iy = int( mx_floor( p.y ) ).toVar();
  34366. const iz = int( mx_floor( p.z ) ).toVar();
  34367. const iw = int( mx_floor( p.w ) ).toVar();
  34368. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  34369. } ).setLayout( {
  34370. name: 'mx_cell_noise_float_3',
  34371. type: 'float',
  34372. inputs: [
  34373. { name: 'p', type: 'vec4' }
  34374. ]
  34375. } );
  34376. 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 ] );
  34377. const mx_cell_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34378. const p = float( p_immutable ).toVar();
  34379. const ix = int( mx_floor( p ) ).toVar();
  34380. 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 ) ) ) );
  34381. } ).setLayout( {
  34382. name: 'mx_cell_noise_vec3_0',
  34383. type: 'vec3',
  34384. inputs: [
  34385. { name: 'p', type: 'float' }
  34386. ]
  34387. } );
  34388. const mx_cell_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34389. const p = vec2( p_immutable ).toVar();
  34390. const ix = int( mx_floor( p.x ) ).toVar();
  34391. const iy = int( mx_floor( p.y ) ).toVar();
  34392. 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 ) ) ) );
  34393. } ).setLayout( {
  34394. name: 'mx_cell_noise_vec3_1',
  34395. type: 'vec3',
  34396. inputs: [
  34397. { name: 'p', type: 'vec2' }
  34398. ]
  34399. } );
  34400. const mx_cell_noise_vec3_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34401. const p = vec3( p_immutable ).toVar();
  34402. const ix = int( mx_floor( p.x ) ).toVar();
  34403. const iy = int( mx_floor( p.y ) ).toVar();
  34404. const iz = int( mx_floor( p.z ) ).toVar();
  34405. 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 ) ) ) );
  34406. } ).setLayout( {
  34407. name: 'mx_cell_noise_vec3_2',
  34408. type: 'vec3',
  34409. inputs: [
  34410. { name: 'p', type: 'vec3' }
  34411. ]
  34412. } );
  34413. const mx_cell_noise_vec3_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34414. const p = vec4( p_immutable ).toVar();
  34415. const ix = int( mx_floor( p.x ) ).toVar();
  34416. const iy = int( mx_floor( p.y ) ).toVar();
  34417. const iz = int( mx_floor( p.z ) ).toVar();
  34418. const iw = int( mx_floor( p.w ) ).toVar();
  34419. 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 ) ) ) );
  34420. } ).setLayout( {
  34421. name: 'mx_cell_noise_vec3_3',
  34422. type: 'vec3',
  34423. inputs: [
  34424. { name: 'p', type: 'vec4' }
  34425. ]
  34426. } );
  34427. 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 ] );
  34428. const mx_fractal_noise_float$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34429. const diminish = float( diminish_immutable ).toVar();
  34430. const lacunarity = float( lacunarity_immutable ).toVar();
  34431. const octaves = int( octaves_immutable ).toVar();
  34432. const p = vec3( p_immutable ).toVar();
  34433. const result = float( 0.0 ).toVar();
  34434. const amplitude = float( 1.0 ).toVar();
  34435. loop( octaves, () => {
  34436. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  34437. amplitude.mulAssign( diminish );
  34438. p.mulAssign( lacunarity );
  34439. } );
  34440. return result;
  34441. } ).setLayout( {
  34442. name: 'mx_fractal_noise_float',
  34443. type: 'float',
  34444. inputs: [
  34445. { name: 'p', type: 'vec3' },
  34446. { name: 'octaves', type: 'int' },
  34447. { name: 'lacunarity', type: 'float' },
  34448. { name: 'diminish', type: 'float' }
  34449. ]
  34450. } );
  34451. const mx_fractal_noise_vec3$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34452. const diminish = float( diminish_immutable ).toVar();
  34453. const lacunarity = float( lacunarity_immutable ).toVar();
  34454. const octaves = int( octaves_immutable ).toVar();
  34455. const p = vec3( p_immutable ).toVar();
  34456. const result = vec3( 0.0 ).toVar();
  34457. const amplitude = float( 1.0 ).toVar();
  34458. loop( octaves, () => {
  34459. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  34460. amplitude.mulAssign( diminish );
  34461. p.mulAssign( lacunarity );
  34462. } );
  34463. return result;
  34464. } ).setLayout( {
  34465. name: 'mx_fractal_noise_vec3',
  34466. type: 'vec3',
  34467. inputs: [
  34468. { name: 'p', type: 'vec3' },
  34469. { name: 'octaves', type: 'int' },
  34470. { name: 'lacunarity', type: 'float' },
  34471. { name: 'diminish', type: 'float' }
  34472. ]
  34473. } );
  34474. const mx_fractal_noise_vec2$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34475. const diminish = float( diminish_immutable ).toVar();
  34476. const lacunarity = float( lacunarity_immutable ).toVar();
  34477. const octaves = int( octaves_immutable ).toVar();
  34478. const p = vec3( p_immutable ).toVar();
  34479. 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 ) );
  34480. } ).setLayout( {
  34481. name: 'mx_fractal_noise_vec2',
  34482. type: 'vec2',
  34483. inputs: [
  34484. { name: 'p', type: 'vec3' },
  34485. { name: 'octaves', type: 'int' },
  34486. { name: 'lacunarity', type: 'float' },
  34487. { name: 'diminish', type: 'float' }
  34488. ]
  34489. } );
  34490. const mx_fractal_noise_vec4$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34491. const diminish = float( diminish_immutable ).toVar();
  34492. const lacunarity = float( lacunarity_immutable ).toVar();
  34493. const octaves = int( octaves_immutable ).toVar();
  34494. const p = vec3( p_immutable ).toVar();
  34495. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  34496. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  34497. return vec4( c, f );
  34498. } ).setLayout( {
  34499. name: 'mx_fractal_noise_vec4',
  34500. type: 'vec4',
  34501. inputs: [
  34502. { name: 'p', type: 'vec3' },
  34503. { name: 'octaves', type: 'int' },
  34504. { name: 'lacunarity', type: 'float' },
  34505. { name: 'diminish', type: 'float' }
  34506. ]
  34507. } );
  34508. const mx_worley_distance_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34509. const metric = int( metric_immutable ).toVar();
  34510. const jitter = float( jitter_immutable ).toVar();
  34511. const yoff = int( yoff_immutable ).toVar();
  34512. const xoff = int( xoff_immutable ).toVar();
  34513. const y = int( y_immutable ).toVar();
  34514. const x = int( x_immutable ).toVar();
  34515. const p = vec2( p_immutable ).toVar();
  34516. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  34517. const off = vec2( tmp.x, tmp.y ).toVar();
  34518. off.subAssign( 0.5 );
  34519. off.mulAssign( jitter );
  34520. off.addAssign( 0.5 );
  34521. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  34522. const diff = vec2( cellpos.sub( p ) ).toVar();
  34523. If( metric.equal( int( 2 ) ), () => {
  34524. return abs( diff.x ).add( abs( diff.y ) );
  34525. } );
  34526. If( metric.equal( int( 3 ) ), () => {
  34527. return max$1( abs( diff.x ), abs( diff.y ) );
  34528. } );
  34529. return dot( diff, diff );
  34530. } ).setLayout( {
  34531. name: 'mx_worley_distance_0',
  34532. type: 'float',
  34533. inputs: [
  34534. { name: 'p', type: 'vec2' },
  34535. { name: 'x', type: 'int' },
  34536. { name: 'y', type: 'int' },
  34537. { name: 'xoff', type: 'int' },
  34538. { name: 'yoff', type: 'int' },
  34539. { name: 'jitter', type: 'float' },
  34540. { name: 'metric', type: 'int' }
  34541. ]
  34542. } );
  34543. 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 ] ) => {
  34544. const metric = int( metric_immutable ).toVar();
  34545. const jitter = float( jitter_immutable ).toVar();
  34546. const zoff = int( zoff_immutable ).toVar();
  34547. const yoff = int( yoff_immutable ).toVar();
  34548. const xoff = int( xoff_immutable ).toVar();
  34549. const z = int( z_immutable ).toVar();
  34550. const y = int( y_immutable ).toVar();
  34551. const x = int( x_immutable ).toVar();
  34552. const p = vec3( p_immutable ).toVar();
  34553. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  34554. off.subAssign( 0.5 );
  34555. off.mulAssign( jitter );
  34556. off.addAssign( 0.5 );
  34557. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  34558. const diff = vec3( cellpos.sub( p ) ).toVar();
  34559. If( metric.equal( int( 2 ) ), () => {
  34560. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  34561. } );
  34562. If( metric.equal( int( 3 ) ), () => {
  34563. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  34564. } );
  34565. return dot( diff, diff );
  34566. } ).setLayout( {
  34567. name: 'mx_worley_distance_1',
  34568. type: 'float',
  34569. inputs: [
  34570. { name: 'p', type: 'vec3' },
  34571. { name: 'x', type: 'int' },
  34572. { name: 'y', type: 'int' },
  34573. { name: 'z', type: 'int' },
  34574. { name: 'xoff', type: 'int' },
  34575. { name: 'yoff', type: 'int' },
  34576. { name: 'zoff', type: 'int' },
  34577. { name: 'jitter', type: 'float' },
  34578. { name: 'metric', type: 'int' }
  34579. ]
  34580. } );
  34581. const mx_worley_distance = /*#__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  34582. const mx_worley_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34583. const metric = int( metric_immutable ).toVar();
  34584. const jitter = float( jitter_immutable ).toVar();
  34585. const p = vec2( p_immutable ).toVar();
  34586. const X = int().toVar(), Y = int().toVar();
  34587. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34588. const sqdist = float( 1e6 ).toVar();
  34589. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34590. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34591. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34592. sqdist.assign( min$1( sqdist, dist ) );
  34593. } );
  34594. } );
  34595. If( metric.equal( int( 0 ) ), () => {
  34596. sqdist.assign( sqrt( sqdist ) );
  34597. } );
  34598. return sqdist;
  34599. } ).setLayout( {
  34600. name: 'mx_worley_noise_float_0',
  34601. type: 'float',
  34602. inputs: [
  34603. { name: 'p', type: 'vec2' },
  34604. { name: 'jitter', type: 'float' },
  34605. { name: 'metric', type: 'int' }
  34606. ]
  34607. } );
  34608. const mx_worley_noise_vec2_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34609. const metric = int( metric_immutable ).toVar();
  34610. const jitter = float( jitter_immutable ).toVar();
  34611. const p = vec2( p_immutable ).toVar();
  34612. const X = int().toVar(), Y = int().toVar();
  34613. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34614. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34615. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34616. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34617. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34618. If( dist.lessThan( sqdist.x ), () => {
  34619. sqdist.y.assign( sqdist.x );
  34620. sqdist.x.assign( dist );
  34621. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34622. sqdist.y.assign( dist );
  34623. } );
  34624. } );
  34625. } );
  34626. If( metric.equal( int( 0 ) ), () => {
  34627. sqdist.assign( sqrt( sqdist ) );
  34628. } );
  34629. return sqdist;
  34630. } ).setLayout( {
  34631. name: 'mx_worley_noise_vec2_0',
  34632. type: 'vec2',
  34633. inputs: [
  34634. { name: 'p', type: 'vec2' },
  34635. { name: 'jitter', type: 'float' },
  34636. { name: 'metric', type: 'int' }
  34637. ]
  34638. } );
  34639. const mx_worley_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34640. const metric = int( metric_immutable ).toVar();
  34641. const jitter = float( jitter_immutable ).toVar();
  34642. const p = vec2( p_immutable ).toVar();
  34643. const X = int().toVar(), Y = int().toVar();
  34644. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34645. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34646. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34647. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34648. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34649. If( dist.lessThan( sqdist.x ), () => {
  34650. sqdist.z.assign( sqdist.y );
  34651. sqdist.y.assign( sqdist.x );
  34652. sqdist.x.assign( dist );
  34653. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34654. sqdist.z.assign( sqdist.y );
  34655. sqdist.y.assign( dist );
  34656. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34657. sqdist.z.assign( dist );
  34658. } );
  34659. } );
  34660. } );
  34661. If( metric.equal( int( 0 ) ), () => {
  34662. sqdist.assign( sqrt( sqdist ) );
  34663. } );
  34664. return sqdist;
  34665. } ).setLayout( {
  34666. name: 'mx_worley_noise_vec3_0',
  34667. type: 'vec3',
  34668. inputs: [
  34669. { name: 'p', type: 'vec2' },
  34670. { name: 'jitter', type: 'float' },
  34671. { name: 'metric', type: 'int' }
  34672. ]
  34673. } );
  34674. const mx_worley_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34675. const metric = int( metric_immutable ).toVar();
  34676. const jitter = float( jitter_immutable ).toVar();
  34677. const p = vec3( p_immutable ).toVar();
  34678. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34679. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34680. const sqdist = float( 1e6 ).toVar();
  34681. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34682. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34683. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34684. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34685. sqdist.assign( min$1( sqdist, dist ) );
  34686. } );
  34687. } );
  34688. } );
  34689. If( metric.equal( int( 0 ) ), () => {
  34690. sqdist.assign( sqrt( sqdist ) );
  34691. } );
  34692. return sqdist;
  34693. } ).setLayout( {
  34694. name: 'mx_worley_noise_float_1',
  34695. type: 'float',
  34696. inputs: [
  34697. { name: 'p', type: 'vec3' },
  34698. { name: 'jitter', type: 'float' },
  34699. { name: 'metric', type: 'int' }
  34700. ]
  34701. } );
  34702. const mx_worley_noise_float$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  34703. const mx_worley_noise_vec2_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34704. const metric = int( metric_immutable ).toVar();
  34705. const jitter = float( jitter_immutable ).toVar();
  34706. const p = vec3( p_immutable ).toVar();
  34707. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34708. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34709. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34710. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34711. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34712. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34713. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34714. If( dist.lessThan( sqdist.x ), () => {
  34715. sqdist.y.assign( sqdist.x );
  34716. sqdist.x.assign( dist );
  34717. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34718. sqdist.y.assign( dist );
  34719. } );
  34720. } );
  34721. } );
  34722. } );
  34723. If( metric.equal( int( 0 ) ), () => {
  34724. sqdist.assign( sqrt( sqdist ) );
  34725. } );
  34726. return sqdist;
  34727. } ).setLayout( {
  34728. name: 'mx_worley_noise_vec2_1',
  34729. type: 'vec2',
  34730. inputs: [
  34731. { name: 'p', type: 'vec3' },
  34732. { name: 'jitter', type: 'float' },
  34733. { name: 'metric', type: 'int' }
  34734. ]
  34735. } );
  34736. const mx_worley_noise_vec2$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  34737. const mx_worley_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34738. const metric = int( metric_immutable ).toVar();
  34739. const jitter = float( jitter_immutable ).toVar();
  34740. const p = vec3( p_immutable ).toVar();
  34741. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34742. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34743. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34744. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34745. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34746. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34747. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34748. If( dist.lessThan( sqdist.x ), () => {
  34749. sqdist.z.assign( sqdist.y );
  34750. sqdist.y.assign( sqdist.x );
  34751. sqdist.x.assign( dist );
  34752. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34753. sqdist.z.assign( sqdist.y );
  34754. sqdist.y.assign( dist );
  34755. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34756. sqdist.z.assign( dist );
  34757. } );
  34758. } );
  34759. } );
  34760. } );
  34761. If( metric.equal( int( 0 ) ), () => {
  34762. sqdist.assign( sqrt( sqdist ) );
  34763. } );
  34764. return sqdist;
  34765. } ).setLayout( {
  34766. name: 'mx_worley_noise_vec3_1',
  34767. type: 'vec3',
  34768. inputs: [
  34769. { name: 'p', type: 'vec3' },
  34770. { name: 'jitter', type: 'float' },
  34771. { name: 'metric', type: 'int' }
  34772. ]
  34773. } );
  34774. const mx_worley_noise_vec3$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34775. // Three.js Transpiler
  34776. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34777. const mx_hsvtorgb = /*#__PURE__*/ tslFn( ( [ hsv_immutable ] ) => {
  34778. const hsv = vec3( hsv_immutable ).toVar();
  34779. const h = float( hsv.x ).toVar();
  34780. const s = float( hsv.y ).toVar();
  34781. const v = float( hsv.z ).toVar();
  34782. If( s.lessThan( 0.0001 ), () => {
  34783. return vec3( v, v, v );
  34784. } ).else( () => {
  34785. h.assign( mul( 6.0, h.sub( floor( h ) ) ) );
  34786. const hi = int( trunc( h ) ).toVar();
  34787. const f = float( h.sub( float( hi ) ) ).toVar();
  34788. const p = float( v.mul( sub( 1.0, s ) ) ).toVar();
  34789. const q = float( v.mul( sub( 1.0, s.mul( f ) ) ) ).toVar();
  34790. const t = float( v.mul( sub( 1.0, s.mul( sub( 1.0, f ) ) ) ) ).toVar();
  34791. If( hi.equal( int( 0 ) ), () => {
  34792. return vec3( v, t, p );
  34793. } ).elseif( hi.equal( int( 1 ) ), () => {
  34794. return vec3( q, v, p );
  34795. } ).elseif( hi.equal( int( 2 ) ), () => {
  34796. return vec3( p, v, t );
  34797. } ).elseif( hi.equal( int( 3 ) ), () => {
  34798. return vec3( p, q, v );
  34799. } ).elseif( hi.equal( int( 4 ) ), () => {
  34800. return vec3( t, p, v );
  34801. } );
  34802. return vec3( v, p, q );
  34803. } );
  34804. } ).setLayout( {
  34805. name: 'mx_hsvtorgb',
  34806. type: 'vec3',
  34807. inputs: [
  34808. { name: 'hsv', type: 'vec3' }
  34809. ]
  34810. } );
  34811. const mx_rgbtohsv = /*#__PURE__*/ tslFn( ( [ c_immutable ] ) => {
  34812. const c = vec3( c_immutable ).toVar();
  34813. const r = float( c.x ).toVar();
  34814. const g = float( c.y ).toVar();
  34815. const b = float( c.z ).toVar();
  34816. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34817. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34818. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34819. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34820. v.assign( maxcomp );
  34821. If( maxcomp.greaterThan( 0.0 ), () => {
  34822. s.assign( delta.div( maxcomp ) );
  34823. } ).else( () => {
  34824. s.assign( 0.0 );
  34825. } );
  34826. If( s.lessThanEqual( 0.0 ), () => {
  34827. h.assign( 0.0 );
  34828. } ).else( () => {
  34829. If( r.greaterThanEqual( maxcomp ), () => {
  34830. h.assign( g.sub( b ).div( delta ) );
  34831. } ).elseif( g.greaterThanEqual( maxcomp ), () => {
  34832. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34833. } ).else( () => {
  34834. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34835. } );
  34836. h.mulAssign( 1.0 / 6.0 );
  34837. If( h.lessThan( 0.0 ), () => {
  34838. h.addAssign( 1.0 );
  34839. } );
  34840. } );
  34841. return vec3( h, s, v );
  34842. } ).setLayout( {
  34843. name: 'mx_rgbtohsv',
  34844. type: 'vec3',
  34845. inputs: [
  34846. { name: 'c', type: 'vec3' }
  34847. ]
  34848. } );
  34849. // Three.js Transpiler
  34850. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  34851. const mx_srgb_texture_to_lin_rec709 = /*#__PURE__*/ tslFn( ( [ color_immutable ] ) => {
  34852. const color = vec3( color_immutable ).toVar();
  34853. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  34854. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  34855. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  34856. return mix( linSeg, powSeg, isAbove );
  34857. } ).setLayout( {
  34858. name: 'mx_srgb_texture_to_lin_rec709',
  34859. type: 'vec3',
  34860. inputs: [
  34861. { name: 'color', type: 'vec3' }
  34862. ]
  34863. } );
  34864. const mx_aastep = ( threshold, value ) => {
  34865. threshold = float( threshold );
  34866. value = float( value );
  34867. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  34868. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  34869. };
  34870. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  34871. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  34872. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  34873. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  34874. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  34875. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  34876. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  34877. const mx_safepower = ( in1, in2 = 1 ) => {
  34878. in1 = float( in1 );
  34879. return in1.abs().pow( in2 ).mul( in1.sign() );
  34880. };
  34881. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  34882. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34883. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34884. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34885. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  34886. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  34887. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  34888. return noise_vec4.mul( amplitude ).add( pivot );
  34889. };
  34890. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34891. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34892. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34893. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  34894. 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 );
  34895. 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 );
  34896. 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 );
  34897. 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 );
  34898. function painterSortStable( a, b ) {
  34899. if ( a.groupOrder !== b.groupOrder ) {
  34900. return a.groupOrder - b.groupOrder;
  34901. } else if ( a.renderOrder !== b.renderOrder ) {
  34902. return a.renderOrder - b.renderOrder;
  34903. } else if ( a.material.id !== b.material.id ) {
  34904. return a.material.id - b.material.id;
  34905. } else if ( a.z !== b.z ) {
  34906. return a.z - b.z;
  34907. } else {
  34908. return a.id - b.id;
  34909. }
  34910. }
  34911. function reversePainterSortStable( a, b ) {
  34912. if ( a.groupOrder !== b.groupOrder ) {
  34913. return a.groupOrder - b.groupOrder;
  34914. } else if ( a.renderOrder !== b.renderOrder ) {
  34915. return a.renderOrder - b.renderOrder;
  34916. } else if ( a.z !== b.z ) {
  34917. return b.z - a.z;
  34918. } else {
  34919. return a.id - b.id;
  34920. }
  34921. }
  34922. class RenderList {
  34923. constructor() {
  34924. this.renderItems = [];
  34925. this.renderItemsIndex = 0;
  34926. this.opaque = [];
  34927. this.transparent = [];
  34928. this.bundles = [];
  34929. this.lightsNode = new LightsNode( [] );
  34930. this.lightsArray = [];
  34931. this.occlusionQueryCount = 0;
  34932. }
  34933. begin() {
  34934. this.renderItemsIndex = 0;
  34935. this.opaque.length = 0;
  34936. this.transparent.length = 0;
  34937. this.bundles.length = 0;
  34938. this.lightsArray.length = 0;
  34939. this.occlusionQueryCount = 0;
  34940. return this;
  34941. }
  34942. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  34943. let renderItem = this.renderItems[ this.renderItemsIndex ];
  34944. if ( renderItem === undefined ) {
  34945. renderItem = {
  34946. id: object.id,
  34947. object: object,
  34948. geometry: geometry,
  34949. material: material,
  34950. groupOrder: groupOrder,
  34951. renderOrder: object.renderOrder,
  34952. z: z,
  34953. group: group
  34954. };
  34955. this.renderItems[ this.renderItemsIndex ] = renderItem;
  34956. } else {
  34957. renderItem.id = object.id;
  34958. renderItem.object = object;
  34959. renderItem.geometry = geometry;
  34960. renderItem.material = material;
  34961. renderItem.groupOrder = groupOrder;
  34962. renderItem.renderOrder = object.renderOrder;
  34963. renderItem.z = z;
  34964. renderItem.group = group;
  34965. }
  34966. this.renderItemsIndex ++;
  34967. return renderItem;
  34968. }
  34969. push( object, geometry, material, groupOrder, z, group ) {
  34970. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  34971. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  34972. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  34973. }
  34974. unshift( object, geometry, material, groupOrder, z, group ) {
  34975. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  34976. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  34977. }
  34978. pushBundle( group ) {
  34979. this.bundles.push( group );
  34980. }
  34981. pushLight( light ) {
  34982. this.lightsArray.push( light );
  34983. }
  34984. getLightsNode() {
  34985. return this.lightsNode.fromLights( this.lightsArray );
  34986. }
  34987. sort( customOpaqueSort, customTransparentSort ) {
  34988. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  34989. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  34990. }
  34991. finish() {
  34992. // update lights
  34993. this.lightsNode.fromLights( this.lightsArray );
  34994. // Clear references from inactive renderItems in the list
  34995. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  34996. const renderItem = this.renderItems[ i ];
  34997. if ( renderItem.id === null ) break;
  34998. renderItem.id = null;
  34999. renderItem.object = null;
  35000. renderItem.geometry = null;
  35001. renderItem.material = null;
  35002. renderItem.groupOrder = null;
  35003. renderItem.renderOrder = null;
  35004. renderItem.z = null;
  35005. renderItem.group = null;
  35006. }
  35007. }
  35008. }
  35009. class RenderLists {
  35010. constructor() {
  35011. this.lists = new ChainMap();
  35012. }
  35013. get( scene, camera ) {
  35014. const lists = this.lists;
  35015. const keys = [ scene, camera ];
  35016. let list = lists.get( keys );
  35017. if ( list === undefined ) {
  35018. list = new RenderList();
  35019. lists.set( keys, list );
  35020. }
  35021. return list;
  35022. }
  35023. dispose() {
  35024. this.lists = new ChainMap();
  35025. }
  35026. }
  35027. let id$2 = 0;
  35028. class RenderContext {
  35029. constructor() {
  35030. this.id = id$2 ++;
  35031. this.color = true;
  35032. this.clearColor = true;
  35033. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  35034. this.depth = true;
  35035. this.clearDepth = true;
  35036. this.clearDepthValue = 1;
  35037. this.stencil = false;
  35038. this.clearStencil = true;
  35039. this.clearStencilValue = 1;
  35040. this.viewport = false;
  35041. this.viewportValue = new Vector4();
  35042. this.scissor = false;
  35043. this.scissorValue = new Vector4();
  35044. this.textures = null;
  35045. this.depthTexture = null;
  35046. this.activeCubeFace = 0;
  35047. this.sampleCount = 1;
  35048. this.width = 0;
  35049. this.height = 0;
  35050. this.isRenderContext = true;
  35051. }
  35052. }
  35053. class RenderContexts {
  35054. constructor() {
  35055. this.chainMaps = {};
  35056. }
  35057. get( scene, camera, renderTarget = null ) {
  35058. const chainKey = [ scene, camera ];
  35059. let attachmentState;
  35060. if ( renderTarget === null ) {
  35061. attachmentState = 'default';
  35062. } else {
  35063. const format = renderTarget.texture.format;
  35064. const count = renderTarget.count;
  35065. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  35066. }
  35067. const chainMap = this.getChainMap( attachmentState );
  35068. let renderState = chainMap.get( chainKey );
  35069. if ( renderState === undefined ) {
  35070. renderState = new RenderContext();
  35071. chainMap.set( chainKey, renderState );
  35072. }
  35073. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  35074. return renderState;
  35075. }
  35076. getChainMap( attachmentState ) {
  35077. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  35078. }
  35079. dispose() {
  35080. this.chainMaps = {};
  35081. }
  35082. }
  35083. const _size = new Vector3();
  35084. class Textures extends DataMap {
  35085. constructor( renderer, backend, info ) {
  35086. super();
  35087. this.renderer = renderer;
  35088. this.backend = backend;
  35089. this.info = info;
  35090. }
  35091. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  35092. const renderTargetData = this.get( renderTarget );
  35093. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  35094. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  35095. const texture = renderTarget.texture;
  35096. const textures = renderTarget.textures;
  35097. const size = this.getSize( texture );
  35098. const mipWidth = size.width >> activeMipmapLevel;
  35099. const mipHeight = size.height >> activeMipmapLevel;
  35100. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  35101. let textureNeedsUpdate = false;
  35102. if ( depthTexture === undefined ) {
  35103. depthTexture = new DepthTexture();
  35104. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  35105. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  35106. depthTexture.image.width = mipWidth;
  35107. depthTexture.image.height = mipHeight;
  35108. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  35109. }
  35110. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  35111. textureNeedsUpdate = true;
  35112. depthTexture.needsUpdate = true;
  35113. depthTexture.image.width = mipWidth;
  35114. depthTexture.image.height = mipHeight;
  35115. }
  35116. renderTargetData.width = size.width;
  35117. renderTargetData.height = size.height;
  35118. renderTargetData.textures = textures;
  35119. renderTargetData.depthTexture = depthTexture;
  35120. renderTargetData.depth = renderTarget.depthBuffer;
  35121. renderTargetData.stencil = renderTarget.stencilBuffer;
  35122. renderTargetData.renderTarget = renderTarget;
  35123. if ( renderTargetData.sampleCount !== sampleCount ) {
  35124. textureNeedsUpdate = true;
  35125. depthTexture.needsUpdate = true;
  35126. renderTargetData.sampleCount = sampleCount;
  35127. }
  35128. //
  35129. const options = { sampleCount };
  35130. for ( let i = 0; i < textures.length; i ++ ) {
  35131. const texture = textures[ i ];
  35132. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  35133. this.updateTexture( texture, options );
  35134. }
  35135. this.updateTexture( depthTexture, options );
  35136. // dispose handler
  35137. if ( renderTargetData.initialized !== true ) {
  35138. renderTargetData.initialized = true;
  35139. // dispose
  35140. const onDispose = () => {
  35141. renderTarget.removeEventListener( 'dispose', onDispose );
  35142. if ( textures !== undefined ) {
  35143. for ( let i = 0; i < textures.length; i ++ ) {
  35144. this._destroyTexture( textures[ i ] );
  35145. }
  35146. } else {
  35147. this._destroyTexture( texture );
  35148. }
  35149. this._destroyTexture( depthTexture );
  35150. };
  35151. renderTarget.addEventListener( 'dispose', onDispose );
  35152. }
  35153. }
  35154. updateTexture( texture, options = {} ) {
  35155. const textureData = this.get( texture );
  35156. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  35157. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  35158. const backend = this.backend;
  35159. if ( isRenderTarget && textureData.initialized === true ) {
  35160. // it's an update
  35161. backend.destroySampler( texture );
  35162. backend.destroyTexture( texture );
  35163. }
  35164. //
  35165. if ( texture.isFramebufferTexture ) {
  35166. const renderer = this.renderer;
  35167. const renderTarget = renderer.getRenderTarget();
  35168. if ( renderTarget ) {
  35169. texture.type = renderTarget.texture.type;
  35170. } else {
  35171. texture.type = UnsignedByteType;
  35172. }
  35173. }
  35174. //
  35175. const { width, height, depth } = this.getSize( texture );
  35176. options.width = width;
  35177. options.height = height;
  35178. options.depth = depth;
  35179. options.needsMipmaps = this.needsMipmaps( texture );
  35180. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  35181. //
  35182. if ( isRenderTarget || texture.isStorageTexture === true ) {
  35183. backend.createSampler( texture );
  35184. backend.createTexture( texture, options );
  35185. } else {
  35186. const needsCreate = textureData.initialized !== true;
  35187. if ( needsCreate ) backend.createSampler( texture );
  35188. if ( texture.version > 0 ) {
  35189. const image = texture.image;
  35190. if ( image === undefined ) {
  35191. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  35192. } else if ( image.complete === false ) {
  35193. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  35194. } else {
  35195. if ( texture.images ) {
  35196. const images = [];
  35197. for ( const image of texture.images ) {
  35198. images.push( image );
  35199. }
  35200. options.images = images;
  35201. } else {
  35202. options.image = image;
  35203. }
  35204. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  35205. backend.createTexture( texture, options );
  35206. textureData.isDefaultTexture = false;
  35207. }
  35208. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  35209. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  35210. }
  35211. } else {
  35212. // async update
  35213. backend.createDefaultTexture( texture );
  35214. textureData.isDefaultTexture = true;
  35215. }
  35216. }
  35217. // dispose handler
  35218. if ( textureData.initialized !== true ) {
  35219. textureData.initialized = true;
  35220. //
  35221. this.info.memory.textures ++;
  35222. // dispose
  35223. const onDispose = () => {
  35224. texture.removeEventListener( 'dispose', onDispose );
  35225. this._destroyTexture( texture );
  35226. this.info.memory.textures --;
  35227. };
  35228. texture.addEventListener( 'dispose', onDispose );
  35229. }
  35230. //
  35231. textureData.version = texture.version;
  35232. }
  35233. getSize( texture, target = _size ) {
  35234. let image = texture.images ? texture.images[ 0 ] : texture.image;
  35235. if ( image ) {
  35236. if ( image.image !== undefined ) image = image.image;
  35237. target.width = image.width;
  35238. target.height = image.height;
  35239. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  35240. } else {
  35241. target.width = target.height = target.depth = 1;
  35242. }
  35243. return target;
  35244. }
  35245. getMipLevels( texture, width, height ) {
  35246. let mipLevelCount;
  35247. if ( texture.isCompressedTexture ) {
  35248. mipLevelCount = texture.mipmaps.length;
  35249. } else {
  35250. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  35251. }
  35252. return mipLevelCount;
  35253. }
  35254. needsMipmaps( texture ) {
  35255. if ( this.isEnvironmentTexture( texture ) ) return true;
  35256. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  35257. }
  35258. isEnvironmentTexture( texture ) {
  35259. const mapping = texture.mapping;
  35260. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  35261. }
  35262. _destroyTexture( texture ) {
  35263. this.backend.destroySampler( texture );
  35264. this.backend.destroyTexture( texture );
  35265. this.delete( texture );
  35266. }
  35267. }
  35268. class Color4 extends Color {
  35269. constructor( r, g, b, a = 1 ) {
  35270. super( r, g, b );
  35271. this.a = a;
  35272. }
  35273. set( r, g, b, a = 1 ) {
  35274. this.a = a;
  35275. return super.set( r, g, b );
  35276. }
  35277. copy( color ) {
  35278. if ( color.a !== undefined ) this.a = color.a;
  35279. return super.copy( color );
  35280. }
  35281. clone() {
  35282. return new this.constructor( this.r, this.g, this.b, this.a );
  35283. }
  35284. }
  35285. const _clearColor = new Color4();
  35286. class Background extends DataMap {
  35287. constructor( renderer, nodes ) {
  35288. super();
  35289. this.renderer = renderer;
  35290. this.nodes = nodes;
  35291. }
  35292. update( scene, renderList, renderContext ) {
  35293. const renderer = this.renderer;
  35294. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  35295. let forceClear = false;
  35296. if ( background === null ) {
  35297. // no background settings, use clear color configuration from the renderer
  35298. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  35299. _clearColor.a = renderer._clearColor.a;
  35300. } else if ( background.isColor === true ) {
  35301. // background is an opaque color
  35302. background.getRGB( _clearColor, LinearSRGBColorSpace );
  35303. _clearColor.a = 1;
  35304. forceClear = true;
  35305. } else if ( background.isNode === true ) {
  35306. const sceneData = this.get( scene );
  35307. const backgroundNode = background;
  35308. _clearColor.copy( renderer._clearColor );
  35309. let backgroundMesh = sceneData.backgroundMesh;
  35310. if ( backgroundMesh === undefined ) {
  35311. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  35312. // @TODO: Add Texture2D support using node context
  35313. getUV: () => normalWorld,
  35314. getTextureLevel: () => backgroundBlurriness
  35315. } );
  35316. let viewProj = modelViewProjection();
  35317. viewProj = viewProj.setZ( viewProj.w );
  35318. const nodeMaterial = new NodeMaterial();
  35319. nodeMaterial.side = BackSide;
  35320. nodeMaterial.depthTest = false;
  35321. nodeMaterial.depthWrite = false;
  35322. nodeMaterial.fog = false;
  35323. nodeMaterial.vertexNode = viewProj;
  35324. nodeMaterial.fragmentNode = backgroundMeshNode;
  35325. sceneData.backgroundMeshNode = backgroundMeshNode;
  35326. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  35327. backgroundMesh.frustumCulled = false;
  35328. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  35329. this.matrixWorld.copyPosition( camera.matrixWorld );
  35330. };
  35331. }
  35332. const backgroundCacheKey = backgroundNode.getCacheKey();
  35333. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  35334. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  35335. backgroundMesh.material.needsUpdate = true;
  35336. sceneData.backgroundCacheKey = backgroundCacheKey;
  35337. }
  35338. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  35339. } else {
  35340. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  35341. }
  35342. //
  35343. if ( renderer.autoClear === true || forceClear === true ) {
  35344. _clearColor.multiplyScalar( _clearColor.a );
  35345. const clearColorValue = renderContext.clearColorValue;
  35346. clearColorValue.r = _clearColor.r;
  35347. clearColorValue.g = _clearColor.g;
  35348. clearColorValue.b = _clearColor.b;
  35349. clearColorValue.a = _clearColor.a;
  35350. renderContext.depthClearValue = renderer._clearDepth;
  35351. renderContext.stencilClearValue = renderer._clearStencil;
  35352. renderContext.clearColor = renderer.autoClearColor === true;
  35353. renderContext.clearDepth = renderer.autoClearDepth === true;
  35354. renderContext.clearStencil = renderer.autoClearStencil === true;
  35355. } else {
  35356. renderContext.clearColor = false;
  35357. renderContext.clearDepth = false;
  35358. renderContext.clearStencil = false;
  35359. }
  35360. }
  35361. }
  35362. class NodeBuilderState {
  35363. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, instanceBindGroups = true, transforms = [] ) {
  35364. this.vertexShader = vertexShader;
  35365. this.fragmentShader = fragmentShader;
  35366. this.computeShader = computeShader;
  35367. this.transforms = transforms;
  35368. this.nodeAttributes = nodeAttributes;
  35369. this.bindings = bindings;
  35370. this.updateNodes = updateNodes;
  35371. this.updateBeforeNodes = updateBeforeNodes;
  35372. this.updateAfterNodes = updateAfterNodes;
  35373. this.instanceBindGroups = instanceBindGroups;
  35374. this.usedTimes = 0;
  35375. }
  35376. createBindings() {
  35377. const bindings = [];
  35378. for ( const instanceGroup of this.bindings ) {
  35379. const shared = this.instanceBindGroups && instanceGroup.bindings[ 0 ].groupNode.shared;
  35380. if ( shared !== true ) {
  35381. const bindingsGroup = new BindGroup( instanceGroup.name );
  35382. bindings.push( bindingsGroup );
  35383. for ( const instanceBinding of instanceGroup.bindings ) {
  35384. bindingsGroup.bindings.push( instanceBinding.clone() );
  35385. }
  35386. } else {
  35387. bindings.push( instanceGroup );
  35388. }
  35389. }
  35390. return bindings;
  35391. }
  35392. }
  35393. const outputNodeMap = new WeakMap();
  35394. class Nodes extends DataMap {
  35395. constructor( renderer, backend ) {
  35396. super();
  35397. this.renderer = renderer;
  35398. this.backend = backend;
  35399. this.nodeFrame = new NodeFrame();
  35400. this.nodeBuilderCache = new Map();
  35401. this.callHashCache = new ChainMap();
  35402. this.groupsData = new ChainMap();
  35403. }
  35404. updateGroup( nodeUniformsGroup ) {
  35405. const groupNode = nodeUniformsGroup.groupNode;
  35406. const name = groupNode.name;
  35407. // objectGroup is every updated
  35408. if ( name === objectGroup.name ) return true;
  35409. // renderGroup is updated once per render/compute call
  35410. if ( name === renderGroup.name ) {
  35411. const uniformsGroupData = this.get( nodeUniformsGroup );
  35412. const renderId = this.nodeFrame.renderId;
  35413. if ( uniformsGroupData.renderId !== renderId ) {
  35414. uniformsGroupData.renderId = renderId;
  35415. return true;
  35416. }
  35417. return false;
  35418. }
  35419. // frameGroup is updated once per frame
  35420. if ( name === frameGroup.name ) {
  35421. const uniformsGroupData = this.get( nodeUniformsGroup );
  35422. const frameId = this.nodeFrame.frameId;
  35423. if ( uniformsGroupData.frameId !== frameId ) {
  35424. uniformsGroupData.frameId = frameId;
  35425. return true;
  35426. }
  35427. return false;
  35428. }
  35429. // other groups are updated just when groupNode.needsUpdate is true
  35430. const groupChain = [ groupNode, nodeUniformsGroup ];
  35431. let groupData = this.groupsData.get( groupChain );
  35432. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  35433. if ( groupData.version !== groupNode.version ) {
  35434. groupData.version = groupNode.version;
  35435. return true;
  35436. }
  35437. return false;
  35438. }
  35439. getForRenderCacheKey( renderObject ) {
  35440. return renderObject.initialCacheKey;
  35441. }
  35442. getForRender( renderObject ) {
  35443. const renderObjectData = this.get( renderObject );
  35444. let nodeBuilderState = renderObjectData.nodeBuilderState;
  35445. if ( nodeBuilderState === undefined ) {
  35446. const { nodeBuilderCache } = this;
  35447. const cacheKey = this.getForRenderCacheKey( renderObject );
  35448. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  35449. if ( nodeBuilderState === undefined ) {
  35450. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  35451. nodeBuilder.scene = renderObject.scene;
  35452. nodeBuilder.material = renderObject.material;
  35453. nodeBuilder.camera = renderObject.camera;
  35454. nodeBuilder.context.material = renderObject.material;
  35455. nodeBuilder.lightsNode = renderObject.lightsNode;
  35456. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  35457. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  35458. nodeBuilder.clippingContext = renderObject.clippingContext;
  35459. nodeBuilder.build();
  35460. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35461. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  35462. }
  35463. nodeBuilderState.usedTimes ++;
  35464. renderObjectData.nodeBuilderState = nodeBuilderState;
  35465. }
  35466. return nodeBuilderState;
  35467. }
  35468. delete( object ) {
  35469. if ( object.isRenderObject ) {
  35470. const nodeBuilderState = this.get( object ).nodeBuilderState;
  35471. nodeBuilderState.usedTimes --;
  35472. if ( nodeBuilderState.usedTimes === 0 ) {
  35473. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  35474. }
  35475. }
  35476. return super.delete( object );
  35477. }
  35478. getForCompute( computeNode ) {
  35479. const computeData = this.get( computeNode );
  35480. let nodeBuilderState = computeData.nodeBuilderState;
  35481. if ( nodeBuilderState === undefined ) {
  35482. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  35483. nodeBuilder.build();
  35484. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35485. computeData.nodeBuilderState = nodeBuilderState;
  35486. }
  35487. return nodeBuilderState;
  35488. }
  35489. _createNodeBuilderState( nodeBuilder ) {
  35490. return new NodeBuilderState(
  35491. nodeBuilder.vertexShader,
  35492. nodeBuilder.fragmentShader,
  35493. nodeBuilder.computeShader,
  35494. nodeBuilder.getAttributesArray(),
  35495. nodeBuilder.getBindings(),
  35496. nodeBuilder.updateNodes,
  35497. nodeBuilder.updateBeforeNodes,
  35498. nodeBuilder.updateAfterNodes,
  35499. nodeBuilder.instanceBindGroups,
  35500. nodeBuilder.transforms
  35501. );
  35502. }
  35503. getEnvironmentNode( scene ) {
  35504. return scene.environmentNode || this.get( scene ).environmentNode || null;
  35505. }
  35506. getBackgroundNode( scene ) {
  35507. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  35508. }
  35509. getFogNode( scene ) {
  35510. return scene.fogNode || this.get( scene ).fogNode || null;
  35511. }
  35512. getCacheKey( scene, lightsNode ) {
  35513. const chain = [ scene, lightsNode ];
  35514. const callId = this.renderer.info.calls;
  35515. let cacheKeyData = this.callHashCache.get( chain );
  35516. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  35517. const environmentNode = this.getEnvironmentNode( scene );
  35518. const fogNode = this.getFogNode( scene );
  35519. const cacheKey = [];
  35520. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey() );
  35521. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  35522. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  35523. cacheKeyData = {
  35524. callId,
  35525. cacheKey: cacheKey.join( ',' )
  35526. };
  35527. this.callHashCache.set( chain, cacheKeyData );
  35528. }
  35529. return cacheKeyData.cacheKey;
  35530. }
  35531. updateScene( scene ) {
  35532. this.updateEnvironment( scene );
  35533. this.updateFog( scene );
  35534. this.updateBackground( scene );
  35535. }
  35536. get isToneMappingState() {
  35537. return this.renderer.getRenderTarget() ? false : true;
  35538. }
  35539. updateBackground( scene ) {
  35540. const sceneData = this.get( scene );
  35541. const background = scene.background;
  35542. if ( background ) {
  35543. if ( sceneData.background !== background ) {
  35544. let backgroundNode = null;
  35545. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping ) ) {
  35546. backgroundNode = pmremTexture( background, normalWorld );
  35547. } else if ( background.isTexture === true ) {
  35548. backgroundNode = texture( background, viewportBottomLeft ).setUpdateMatrix( true );
  35549. } else if ( background.isColor !== true ) {
  35550. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  35551. }
  35552. sceneData.backgroundNode = backgroundNode;
  35553. sceneData.background = background;
  35554. }
  35555. } else if ( sceneData.backgroundNode ) {
  35556. delete sceneData.backgroundNode;
  35557. delete sceneData.background;
  35558. }
  35559. }
  35560. updateFog( scene ) {
  35561. const sceneData = this.get( scene );
  35562. const fog = scene.fog;
  35563. if ( fog ) {
  35564. if ( sceneData.fog !== fog ) {
  35565. let fogNode = null;
  35566. if ( fog.isFogExp2 ) {
  35567. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  35568. } else if ( fog.isFog ) {
  35569. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  35570. } else {
  35571. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  35572. }
  35573. sceneData.fogNode = fogNode;
  35574. sceneData.fog = fog;
  35575. }
  35576. } else {
  35577. delete sceneData.fogNode;
  35578. delete sceneData.fog;
  35579. }
  35580. }
  35581. updateEnvironment( scene ) {
  35582. const sceneData = this.get( scene );
  35583. const environment = scene.environment;
  35584. if ( environment ) {
  35585. if ( sceneData.environment !== environment ) {
  35586. let environmentNode = null;
  35587. if ( environment.isCubeTexture === true ) {
  35588. environmentNode = cubeTexture( environment );
  35589. } else if ( environment.isTexture === true ) {
  35590. environmentNode = texture( environment );
  35591. } else {
  35592. console.error( 'Nodes: Unsupported environment configuration.', environment );
  35593. }
  35594. sceneData.environmentNode = environmentNode;
  35595. sceneData.environment = environment;
  35596. }
  35597. } else if ( sceneData.environmentNode ) {
  35598. delete sceneData.environmentNode;
  35599. delete sceneData.environment;
  35600. }
  35601. }
  35602. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  35603. const nodeFrame = this.nodeFrame;
  35604. nodeFrame.renderer = renderer;
  35605. nodeFrame.scene = scene;
  35606. nodeFrame.object = object;
  35607. nodeFrame.camera = camera;
  35608. nodeFrame.material = material;
  35609. return nodeFrame;
  35610. }
  35611. getNodeFrameForRender( renderObject ) {
  35612. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  35613. }
  35614. getOutputCacheKey() {
  35615. const renderer = this.renderer;
  35616. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  35617. }
  35618. hasOutputChange( outputTarget ) {
  35619. const cacheKey = outputNodeMap.get( outputTarget );
  35620. return cacheKey !== this.getOutputCacheKey();
  35621. }
  35622. getOutputNode( outputTexture ) {
  35623. const renderer = this.renderer;
  35624. const cacheKey = this.getOutputCacheKey();
  35625. const output = texture( outputTexture, viewportTopLeft ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  35626. outputNodeMap.set( outputTexture, cacheKey );
  35627. return output;
  35628. }
  35629. updateBefore( renderObject ) {
  35630. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35631. const nodeBuilder = renderObject.getNodeBuilderState();
  35632. for ( const node of nodeBuilder.updateBeforeNodes ) {
  35633. nodeFrame.updateBeforeNode( node );
  35634. }
  35635. }
  35636. updateAfter( renderObject ) {
  35637. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35638. const nodeBuilder = renderObject.getNodeBuilderState();
  35639. for ( const node of nodeBuilder.updateAfterNodes ) {
  35640. nodeFrame.updateAfterNode( node );
  35641. }
  35642. }
  35643. updateForCompute( computeNode ) {
  35644. const nodeFrame = this.getNodeFrame();
  35645. const nodeBuilder = this.getForCompute( computeNode );
  35646. for ( const node of nodeBuilder.updateNodes ) {
  35647. nodeFrame.updateNode( node );
  35648. }
  35649. }
  35650. updateForRender( renderObject ) {
  35651. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35652. const nodeBuilder = renderObject.getNodeBuilderState();
  35653. for ( const node of nodeBuilder.updateNodes ) {
  35654. nodeFrame.updateNode( node );
  35655. }
  35656. }
  35657. dispose() {
  35658. super.dispose();
  35659. this.nodeFrame = new NodeFrame();
  35660. this.nodeBuilderCache = new Map();
  35661. }
  35662. }
  35663. class RenderBundle {
  35664. constructor( scene, camera ) {
  35665. this.scene = scene;
  35666. this.camera = camera;
  35667. }
  35668. clone() {
  35669. return Object.assign( new this.constructor(), this );
  35670. }
  35671. }
  35672. class RenderBundles {
  35673. constructor() {
  35674. this.lists = new ChainMap();
  35675. }
  35676. get( scene, camera ) {
  35677. const lists = this.lists;
  35678. const keys = [ scene, camera ];
  35679. let list = lists.get( keys );
  35680. if ( list === undefined ) {
  35681. list = new RenderBundle( scene, camera );
  35682. lists.set( keys, list );
  35683. }
  35684. return list;
  35685. }
  35686. dispose() {
  35687. this.lists = new ChainMap();
  35688. }
  35689. }
  35690. const _scene = new Scene();
  35691. const _drawingBufferSize = new Vector2();
  35692. const _screen = new Vector4();
  35693. const _frustum = new Frustum();
  35694. const _projScreenMatrix = new Matrix4();
  35695. const _vector3 = new Vector3();
  35696. class Renderer {
  35697. constructor( backend, parameters = {} ) {
  35698. this.isRenderer = true;
  35699. //
  35700. const {
  35701. logarithmicDepthBuffer = false,
  35702. alpha = true,
  35703. antialias = false,
  35704. samples = 0
  35705. } = parameters;
  35706. // public
  35707. this.domElement = backend.getDomElement();
  35708. this.backend = backend;
  35709. this.samples = samples || ( antialias === true ) ? 4 : 0;
  35710. this.autoClear = true;
  35711. this.autoClearColor = true;
  35712. this.autoClearDepth = true;
  35713. this.autoClearStencil = true;
  35714. this.alpha = alpha;
  35715. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  35716. this.outputColorSpace = SRGBColorSpace;
  35717. this.toneMapping = NoToneMapping;
  35718. this.toneMappingExposure = 1.0;
  35719. this.sortObjects = true;
  35720. this.depth = true;
  35721. this.stencil = false;
  35722. this.clippingPlanes = [];
  35723. this.info = new Info();
  35724. // internals
  35725. this._pixelRatio = 1;
  35726. this._width = this.domElement.width;
  35727. this._height = this.domElement.height;
  35728. this._viewport = new Vector4( 0, 0, this._width, this._height );
  35729. this._scissor = new Vector4( 0, 0, this._width, this._height );
  35730. this._scissorTest = false;
  35731. this._attributes = null;
  35732. this._geometries = null;
  35733. this._nodes = null;
  35734. this._animation = null;
  35735. this._bindings = null;
  35736. this._objects = null;
  35737. this._pipelines = null;
  35738. this._bundles = null;
  35739. this._renderLists = null;
  35740. this._renderContexts = null;
  35741. this._textures = null;
  35742. this._background = null;
  35743. this._quad = new QuadMesh( new NodeMaterial() );
  35744. this._currentRenderContext = null;
  35745. this._opaqueSort = null;
  35746. this._transparentSort = null;
  35747. this._frameBufferTarget = null;
  35748. const alphaClear = this.alpha === true ? 0 : 1;
  35749. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  35750. this._clearDepth = 1;
  35751. this._clearStencil = 0;
  35752. this._renderTarget = null;
  35753. this._activeCubeFace = 0;
  35754. this._activeMipmapLevel = 0;
  35755. this._renderObjectFunction = null;
  35756. this._currentRenderObjectFunction = null;
  35757. this._currentRenderBundle = null;
  35758. this._handleObjectFunction = this._renderObjectDirect;
  35759. this._initialized = false;
  35760. this._initPromise = null;
  35761. this._compilationPromises = null;
  35762. // backwards compatibility
  35763. this.shadowMap = {
  35764. enabled: false,
  35765. type: null
  35766. };
  35767. this.xr = {
  35768. enabled: false
  35769. };
  35770. this.debug = {
  35771. checkShaderErrors: true,
  35772. onShaderError: null
  35773. };
  35774. }
  35775. async init() {
  35776. if ( this._initialized ) {
  35777. throw new Error( 'Renderer: Backend has already been initialized.' );
  35778. }
  35779. if ( this._initPromise !== null ) {
  35780. return this._initPromise;
  35781. }
  35782. this._initPromise = new Promise( async ( resolve, reject ) => {
  35783. const backend = this.backend;
  35784. try {
  35785. await backend.init( this );
  35786. } catch ( error ) {
  35787. reject( error );
  35788. return;
  35789. }
  35790. this._nodes = new Nodes( this, backend );
  35791. this._animation = new Animation( this._nodes, this.info );
  35792. this._attributes = new Attributes( backend );
  35793. this._background = new Background( this, this._nodes );
  35794. this._geometries = new Geometries( this._attributes, this.info );
  35795. this._textures = new Textures( this, backend, this.info );
  35796. this._pipelines = new Pipelines( backend, this._nodes );
  35797. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35798. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35799. this._renderLists = new RenderLists();
  35800. this._bundles = new RenderBundles();
  35801. this._renderContexts = new RenderContexts();
  35802. //
  35803. this._initialized = true;
  35804. resolve();
  35805. } );
  35806. return this._initPromise;
  35807. }
  35808. get coordinateSystem() {
  35809. return this.backend.coordinateSystem;
  35810. }
  35811. async compileAsync( scene, camera, targetScene = null ) {
  35812. if ( this._initialized === false ) await this.init();
  35813. // preserve render tree
  35814. const nodeFrame = this._nodes.nodeFrame;
  35815. const previousRenderId = nodeFrame.renderId;
  35816. const previousRenderContext = this._currentRenderContext;
  35817. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35818. const previousCompilationPromises = this._compilationPromises;
  35819. //
  35820. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35821. if ( targetScene === null ) targetScene = scene;
  35822. const renderTarget = this._renderTarget;
  35823. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  35824. const activeMipmapLevel = this._activeMipmapLevel;
  35825. const compilationPromises = [];
  35826. this._currentRenderContext = renderContext;
  35827. this._currentRenderObjectFunction = this.renderObject;
  35828. this._handleObjectFunction = this._createObjectPipeline;
  35829. this._compilationPromises = compilationPromises;
  35830. nodeFrame.renderId ++;
  35831. //
  35832. nodeFrame.update();
  35833. //
  35834. renderContext.depth = this.depth;
  35835. renderContext.stencil = this.stencil;
  35836. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35837. renderContext.clippingContext.updateGlobal( this, camera );
  35838. //
  35839. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35840. //
  35841. const renderList = this._renderLists.get( scene, camera );
  35842. renderList.begin();
  35843. this._projectObject( scene, camera, 0, renderList );
  35844. // include lights from target scene
  35845. if ( targetScene !== scene ) {
  35846. targetScene.traverseVisible( function ( object ) {
  35847. if ( object.isLight && object.layers.test( camera.layers ) ) {
  35848. renderList.pushLight( object );
  35849. }
  35850. } );
  35851. }
  35852. renderList.finish();
  35853. //
  35854. if ( renderTarget !== null ) {
  35855. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35856. const renderTargetData = this._textures.get( renderTarget );
  35857. renderContext.textures = renderTargetData.textures;
  35858. renderContext.depthTexture = renderTargetData.depthTexture;
  35859. } else {
  35860. renderContext.textures = null;
  35861. renderContext.depthTexture = null;
  35862. }
  35863. //
  35864. this._nodes.updateScene( sceneRef );
  35865. //
  35866. this._background.update( sceneRef, renderList, renderContext );
  35867. // process render lists
  35868. const opaqueObjects = renderList.opaque;
  35869. const transparentObjects = renderList.transparent;
  35870. const lightsNode = renderList.lightsNode;
  35871. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35872. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  35873. // restore render tree
  35874. nodeFrame.renderId = previousRenderId;
  35875. this._currentRenderContext = previousRenderContext;
  35876. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35877. this._compilationPromises = previousCompilationPromises;
  35878. this._handleObjectFunction = this._renderObjectDirect;
  35879. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  35880. await Promise.all( compilationPromises );
  35881. }
  35882. async renderAsync( scene, camera ) {
  35883. if ( this._initialized === false ) await this.init();
  35884. const renderContext = this._renderScene( scene, camera );
  35885. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  35886. }
  35887. _renderBundle( bundle, sceneRef, lightsNode ) {
  35888. const { object, camera, renderList } = bundle;
  35889. const renderContext = this._currentRenderContext;
  35890. const renderContextData = this.backend.get( renderContext );
  35891. //
  35892. const renderBundle = this._bundles.get( object, camera );
  35893. const renderBundleData = this.backend.get( renderBundle );
  35894. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  35895. //
  35896. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || object.needsUpdate === true;
  35897. renderBundleData.renderContexts.add( renderContext );
  35898. if ( renderBundleNeedsUpdate ) {
  35899. if ( renderContextData.renderObjects === undefined || object.needsUpdate === true ) {
  35900. const nodeFrame = this._nodes.nodeFrame;
  35901. renderContextData.renderObjects = [];
  35902. renderContextData.renderBundles = [];
  35903. renderContextData.scene = sceneRef;
  35904. renderContextData.camera = camera;
  35905. renderContextData.renderId = nodeFrame.renderId;
  35906. renderContextData.registerBundlesPhase = true;
  35907. }
  35908. this._currentRenderBundle = renderBundle;
  35909. const opaqueObjects = renderList.opaque;
  35910. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35911. this._currentRenderBundle = null;
  35912. //
  35913. object.needsUpdate = false;
  35914. } else {
  35915. const renderContext = this._currentRenderContext;
  35916. const renderContextData = this.backend.get( renderContext );
  35917. for ( let i = 0, l = renderContextData.renderObjects.length; i < l; i ++ ) {
  35918. const renderObject = renderContextData.renderObjects[ i ];
  35919. this._nodes.updateBefore( renderObject );
  35920. //
  35921. renderObject.object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, renderObject.object.matrixWorld );
  35922. renderObject.object.normalMatrix.getNormalMatrix( renderObject.object.modelViewMatrix );
  35923. this._nodes.updateForRender( renderObject );
  35924. this._bindings.updateForRender( renderObject );
  35925. this.backend.draw( renderObject, this.info );
  35926. this._nodes.updateAfter( renderObject );
  35927. }
  35928. }
  35929. }
  35930. render( scene, camera ) {
  35931. if ( this._initialized === false ) {
  35932. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  35933. return this.renderAsync( scene, camera );
  35934. }
  35935. this._renderScene( scene, camera );
  35936. }
  35937. _getFrameBufferTarget() {
  35938. const { currentColorSpace } = this;
  35939. const useToneMapping = this._renderTarget === null && ( this.toneMapping !== NoToneMapping );
  35940. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace && currentColorSpace !== NoColorSpace;
  35941. if ( useToneMapping === false && useColorSpace === false ) return null;
  35942. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  35943. const { depth, stencil } = this;
  35944. let frameBufferTarget = this._frameBufferTarget;
  35945. if ( frameBufferTarget === null ) {
  35946. frameBufferTarget = new RenderTarget( width, height, {
  35947. depthBuffer: depth,
  35948. stencilBuffer: stencil,
  35949. type: HalfFloatType, // FloatType
  35950. format: RGBAFormat,
  35951. colorSpace: LinearSRGBColorSpace,
  35952. generateMipmaps: false,
  35953. minFilter: LinearFilter,
  35954. magFilter: LinearFilter,
  35955. samples: this.samples
  35956. } );
  35957. frameBufferTarget.isPostProcessingRenderTarget = true;
  35958. this._frameBufferTarget = frameBufferTarget;
  35959. }
  35960. frameBufferTarget.depthBuffer = depth;
  35961. frameBufferTarget.stencilBuffer = stencil;
  35962. frameBufferTarget.setSize( width, height );
  35963. frameBufferTarget.viewport.copy( this._viewport );
  35964. frameBufferTarget.scissor.copy( this._scissor );
  35965. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  35966. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  35967. frameBufferTarget.scissorTest = this._scissorTest;
  35968. return frameBufferTarget;
  35969. }
  35970. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  35971. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  35972. // preserve render tree
  35973. const nodeFrame = this._nodes.nodeFrame;
  35974. const previousRenderId = nodeFrame.renderId;
  35975. const previousRenderContext = this._currentRenderContext;
  35976. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35977. //
  35978. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35979. const outputRenderTarget = this._renderTarget;
  35980. const activeCubeFace = this._activeCubeFace;
  35981. const activeMipmapLevel = this._activeMipmapLevel;
  35982. //
  35983. let renderTarget;
  35984. if ( frameBufferTarget !== null ) {
  35985. renderTarget = frameBufferTarget;
  35986. this.setRenderTarget( renderTarget );
  35987. } else {
  35988. renderTarget = outputRenderTarget;
  35989. }
  35990. //
  35991. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  35992. this._currentRenderContext = renderContext;
  35993. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  35994. //
  35995. this.info.calls ++;
  35996. this.info.render.calls ++;
  35997. this.info.render.frameCalls ++;
  35998. nodeFrame.renderId = this.info.calls;
  35999. //
  36000. const coordinateSystem = this.coordinateSystem;
  36001. if ( camera.coordinateSystem !== coordinateSystem ) {
  36002. camera.coordinateSystem = coordinateSystem;
  36003. camera.updateProjectionMatrix();
  36004. }
  36005. //
  36006. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  36007. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  36008. //
  36009. let viewport = this._viewport;
  36010. let scissor = this._scissor;
  36011. let pixelRatio = this._pixelRatio;
  36012. if ( renderTarget !== null ) {
  36013. viewport = renderTarget.viewport;
  36014. scissor = renderTarget.scissor;
  36015. pixelRatio = 1;
  36016. }
  36017. this.getDrawingBufferSize( _drawingBufferSize );
  36018. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  36019. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  36020. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  36021. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  36022. renderContext.viewportValue.width >>= activeMipmapLevel;
  36023. renderContext.viewportValue.height >>= activeMipmapLevel;
  36024. renderContext.viewportValue.minDepth = minDepth;
  36025. renderContext.viewportValue.maxDepth = maxDepth;
  36026. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  36027. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  36028. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  36029. renderContext.scissorValue.width >>= activeMipmapLevel;
  36030. renderContext.scissorValue.height >>= activeMipmapLevel;
  36031. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36032. renderContext.clippingContext.updateGlobal( this, camera );
  36033. //
  36034. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36035. //
  36036. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  36037. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  36038. const renderList = this._renderLists.get( scene, camera );
  36039. renderList.begin();
  36040. this._projectObject( scene, camera, 0, renderList );
  36041. renderList.finish();
  36042. if ( this.sortObjects === true ) {
  36043. renderList.sort( this._opaqueSort, this._transparentSort );
  36044. }
  36045. //
  36046. if ( renderTarget !== null ) {
  36047. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36048. const renderTargetData = this._textures.get( renderTarget );
  36049. renderContext.textures = renderTargetData.textures;
  36050. renderContext.depthTexture = renderTargetData.depthTexture;
  36051. renderContext.width = renderTargetData.width;
  36052. renderContext.height = renderTargetData.height;
  36053. renderContext.renderTarget = renderTarget;
  36054. renderContext.depth = renderTarget.depthBuffer;
  36055. renderContext.stencil = renderTarget.stencilBuffer;
  36056. } else {
  36057. renderContext.textures = null;
  36058. renderContext.depthTexture = null;
  36059. renderContext.width = this.domElement.width;
  36060. renderContext.height = this.domElement.height;
  36061. renderContext.depth = this.depth;
  36062. renderContext.stencil = this.stencil;
  36063. }
  36064. renderContext.width >>= activeMipmapLevel;
  36065. renderContext.height >>= activeMipmapLevel;
  36066. renderContext.activeCubeFace = activeCubeFace;
  36067. renderContext.activeMipmapLevel = activeMipmapLevel;
  36068. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  36069. //
  36070. this._nodes.updateScene( sceneRef );
  36071. //
  36072. this._background.update( sceneRef, renderList, renderContext );
  36073. //
  36074. this.backend.beginRender( renderContext );
  36075. // process render lists
  36076. const opaqueObjects = renderList.opaque;
  36077. const transparentObjects = renderList.transparent;
  36078. const bundles = renderList.bundles;
  36079. const lightsNode = renderList.lightsNode;
  36080. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  36081. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36082. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  36083. // finish render pass
  36084. this.backend.finishRender( renderContext );
  36085. // restore render tree
  36086. nodeFrame.renderId = previousRenderId;
  36087. this._currentRenderContext = previousRenderContext;
  36088. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36089. //
  36090. if ( frameBufferTarget !== null ) {
  36091. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  36092. const quad = this._quad;
  36093. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  36094. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36095. quad.material.needsUpdate = true;
  36096. }
  36097. this._renderScene( quad, quad.camera, false );
  36098. }
  36099. //
  36100. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  36101. //
  36102. return renderContext;
  36103. }
  36104. getMaxAnisotropy() {
  36105. return this.backend.getMaxAnisotropy();
  36106. }
  36107. getActiveCubeFace() {
  36108. return this._activeCubeFace;
  36109. }
  36110. getActiveMipmapLevel() {
  36111. return this._activeMipmapLevel;
  36112. }
  36113. async setAnimationLoop( callback ) {
  36114. if ( this._initialized === false ) await this.init();
  36115. this._animation.setAnimationLoop( callback );
  36116. }
  36117. async getArrayBufferAsync( attribute ) {
  36118. return await this.backend.getArrayBufferAsync( attribute );
  36119. }
  36120. getContext() {
  36121. return this.backend.getContext();
  36122. }
  36123. getPixelRatio() {
  36124. return this._pixelRatio;
  36125. }
  36126. getDrawingBufferSize( target ) {
  36127. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  36128. }
  36129. getSize( target ) {
  36130. return target.set( this._width, this._height );
  36131. }
  36132. setPixelRatio( value = 1 ) {
  36133. this._pixelRatio = value;
  36134. this.setSize( this._width, this._height, false );
  36135. }
  36136. setDrawingBufferSize( width, height, pixelRatio ) {
  36137. this._width = width;
  36138. this._height = height;
  36139. this._pixelRatio = pixelRatio;
  36140. this.domElement.width = Math.floor( width * pixelRatio );
  36141. this.domElement.height = Math.floor( height * pixelRatio );
  36142. this.setViewport( 0, 0, width, height );
  36143. if ( this._initialized ) this.backend.updateSize();
  36144. }
  36145. setSize( width, height, updateStyle = true ) {
  36146. this._width = width;
  36147. this._height = height;
  36148. this.domElement.width = Math.floor( width * this._pixelRatio );
  36149. this.domElement.height = Math.floor( height * this._pixelRatio );
  36150. if ( updateStyle === true ) {
  36151. this.domElement.style.width = width + 'px';
  36152. this.domElement.style.height = height + 'px';
  36153. }
  36154. this.setViewport( 0, 0, width, height );
  36155. if ( this._initialized ) this.backend.updateSize();
  36156. }
  36157. setOpaqueSort( method ) {
  36158. this._opaqueSort = method;
  36159. }
  36160. setTransparentSort( method ) {
  36161. this._transparentSort = method;
  36162. }
  36163. getScissor( target ) {
  36164. const scissor = this._scissor;
  36165. target.x = scissor.x;
  36166. target.y = scissor.y;
  36167. target.width = scissor.width;
  36168. target.height = scissor.height;
  36169. return target;
  36170. }
  36171. setScissor( x, y, width, height ) {
  36172. const scissor = this._scissor;
  36173. if ( x.isVector4 ) {
  36174. scissor.copy( x );
  36175. } else {
  36176. scissor.set( x, y, width, height );
  36177. }
  36178. }
  36179. getScissorTest() {
  36180. return this._scissorTest;
  36181. }
  36182. setScissorTest( boolean ) {
  36183. this._scissorTest = boolean;
  36184. this.backend.setScissorTest( boolean );
  36185. }
  36186. getViewport( target ) {
  36187. return target.copy( this._viewport );
  36188. }
  36189. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  36190. const viewport = this._viewport;
  36191. if ( x.isVector4 ) {
  36192. viewport.copy( x );
  36193. } else {
  36194. viewport.set( x, y, width, height );
  36195. }
  36196. viewport.minDepth = minDepth;
  36197. viewport.maxDepth = maxDepth;
  36198. }
  36199. getClearColor( target ) {
  36200. return target.copy( this._clearColor );
  36201. }
  36202. setClearColor( color, alpha = 1 ) {
  36203. this._clearColor.set( color );
  36204. this._clearColor.a = alpha;
  36205. }
  36206. getClearAlpha() {
  36207. return this._clearColor.a;
  36208. }
  36209. setClearAlpha( alpha ) {
  36210. this._clearColor.a = alpha;
  36211. }
  36212. getClearDepth() {
  36213. return this._clearDepth;
  36214. }
  36215. setClearDepth( depth ) {
  36216. this._clearDepth = depth;
  36217. }
  36218. getClearStencil() {
  36219. return this._clearStencil;
  36220. }
  36221. setClearStencil( stencil ) {
  36222. this._clearStencil = stencil;
  36223. }
  36224. isOccluded( object ) {
  36225. const renderContext = this._currentRenderContext;
  36226. return renderContext && this.backend.isOccluded( renderContext, object );
  36227. }
  36228. clear( color = true, depth = true, stencil = true ) {
  36229. if ( this._initialized === false ) {
  36230. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  36231. return this.clearAsync( color, depth, stencil );
  36232. }
  36233. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36234. let renderTargetData = null;
  36235. if ( renderTarget !== null ) {
  36236. this._textures.updateRenderTarget( renderTarget );
  36237. renderTargetData = this._textures.get( renderTarget );
  36238. }
  36239. this.backend.clear( color, depth, stencil, renderTargetData );
  36240. if ( renderTarget !== null && this._renderTarget === null ) {
  36241. // If a color space transform or tone mapping is required,
  36242. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  36243. const quad = this._quad;
  36244. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  36245. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36246. quad.material.needsUpdate = true;
  36247. }
  36248. this._renderScene( quad, quad.camera, false );
  36249. }
  36250. }
  36251. clearColor() {
  36252. return this.clear( true, false, false );
  36253. }
  36254. clearDepth() {
  36255. return this.clear( false, true, false );
  36256. }
  36257. clearStencil() {
  36258. return this.clear( false, false, true );
  36259. }
  36260. async clearAsync( color = true, depth = true, stencil = true ) {
  36261. if ( this._initialized === false ) await this.init();
  36262. this.clear( color, depth, stencil );
  36263. }
  36264. clearColorAsync() {
  36265. return this.clearAsync( true, false, false );
  36266. }
  36267. clearDepthAsync() {
  36268. return this.clearAsync( false, true, false );
  36269. }
  36270. clearStencilAsync() {
  36271. return this.clearAsync( false, false, true );
  36272. }
  36273. get currentColorSpace() {
  36274. const renderTarget = this._renderTarget;
  36275. if ( renderTarget !== null ) {
  36276. const texture = renderTarget.texture;
  36277. return ( Array.isArray( texture ) ? texture[ 0 ] : texture ).colorSpace;
  36278. }
  36279. return this.outputColorSpace;
  36280. }
  36281. dispose() {
  36282. this.info.dispose();
  36283. this._animation.dispose();
  36284. this._objects.dispose();
  36285. this._pipelines.dispose();
  36286. this._nodes.dispose();
  36287. this._bindings.dispose();
  36288. this._renderLists.dispose();
  36289. this._renderContexts.dispose();
  36290. this._textures.dispose();
  36291. this.setRenderTarget( null );
  36292. this.setAnimationLoop( null );
  36293. }
  36294. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  36295. this._renderTarget = renderTarget;
  36296. this._activeCubeFace = activeCubeFace;
  36297. this._activeMipmapLevel = activeMipmapLevel;
  36298. }
  36299. getRenderTarget() {
  36300. return this._renderTarget;
  36301. }
  36302. setRenderObjectFunction( renderObjectFunction ) {
  36303. this._renderObjectFunction = renderObjectFunction;
  36304. }
  36305. getRenderObjectFunction() {
  36306. return this._renderObjectFunction;
  36307. }
  36308. async computeAsync( computeNodes ) {
  36309. if ( this._initialized === false ) await this.init();
  36310. const nodeFrame = this._nodes.nodeFrame;
  36311. const previousRenderId = nodeFrame.renderId;
  36312. //
  36313. this.info.calls ++;
  36314. this.info.compute.calls ++;
  36315. this.info.compute.frameCalls ++;
  36316. nodeFrame.renderId = this.info.calls;
  36317. //
  36318. const backend = this.backend;
  36319. const pipelines = this._pipelines;
  36320. const bindings = this._bindings;
  36321. const nodes = this._nodes;
  36322. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36323. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36324. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36325. }
  36326. backend.beginCompute( computeNodes );
  36327. for ( const computeNode of computeList ) {
  36328. // onInit
  36329. if ( pipelines.has( computeNode ) === false ) {
  36330. const dispose = () => {
  36331. computeNode.removeEventListener( 'dispose', dispose );
  36332. pipelines.delete( computeNode );
  36333. bindings.delete( computeNode );
  36334. nodes.delete( computeNode );
  36335. };
  36336. computeNode.addEventListener( 'dispose', dispose );
  36337. //
  36338. computeNode.onInit( { renderer: this } );
  36339. }
  36340. nodes.updateForCompute( computeNode );
  36341. bindings.updateForCompute( computeNode );
  36342. const computeBindings = bindings.getForCompute( computeNode );
  36343. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  36344. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  36345. }
  36346. backend.finishCompute( computeNodes );
  36347. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  36348. //
  36349. nodeFrame.renderId = previousRenderId;
  36350. }
  36351. async hasFeatureAsync( name ) {
  36352. if ( this._initialized === false ) await this.init();
  36353. return this.backend.hasFeature( name );
  36354. }
  36355. hasFeature( name ) {
  36356. if ( this._initialized === false ) {
  36357. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  36358. return false;
  36359. }
  36360. return this.backend.hasFeature( name );
  36361. }
  36362. copyFramebufferToTexture( framebufferTexture ) {
  36363. const renderContext = this._currentRenderContext;
  36364. this._textures.updateTexture( framebufferTexture );
  36365. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  36366. }
  36367. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  36368. this._textures.updateTexture( srcTexture );
  36369. this._textures.updateTexture( dstTexture );
  36370. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  36371. }
  36372. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0 ) {
  36373. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height );
  36374. }
  36375. _projectObject( object, camera, groupOrder, renderList ) {
  36376. if ( object.visible === false ) return;
  36377. const visible = object.layers.test( camera.layers );
  36378. if ( visible ) {
  36379. if ( object.isGroup ) {
  36380. groupOrder = object.renderOrder;
  36381. } else if ( object.isLOD ) {
  36382. if ( object.autoUpdate === true ) object.update( camera );
  36383. } else if ( object.isLight ) {
  36384. renderList.pushLight( object );
  36385. } else if ( object.isSprite ) {
  36386. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  36387. if ( this.sortObjects === true ) {
  36388. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  36389. }
  36390. const geometry = object.geometry;
  36391. const material = object.material;
  36392. if ( material.visible ) {
  36393. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36394. }
  36395. }
  36396. } else if ( object.isLineLoop ) {
  36397. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  36398. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  36399. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  36400. const geometry = object.geometry;
  36401. const material = object.material;
  36402. if ( this.sortObjects === true ) {
  36403. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  36404. _vector3
  36405. .copy( geometry.boundingSphere.center )
  36406. .applyMatrix4( object.matrixWorld )
  36407. .applyMatrix4( _projScreenMatrix );
  36408. }
  36409. if ( Array.isArray( material ) ) {
  36410. const groups = geometry.groups;
  36411. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  36412. const group = groups[ i ];
  36413. const groupMaterial = material[ group.materialIndex ];
  36414. if ( groupMaterial && groupMaterial.visible ) {
  36415. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  36416. }
  36417. }
  36418. } else if ( material.visible ) {
  36419. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36420. }
  36421. }
  36422. }
  36423. }
  36424. if ( object.static === true ) {
  36425. const baseRenderList = renderList;
  36426. // replace render list
  36427. renderList = this._renderLists.get( object, camera );
  36428. renderList.begin();
  36429. baseRenderList.pushBundle( {
  36430. object,
  36431. camera,
  36432. renderList,
  36433. } );
  36434. renderList.finish();
  36435. }
  36436. const children = object.children;
  36437. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36438. this._projectObject( children[ i ], camera, groupOrder, renderList );
  36439. }
  36440. }
  36441. _renderBundles( bundles, sceneRef, lightsNode ) {
  36442. for ( const bundle of bundles ) {
  36443. this._renderBundle( bundle, sceneRef, lightsNode );
  36444. }
  36445. }
  36446. _renderObjects( renderList, camera, scene, lightsNode ) {
  36447. // process renderable objects
  36448. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36449. const renderItem = renderList[ i ];
  36450. // @TODO: Add support for multiple materials per object. This will require to extract
  36451. // the material from the renderItem object and pass it with its group data to renderObject().
  36452. const { object, geometry, material, group } = renderItem;
  36453. if ( camera.isArrayCamera ) {
  36454. const cameras = camera.cameras;
  36455. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  36456. const camera2 = cameras[ j ];
  36457. if ( object.layers.test( camera2.layers ) ) {
  36458. const vp = camera2.viewport;
  36459. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  36460. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  36461. const viewportValue = this._currentRenderContext.viewportValue;
  36462. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  36463. viewportValue.minDepth = minDepth;
  36464. viewportValue.maxDepth = maxDepth;
  36465. this.backend.updateViewport( this._currentRenderContext );
  36466. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  36467. }
  36468. }
  36469. } else {
  36470. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  36471. }
  36472. }
  36473. }
  36474. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  36475. let overridePositionNode;
  36476. let overrideFragmentNode;
  36477. let overrideDepthNode;
  36478. //
  36479. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36480. //
  36481. if ( scene.overrideMaterial !== null ) {
  36482. const overrideMaterial = scene.overrideMaterial;
  36483. if ( material.positionNode && material.positionNode.isNode ) {
  36484. overridePositionNode = overrideMaterial.positionNode;
  36485. overrideMaterial.positionNode = material.positionNode;
  36486. }
  36487. if ( overrideMaterial.isShadowNodeMaterial ) {
  36488. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36489. if ( material.depthNode && material.depthNode.isNode ) {
  36490. overrideDepthNode = overrideMaterial.depthNode;
  36491. overrideMaterial.depthNode = material.depthNode;
  36492. }
  36493. if ( material.shadowNode && material.shadowNode.isNode ) {
  36494. overrideFragmentNode = overrideMaterial.fragmentNode;
  36495. overrideMaterial.fragmentNode = material.shadowNode;
  36496. }
  36497. if ( this.localClippingEnabled ) {
  36498. if ( material.clipShadows ) {
  36499. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  36500. overrideMaterial.clippingPlanes = material.clippingPlanes;
  36501. overrideMaterial.needsUpdate = true;
  36502. }
  36503. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  36504. overrideMaterial.clipIntersection = material.clipIntersection;
  36505. }
  36506. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  36507. overrideMaterial.clippingPlanes = null;
  36508. overrideMaterial.needsUpdate = true;
  36509. }
  36510. }
  36511. }
  36512. material = overrideMaterial;
  36513. }
  36514. //
  36515. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36516. material.side = BackSide;
  36517. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  36518. material.side = FrontSide;
  36519. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  36520. material.side = DoubleSide;
  36521. } else {
  36522. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  36523. }
  36524. //
  36525. if ( overridePositionNode !== undefined ) {
  36526. scene.overrideMaterial.positionNode = overridePositionNode;
  36527. }
  36528. if ( overrideDepthNode !== undefined ) {
  36529. scene.overrideMaterial.depthNode = overrideDepthNode;
  36530. }
  36531. if ( overrideFragmentNode !== undefined ) {
  36532. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  36533. }
  36534. //
  36535. object.onAfterRender( this, scene, camera, geometry, material, group );
  36536. }
  36537. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  36538. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36539. renderObject.drawRange = group || object.geometry.drawRange;
  36540. //
  36541. this._nodes.updateBefore( renderObject );
  36542. //
  36543. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  36544. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  36545. //
  36546. this._nodes.updateForRender( renderObject );
  36547. this._geometries.updateForRender( renderObject );
  36548. this._bindings.updateForRender( renderObject );
  36549. this._pipelines.updateForRender( renderObject );
  36550. //
  36551. if ( this._currentRenderBundle !== null && this._currentRenderBundle.needsUpdate === true ) {
  36552. const renderObjectData = this.backend.get( renderObject );
  36553. renderObjectData.bundleEncoder = undefined;
  36554. renderObjectData.lastPipelineGPU = undefined;
  36555. }
  36556. this.backend.draw( renderObject, this.info );
  36557. if ( this._currentRenderBundle !== null ) {
  36558. const renderContextData = this.backend.get( this._currentRenderContext );
  36559. renderContextData.renderObjects.push( renderObject );
  36560. }
  36561. this._nodes.updateAfter( renderObject );
  36562. }
  36563. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  36564. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36565. //
  36566. this._nodes.updateBefore( renderObject );
  36567. //
  36568. this._nodes.updateForRender( renderObject );
  36569. this._geometries.updateForRender( renderObject );
  36570. this._bindings.updateForRender( renderObject );
  36571. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36572. this._nodes.updateAfter( renderObject );
  36573. }
  36574. get compute() {
  36575. return this.computeAsync;
  36576. }
  36577. get compile() {
  36578. return this.compileAsync;
  36579. }
  36580. }
  36581. class Binding {
  36582. constructor( name = '' ) {
  36583. this.name = name;
  36584. this.visibility = 0;
  36585. }
  36586. setVisibility( visibility ) {
  36587. this.visibility |= visibility;
  36588. }
  36589. clone() {
  36590. return Object.assign( new this.constructor(), this );
  36591. }
  36592. }
  36593. function getFloatLength( floatLength ) {
  36594. // ensure chunk size alignment (STD140 layout)
  36595. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36596. }
  36597. class Buffer extends Binding {
  36598. constructor( name, buffer = null ) {
  36599. super( name );
  36600. this.isBuffer = true;
  36601. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36602. this._buffer = buffer;
  36603. }
  36604. get byteLength() {
  36605. return getFloatLength( this._buffer.byteLength );
  36606. }
  36607. get buffer() {
  36608. return this._buffer;
  36609. }
  36610. update() {
  36611. return true;
  36612. }
  36613. }
  36614. class UniformBuffer extends Buffer {
  36615. constructor( name, buffer = null ) {
  36616. super( name, buffer );
  36617. this.isUniformBuffer = true;
  36618. }
  36619. }
  36620. let _id$2 = 0;
  36621. class NodeUniformBuffer extends UniformBuffer {
  36622. constructor( nodeUniform, groupNode ) {
  36623. super( 'UniformBuffer_' + _id$2 ++, nodeUniform ? nodeUniform.value : null );
  36624. this.nodeUniform = nodeUniform;
  36625. this.groupNode = groupNode;
  36626. }
  36627. get buffer() {
  36628. return this.nodeUniform.value;
  36629. }
  36630. }
  36631. class UniformsGroup extends UniformBuffer {
  36632. constructor( name ) {
  36633. super( name );
  36634. this.isUniformsGroup = true;
  36635. this._values = null;
  36636. // the order of uniforms in this array must match the order of uniforms in the shader
  36637. this.uniforms = [];
  36638. }
  36639. addUniform( uniform ) {
  36640. this.uniforms.push( uniform );
  36641. return this;
  36642. }
  36643. removeUniform( uniform ) {
  36644. const index = this.uniforms.indexOf( uniform );
  36645. if ( index !== - 1 ) {
  36646. this.uniforms.splice( index, 1 );
  36647. }
  36648. return this;
  36649. }
  36650. get values() {
  36651. if ( this._values === null ) {
  36652. this._values = Array.from( this.buffer );
  36653. }
  36654. return this._values;
  36655. }
  36656. get buffer() {
  36657. let buffer = this._buffer;
  36658. if ( buffer === null ) {
  36659. const byteLength = this.byteLength;
  36660. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36661. this._buffer = buffer;
  36662. }
  36663. return buffer;
  36664. }
  36665. get byteLength() {
  36666. let offset = 0; // global buffer offset in bytes
  36667. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36668. const uniform = this.uniforms[ i ];
  36669. const { boundary, itemSize } = uniform;
  36670. // offset within a single chunk in bytes
  36671. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36672. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36673. // conformance tests
  36674. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36675. // check for chunk overflow
  36676. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36677. } else if ( chunkOffset % boundary !== 0 ) {
  36678. // check for correct alignment
  36679. offset += ( chunkOffset % boundary );
  36680. }
  36681. uniform.offset = ( offset / this.bytesPerElement );
  36682. offset += ( itemSize * this.bytesPerElement );
  36683. }
  36684. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36685. }
  36686. update() {
  36687. let updated = false;
  36688. for ( const uniform of this.uniforms ) {
  36689. if ( this.updateByType( uniform ) === true ) {
  36690. updated = true;
  36691. }
  36692. }
  36693. return updated;
  36694. }
  36695. updateByType( uniform ) {
  36696. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36697. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36698. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36699. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36700. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36701. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36702. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36703. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36704. }
  36705. updateNumber( uniform ) {
  36706. let updated = false;
  36707. const a = this.values;
  36708. const v = uniform.getValue();
  36709. const offset = uniform.offset;
  36710. if ( a[ offset ] !== v ) {
  36711. const b = this.buffer;
  36712. b[ offset ] = a[ offset ] = v;
  36713. updated = true;
  36714. }
  36715. return updated;
  36716. }
  36717. updateVector2( uniform ) {
  36718. let updated = false;
  36719. const a = this.values;
  36720. const v = uniform.getValue();
  36721. const offset = uniform.offset;
  36722. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36723. const b = this.buffer;
  36724. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36725. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36726. updated = true;
  36727. }
  36728. return updated;
  36729. }
  36730. updateVector3( uniform ) {
  36731. let updated = false;
  36732. const a = this.values;
  36733. const v = uniform.getValue();
  36734. const offset = uniform.offset;
  36735. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36736. const b = this.buffer;
  36737. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36738. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36739. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36740. updated = true;
  36741. }
  36742. return updated;
  36743. }
  36744. updateVector4( uniform ) {
  36745. let updated = false;
  36746. const a = this.values;
  36747. const v = uniform.getValue();
  36748. const offset = uniform.offset;
  36749. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36750. const b = this.buffer;
  36751. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36752. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36753. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36754. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36755. updated = true;
  36756. }
  36757. return updated;
  36758. }
  36759. updateColor( uniform ) {
  36760. let updated = false;
  36761. const a = this.values;
  36762. const c = uniform.getValue();
  36763. const offset = uniform.offset;
  36764. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36765. const b = this.buffer;
  36766. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36767. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36768. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36769. updated = true;
  36770. }
  36771. return updated;
  36772. }
  36773. updateMatrix3( uniform ) {
  36774. let updated = false;
  36775. const a = this.values;
  36776. const e = uniform.getValue().elements;
  36777. const offset = uniform.offset;
  36778. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36779. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36780. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36781. const b = this.buffer;
  36782. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36783. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36784. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36785. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36786. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36787. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36788. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36789. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36790. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36791. updated = true;
  36792. }
  36793. return updated;
  36794. }
  36795. updateMatrix4( uniform ) {
  36796. let updated = false;
  36797. const a = this.values;
  36798. const e = uniform.getValue().elements;
  36799. const offset = uniform.offset;
  36800. if ( arraysEqual( a, e, offset ) === false ) {
  36801. const b = this.buffer;
  36802. b.set( e, offset );
  36803. setArray( a, e, offset );
  36804. updated = true;
  36805. }
  36806. return updated;
  36807. }
  36808. }
  36809. function setArray( a, b, offset ) {
  36810. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36811. a[ offset + i ] = b[ i ];
  36812. }
  36813. }
  36814. function arraysEqual( a, b, offset ) {
  36815. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36816. if ( a[ offset + i ] !== b[ i ] ) return false;
  36817. }
  36818. return true;
  36819. }
  36820. let id$1 = 0;
  36821. class NodeUniformsGroup extends UniformsGroup {
  36822. constructor( name, groupNode ) {
  36823. super( name );
  36824. this.id = id$1 ++;
  36825. this.groupNode = groupNode;
  36826. this.isNodeUniformsGroup = true;
  36827. }
  36828. getNodes() {
  36829. const nodes = [];
  36830. for ( const uniform of this.uniforms ) {
  36831. const node = uniform.nodeUniform.node;
  36832. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  36833. nodes.push( node );
  36834. }
  36835. return nodes;
  36836. }
  36837. }
  36838. let id = 0;
  36839. class SampledTexture extends Binding {
  36840. constructor( name, texture ) {
  36841. super( name );
  36842. this.id = id ++;
  36843. this.texture = texture;
  36844. this.version = texture ? texture.version : 0;
  36845. this.store = false;
  36846. this.isSampledTexture = true;
  36847. }
  36848. get needsBindingsUpdate() {
  36849. const { texture, version } = this;
  36850. return texture.isVideoTexture ? true : version !== texture.version; // @TODO: version === 0 && texture.version > 0 ( add it just to External Textures like PNG,JPG )
  36851. }
  36852. update() {
  36853. const { texture, version } = this;
  36854. if ( version !== texture.version ) {
  36855. this.version = texture.version;
  36856. return true;
  36857. }
  36858. return false;
  36859. }
  36860. }
  36861. class NodeSampledTexture extends SampledTexture {
  36862. constructor( name, textureNode, groupNode, access = null ) {
  36863. super( name, textureNode ? textureNode.value : null );
  36864. this.textureNode = textureNode;
  36865. this.groupNode = groupNode;
  36866. this.access = access;
  36867. }
  36868. get needsBindingsUpdate() {
  36869. return this.textureNode.value !== this.texture || super.needsBindingsUpdate;
  36870. }
  36871. update() {
  36872. const { textureNode } = this;
  36873. if ( this.texture !== textureNode.value ) {
  36874. this.texture = textureNode.value;
  36875. return true;
  36876. }
  36877. return super.update();
  36878. }
  36879. }
  36880. class NodeSampledCubeTexture extends NodeSampledTexture {
  36881. constructor( name, textureNode, groupNode, access ) {
  36882. super( name, textureNode, groupNode, access );
  36883. this.isSampledCubeTexture = true;
  36884. }
  36885. }
  36886. class NodeSampledTexture3D extends NodeSampledTexture {
  36887. constructor( name, textureNode, groupNode, access ) {
  36888. super( name, textureNode, groupNode, access );
  36889. this.isSampledTexture3D = true;
  36890. }
  36891. }
  36892. const glslMethods = {
  36893. [ MathNode.ATAN2 ]: 'atan',
  36894. textureDimensions: 'textureSize',
  36895. equals: 'equal'
  36896. };
  36897. const precisionLib = {
  36898. low: 'lowp',
  36899. medium: 'mediump',
  36900. high: 'highp'
  36901. };
  36902. const supports$1 = {
  36903. swizzleAssign: true,
  36904. storageBuffer: false
  36905. };
  36906. const defaultPrecisions = `
  36907. precision highp float;
  36908. precision highp int;
  36909. precision highp sampler2D;
  36910. precision highp sampler3D;
  36911. precision highp samplerCube;
  36912. precision highp sampler2DArray;
  36913. precision highp usampler2D;
  36914. precision highp usampler3D;
  36915. precision highp usamplerCube;
  36916. precision highp usampler2DArray;
  36917. precision highp isampler2D;
  36918. precision highp isampler3D;
  36919. precision highp isamplerCube;
  36920. precision highp isampler2DArray;
  36921. precision lowp sampler2DShadow;
  36922. `;
  36923. class GLSLNodeBuilder extends NodeBuilder {
  36924. constructor( object, renderer ) {
  36925. super( object, renderer, new GLSLNodeParser() );
  36926. this.uniformGroups = {};
  36927. this.transforms = [];
  36928. this.instanceBindGroups = false;
  36929. }
  36930. getMethod( method ) {
  36931. return glslMethods[ method ] || method;
  36932. }
  36933. getOutputStructName() {
  36934. return '';
  36935. }
  36936. buildFunctionCode( shaderNode ) {
  36937. const layout = shaderNode.layout;
  36938. const flowData = this.flowShaderNode( shaderNode );
  36939. const parameters = [];
  36940. for ( const input of layout.inputs ) {
  36941. parameters.push( this.getType( input.type ) + ' ' + input.name );
  36942. }
  36943. //
  36944. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  36945. ${ flowData.vars }
  36946. ${ flowData.code }
  36947. return ${ flowData.result };
  36948. }`;
  36949. //
  36950. return code;
  36951. }
  36952. setupPBO( storageBufferNode ) {
  36953. const attribute = storageBufferNode.value;
  36954. if ( attribute.pbo === undefined ) {
  36955. const originalArray = attribute.array;
  36956. const numElements = attribute.count * attribute.itemSize;
  36957. const { itemSize } = attribute;
  36958. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  36959. let format = isInteger ? RedIntegerFormat : RedFormat;
  36960. if ( itemSize === 2 ) {
  36961. format = isInteger ? RGIntegerFormat : RGFormat;
  36962. } else if ( itemSize === 3 ) {
  36963. format = isInteger ? RGBIntegerFormat : RGBFormat;
  36964. } else if ( itemSize === 4 ) {
  36965. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  36966. }
  36967. const typeMap = {
  36968. Float32Array: FloatType,
  36969. Uint8Array: UnsignedByteType,
  36970. Uint16Array: UnsignedShortType,
  36971. Uint32Array: UnsignedIntType,
  36972. Int8Array: ByteType,
  36973. Int16Array: ShortType,
  36974. Int32Array: IntType,
  36975. Uint8ClampedArray: UnsignedByteType,
  36976. };
  36977. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  36978. let height = Math.ceil( ( numElements / itemSize ) / width );
  36979. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  36980. const newSize = width * height * itemSize;
  36981. const newArray = new originalArray.constructor( newSize );
  36982. newArray.set( originalArray, 0 );
  36983. attribute.array = newArray;
  36984. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  36985. pboTexture.needsUpdate = true;
  36986. pboTexture.isPBOTexture = true;
  36987. const pbo = new TextureNode( pboTexture, null, null );
  36988. pbo.setPrecision( 'high' );
  36989. attribute.pboNode = pbo;
  36990. attribute.pbo = pbo.value;
  36991. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36992. }
  36993. }
  36994. getPropertyName( node, shaderStage = this.shaderStage ) {
  36995. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  36996. return shaderStage.charAt( 0 ) + '_' + node.name;
  36997. }
  36998. return super.getPropertyName( node, shaderStage );
  36999. }
  37000. generatePBO( storageArrayElementNode ) {
  37001. const { node, indexNode } = storageArrayElementNode;
  37002. const attribute = node.value;
  37003. if ( this.renderer.backend.has( attribute ) ) {
  37004. const attributeData = this.renderer.backend.get( attribute );
  37005. attributeData.pbo = attribute.pbo;
  37006. }
  37007. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37008. const textureName = this.getPropertyName( nodeUniform );
  37009. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  37010. const indexSnippet = indexNode.build( this, 'uint' );
  37011. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  37012. let propertyName = elementNodeData.propertyName;
  37013. if ( propertyName === undefined ) {
  37014. // property element
  37015. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  37016. propertyName = this.getPropertyName( nodeVar );
  37017. // property size
  37018. const bufferNodeData = this.getDataFromNode( node );
  37019. let propertySizeName = bufferNodeData.propertySizeName;
  37020. if ( propertySizeName === undefined ) {
  37021. propertySizeName = propertyName + 'Size';
  37022. this.getVarFromNode( node, propertySizeName, 'uint' );
  37023. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  37024. bufferNodeData.propertySizeName = propertySizeName;
  37025. }
  37026. //
  37027. const { itemSize } = attribute;
  37028. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  37029. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  37030. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  37031. //
  37032. let prefix = 'vec4';
  37033. if ( attribute.pbo.type === UnsignedIntType ) {
  37034. prefix = 'uvec4';
  37035. } else if ( attribute.pbo.type === IntType ) {
  37036. prefix = 'ivec4';
  37037. }
  37038. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  37039. elementNodeData.propertyName = propertyName;
  37040. }
  37041. return propertyName;
  37042. }
  37043. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  37044. if ( depthSnippet ) {
  37045. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  37046. } else {
  37047. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  37048. }
  37049. }
  37050. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  37051. if ( texture.isDepthTexture ) {
  37052. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  37053. } else {
  37054. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  37055. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  37056. }
  37057. }
  37058. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  37059. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  37060. }
  37061. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  37062. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  37063. }
  37064. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  37065. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  37066. }
  37067. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  37068. if ( shaderStage === 'fragment' ) {
  37069. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  37070. } else {
  37071. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  37072. }
  37073. }
  37074. getVars( shaderStage ) {
  37075. const snippets = [];
  37076. const vars = this.vars[ shaderStage ];
  37077. if ( vars !== undefined ) {
  37078. for ( const variable of vars ) {
  37079. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  37080. }
  37081. }
  37082. return snippets.join( '\n\t' );
  37083. }
  37084. getUniforms( shaderStage ) {
  37085. const uniforms = this.uniforms[ shaderStage ];
  37086. const bindingSnippets = [];
  37087. const uniformGroups = {};
  37088. for ( const uniform of uniforms ) {
  37089. let snippet = null;
  37090. let group = false;
  37091. if ( uniform.type === 'texture' ) {
  37092. const texture = uniform.node.value;
  37093. let typePrefix = '';
  37094. if ( texture.isDataTexture === true ) {
  37095. if ( texture.type === UnsignedIntType ) {
  37096. typePrefix = 'u';
  37097. } else if ( texture.type === IntType ) {
  37098. typePrefix = 'i';
  37099. }
  37100. }
  37101. if ( texture.compareFunction ) {
  37102. snippet = `sampler2DShadow ${ uniform.name };`;
  37103. } else if ( texture.isDataArrayTexture === true ) {
  37104. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  37105. } else {
  37106. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  37107. }
  37108. } else if ( uniform.type === 'cubeTexture' ) {
  37109. snippet = `samplerCube ${ uniform.name };`;
  37110. } else if ( uniform.type === 'texture3D' ) {
  37111. snippet = `sampler3D ${ uniform.name };`;
  37112. } else if ( uniform.type === 'buffer' ) {
  37113. const bufferNode = uniform.node;
  37114. const bufferType = this.getType( bufferNode.bufferType );
  37115. const bufferCount = bufferNode.bufferCount;
  37116. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  37117. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  37118. } else {
  37119. const vectorType = this.getVectorType( uniform.type );
  37120. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  37121. group = true;
  37122. }
  37123. const precision = uniform.node.precision;
  37124. if ( precision !== null ) {
  37125. snippet = precisionLib[ precision ] + ' ' + snippet;
  37126. }
  37127. if ( group ) {
  37128. snippet = '\t' + snippet;
  37129. const groupName = uniform.groupNode.name;
  37130. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  37131. groupSnippets.push( snippet );
  37132. } else {
  37133. snippet = 'uniform ' + snippet;
  37134. bindingSnippets.push( snippet );
  37135. }
  37136. }
  37137. let output = '';
  37138. for ( const name in uniformGroups ) {
  37139. const groupSnippets = uniformGroups[ name ];
  37140. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37141. }
  37142. output += bindingSnippets.join( '\n' );
  37143. return output;
  37144. }
  37145. getTypeFromAttribute( attribute ) {
  37146. let nodeType = super.getTypeFromAttribute( attribute );
  37147. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37148. let dataAttribute = attribute;
  37149. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37150. const array = dataAttribute.array;
  37151. if ( ( array instanceof Uint32Array || array instanceof Int32Array || array instanceof Uint16Array || array instanceof Int16Array ) === false ) {
  37152. nodeType = nodeType.slice( 1 );
  37153. }
  37154. }
  37155. return nodeType;
  37156. }
  37157. getAttributes( shaderStage ) {
  37158. let snippet = '';
  37159. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37160. const attributes = this.getAttributesArray();
  37161. let location = 0;
  37162. for ( const attribute of attributes ) {
  37163. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37164. }
  37165. }
  37166. return snippet;
  37167. }
  37168. getStructMembers( struct ) {
  37169. const snippets = [];
  37170. const members = struct.getMemberTypes();
  37171. for ( let i = 0; i < members.length; i ++ ) {
  37172. const member = members[ i ];
  37173. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  37174. }
  37175. return snippets.join( '\n' );
  37176. }
  37177. getStructs( shaderStage ) {
  37178. const snippets = [];
  37179. const structs = this.structs[ shaderStage ];
  37180. if ( structs.length === 0 ) {
  37181. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37182. }
  37183. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37184. const struct = structs[ index ];
  37185. let snippet = '\n';
  37186. snippet += this.getStructMembers( struct );
  37187. snippet += '\n';
  37188. snippets.push( snippet );
  37189. }
  37190. return snippets.join( '\n\n' );
  37191. }
  37192. getVaryings( shaderStage ) {
  37193. let snippet = '';
  37194. const varyings = this.varyings;
  37195. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37196. for ( const varying of varyings ) {
  37197. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37198. const type = varying.type;
  37199. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37200. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37201. }
  37202. } else if ( shaderStage === 'fragment' ) {
  37203. for ( const varying of varyings ) {
  37204. if ( varying.needsInterpolation ) {
  37205. const type = varying.type;
  37206. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37207. snippet += `${flat}in ${type} ${varying.name};\n`;
  37208. }
  37209. }
  37210. }
  37211. return snippet;
  37212. }
  37213. getVertexIndex() {
  37214. return 'uint( gl_VertexID )';
  37215. }
  37216. getInstanceIndex() {
  37217. return 'uint( gl_InstanceID )';
  37218. }
  37219. getDrawIndex() {
  37220. const extensions = this.renderer.backend.extensions;
  37221. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37222. return 'uint( gl_DrawID )';
  37223. }
  37224. return null;
  37225. }
  37226. getFrontFacing() {
  37227. return 'gl_FrontFacing';
  37228. }
  37229. getFragCoord() {
  37230. return 'gl_FragCoord';
  37231. }
  37232. getFragDepth() {
  37233. return 'gl_FragDepth';
  37234. }
  37235. getExtensions( shaderStage ) {
  37236. let extensions = '';
  37237. if ( shaderStage === 'vertex' ) {
  37238. const ext = this.renderer.backend.extensions;
  37239. const isBatchedMesh = this.object.isBatchedMesh;
  37240. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37241. extensions += '#extension GL_ANGLE_multi_draw : require\n';
  37242. }
  37243. }
  37244. return extensions;
  37245. }
  37246. isAvailable( name ) {
  37247. let result = supports$1[ name ];
  37248. if ( result === undefined ) {
  37249. if ( name === 'float32Filterable' ) {
  37250. const extensions = this.renderer.backend.extensions;
  37251. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  37252. extensions.get( 'OES_texture_float_linear' );
  37253. result = true;
  37254. } else {
  37255. result = false;
  37256. }
  37257. }
  37258. supports$1[ name ] = result;
  37259. }
  37260. return result;
  37261. }
  37262. isFlipY() {
  37263. return true;
  37264. }
  37265. registerTransform( varyingName, attributeNode ) {
  37266. this.transforms.push( { varyingName, attributeNode } );
  37267. }
  37268. getTransforms( /* shaderStage */ ) {
  37269. const transforms = this.transforms;
  37270. let snippet = '';
  37271. for ( let i = 0; i < transforms.length; i ++ ) {
  37272. const transform = transforms[ i ];
  37273. const attributeName = this.getPropertyName( transform.attributeNode );
  37274. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37275. }
  37276. return snippet;
  37277. }
  37278. _getGLSLUniformStruct( name, vars ) {
  37279. return `
  37280. layout( std140 ) uniform ${name} {
  37281. ${vars}
  37282. };`;
  37283. }
  37284. _getGLSLVertexCode( shaderData ) {
  37285. return `#version 300 es
  37286. // extensions
  37287. ${shaderData.extensions}
  37288. // precision
  37289. ${ defaultPrecisions }
  37290. // uniforms
  37291. ${shaderData.uniforms}
  37292. // varyings
  37293. ${shaderData.varyings}
  37294. // attributes
  37295. ${shaderData.attributes}
  37296. // codes
  37297. ${shaderData.codes}
  37298. void main() {
  37299. // vars
  37300. ${shaderData.vars}
  37301. // transforms
  37302. ${shaderData.transforms}
  37303. // flow
  37304. ${shaderData.flow}
  37305. gl_PointSize = 1.0;
  37306. }
  37307. `;
  37308. }
  37309. _getGLSLFragmentCode( shaderData ) {
  37310. return `#version 300 es
  37311. ${ this.getSignature() }
  37312. // precision
  37313. ${ defaultPrecisions }
  37314. // uniforms
  37315. ${shaderData.uniforms}
  37316. // varyings
  37317. ${shaderData.varyings}
  37318. // codes
  37319. ${shaderData.codes}
  37320. ${shaderData.structs}
  37321. void main() {
  37322. // vars
  37323. ${shaderData.vars}
  37324. // flow
  37325. ${shaderData.flow}
  37326. }
  37327. `;
  37328. }
  37329. buildCode() {
  37330. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37331. for ( const shaderStage in shadersData ) {
  37332. let flow = '// code\n\n';
  37333. flow += this.flowCode[ shaderStage ];
  37334. const flowNodes = this.flowNodes[ shaderStage ];
  37335. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37336. for ( const node of flowNodes ) {
  37337. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37338. const slotName = node.name;
  37339. if ( slotName ) {
  37340. if ( flow.length > 0 ) flow += '\n';
  37341. flow += `\t// flow -> ${ slotName }\n\t`;
  37342. }
  37343. flow += `${ flowSlotData.code }\n\t`;
  37344. if ( node === mainNode && shaderStage !== 'compute' ) {
  37345. flow += '// result\n\t';
  37346. if ( shaderStage === 'vertex' ) {
  37347. flow += 'gl_Position = ';
  37348. flow += `${ flowSlotData.result };`;
  37349. } else if ( shaderStage === 'fragment' ) {
  37350. if ( ! node.outputNode.isOutputStructNode ) {
  37351. flow += 'fragColor = ';
  37352. flow += `${ flowSlotData.result };`;
  37353. }
  37354. }
  37355. }
  37356. }
  37357. const stageData = shadersData[ shaderStage ];
  37358. stageData.extensions = this.getExtensions( shaderStage );
  37359. stageData.uniforms = this.getUniforms( shaderStage );
  37360. stageData.attributes = this.getAttributes( shaderStage );
  37361. stageData.varyings = this.getVaryings( shaderStage );
  37362. stageData.vars = this.getVars( shaderStage );
  37363. stageData.structs = this.getStructs( shaderStage );
  37364. stageData.codes = this.getCodes( shaderStage );
  37365. stageData.transforms = this.getTransforms( shaderStage );
  37366. stageData.flow = flow;
  37367. }
  37368. if ( this.material !== null ) {
  37369. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37370. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37371. } else {
  37372. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37373. }
  37374. }
  37375. getUniformFromNode( node, type, shaderStage, name = null ) {
  37376. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37377. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37378. let uniformGPU = nodeData.uniformGPU;
  37379. if ( uniformGPU === undefined ) {
  37380. const group = node.groupNode;
  37381. const groupName = group.name;
  37382. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37383. if ( type === 'texture' ) {
  37384. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37385. bindings.push( uniformGPU );
  37386. } else if ( type === 'cubeTexture' ) {
  37387. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37388. bindings.push( uniformGPU );
  37389. } else if ( type === 'texture3D' ) {
  37390. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37391. bindings.push( uniformGPU );
  37392. } else if ( type === 'buffer' ) {
  37393. node.name = `NodeBuffer_${ node.id }`;
  37394. uniformNode.name = `buffer${ node.id }`;
  37395. const buffer = new NodeUniformBuffer( node, group );
  37396. buffer.name = node.name;
  37397. bindings.push( buffer );
  37398. uniformGPU = buffer;
  37399. } else {
  37400. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37401. let uniformsGroup = uniformsStage[ groupName ];
  37402. if ( uniformsGroup === undefined ) {
  37403. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37404. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37405. uniformsStage[ groupName ] = uniformsGroup;
  37406. bindings.push( uniformsGroup );
  37407. }
  37408. uniformGPU = this.getNodeUniform( uniformNode, type );
  37409. uniformsGroup.addUniform( uniformGPU );
  37410. }
  37411. nodeData.uniformGPU = uniformGPU;
  37412. }
  37413. return uniformNode;
  37414. }
  37415. }
  37416. let vector2 = null;
  37417. let vector4 = null;
  37418. let color4 = null;
  37419. class Backend {
  37420. constructor( parameters = {} ) {
  37421. this.parameters = Object.assign( {}, parameters );
  37422. this.data = new WeakMap();
  37423. this.renderer = null;
  37424. this.domElement = null;
  37425. }
  37426. async init( renderer ) {
  37427. this.renderer = renderer;
  37428. }
  37429. // render context
  37430. begin( /*renderContext*/ ) { }
  37431. finish( /*renderContext*/ ) { }
  37432. // render object
  37433. draw( /*renderObject, info*/ ) { }
  37434. // program
  37435. createProgram( /*program*/ ) { }
  37436. destroyProgram( /*program*/ ) { }
  37437. // bindings
  37438. createBindings( /*renderObject*/ ) { }
  37439. updateBindings( /*renderObject*/ ) { }
  37440. // pipeline
  37441. createRenderPipeline( /*renderObject*/ ) { }
  37442. createComputePipeline( /*computeNode, pipeline*/ ) { }
  37443. destroyPipeline( /*pipeline*/ ) { }
  37444. // cache key
  37445. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  37446. getRenderCacheKey( /*renderObject*/ ) { } // return String
  37447. // node builder
  37448. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  37449. // textures
  37450. createSampler( /*texture*/ ) { }
  37451. createDefaultTexture( /*texture*/ ) { }
  37452. createTexture( /*texture*/ ) { }
  37453. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  37454. // attributes
  37455. createAttribute( /*attribute*/ ) { }
  37456. createIndexAttribute( /*attribute*/ ) { }
  37457. updateAttribute( /*attribute*/ ) { }
  37458. destroyAttribute( /*attribute*/ ) { }
  37459. // canvas
  37460. getContext() { }
  37461. updateSize() { }
  37462. // utils
  37463. resolveTimestampAsync( /*renderContext, type*/ ) { }
  37464. hasFeatureAsync( /*name*/ ) { } // return Boolean
  37465. hasFeature( /*name*/ ) { } // return Boolean
  37466. getInstanceCount( renderObject ) {
  37467. const { object, geometry } = renderObject;
  37468. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  37469. }
  37470. getDrawingBufferSize() {
  37471. vector2 = vector2 || new Vector2();
  37472. return this.renderer.getDrawingBufferSize( vector2 );
  37473. }
  37474. getScissor() {
  37475. vector4 = vector4 || new Vector4();
  37476. return this.renderer.getScissor( vector4 );
  37477. }
  37478. setScissorTest( /*boolean*/ ) { }
  37479. getClearColor() {
  37480. const renderer = this.renderer;
  37481. color4 = color4 || new Color4();
  37482. renderer.getClearColor( color4 );
  37483. color4.getRGB( color4, this.renderer.currentColorSpace );
  37484. return color4;
  37485. }
  37486. getDomElement() {
  37487. let domElement = this.domElement;
  37488. if ( domElement === null ) {
  37489. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  37490. // OffscreenCanvas does not have setAttribute, see #22811
  37491. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  37492. this.domElement = domElement;
  37493. }
  37494. return domElement;
  37495. }
  37496. // resource properties
  37497. set( object, value ) {
  37498. this.data.set( object, value );
  37499. }
  37500. get( object ) {
  37501. let map = this.data.get( object );
  37502. if ( map === undefined ) {
  37503. map = {};
  37504. this.data.set( object, map );
  37505. }
  37506. return map;
  37507. }
  37508. has( object ) {
  37509. return this.data.has( object );
  37510. }
  37511. delete( object ) {
  37512. this.data.delete( object );
  37513. }
  37514. }
  37515. let _id$1 = 0;
  37516. class DualAttributeData {
  37517. constructor( attributeData, dualBuffer ) {
  37518. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  37519. this.type = attributeData.type;
  37520. this.bufferType = attributeData.bufferType;
  37521. this.pbo = attributeData.pbo;
  37522. this.byteLength = attributeData.byteLength;
  37523. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  37524. this.version = attributeData.version;
  37525. this.isInteger = attributeData.isInteger;
  37526. this.activeBufferIndex = 0;
  37527. this.baseId = attributeData.id;
  37528. }
  37529. get id() {
  37530. return `${ this.baseId }|${ this.activeBufferIndex }`;
  37531. }
  37532. get bufferGPU() {
  37533. return this.buffers[ this.activeBufferIndex ];
  37534. }
  37535. get transformBuffer() {
  37536. return this.buffers[ this.activeBufferIndex ^ 1 ];
  37537. }
  37538. switchBuffers() {
  37539. this.activeBufferIndex ^= 1;
  37540. }
  37541. }
  37542. class WebGLAttributeUtils {
  37543. constructor( backend ) {
  37544. this.backend = backend;
  37545. }
  37546. createAttribute( attribute, bufferType ) {
  37547. const backend = this.backend;
  37548. const { gl } = backend;
  37549. const array = attribute.array;
  37550. const usage = attribute.usage || gl.STATIC_DRAW;
  37551. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37552. const bufferData = backend.get( bufferAttribute );
  37553. let bufferGPU = bufferData.bufferGPU;
  37554. if ( bufferGPU === undefined ) {
  37555. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  37556. bufferData.bufferGPU = bufferGPU;
  37557. bufferData.bufferType = bufferType;
  37558. bufferData.version = bufferAttribute.version;
  37559. }
  37560. //attribute.onUploadCallback();
  37561. let type;
  37562. if ( array instanceof Float32Array ) {
  37563. type = gl.FLOAT;
  37564. } else if ( array instanceof Uint16Array ) {
  37565. if ( attribute.isFloat16BufferAttribute ) {
  37566. type = gl.HALF_FLOAT;
  37567. } else {
  37568. type = gl.UNSIGNED_SHORT;
  37569. }
  37570. } else if ( array instanceof Int16Array ) {
  37571. type = gl.SHORT;
  37572. } else if ( array instanceof Uint32Array ) {
  37573. type = gl.UNSIGNED_INT;
  37574. } else if ( array instanceof Int32Array ) {
  37575. type = gl.INT;
  37576. } else if ( array instanceof Int8Array ) {
  37577. type = gl.BYTE;
  37578. } else if ( array instanceof Uint8Array ) {
  37579. type = gl.UNSIGNED_BYTE;
  37580. } else if ( array instanceof Uint8ClampedArray ) {
  37581. type = gl.UNSIGNED_BYTE;
  37582. } else {
  37583. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  37584. }
  37585. let attributeData = {
  37586. bufferGPU,
  37587. bufferType,
  37588. type,
  37589. byteLength: array.byteLength,
  37590. bytesPerElement: array.BYTES_PER_ELEMENT,
  37591. version: attribute.version,
  37592. pbo: attribute.pbo,
  37593. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || type === gl.UNSIGNED_SHORT || attribute.gpuType === IntType,
  37594. id: _id$1 ++
  37595. };
  37596. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  37597. // create buffer for tranform feedback use
  37598. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  37599. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  37600. }
  37601. backend.set( attribute, attributeData );
  37602. }
  37603. updateAttribute( attribute ) {
  37604. const backend = this.backend;
  37605. const { gl } = backend;
  37606. const array = attribute.array;
  37607. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37608. const bufferData = backend.get( bufferAttribute );
  37609. const bufferType = bufferData.bufferType;
  37610. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  37611. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  37612. if ( updateRanges.length === 0 ) {
  37613. // Not using update ranges
  37614. gl.bufferSubData( bufferType, 0, array );
  37615. } else {
  37616. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  37617. const range = updateRanges[ i ];
  37618. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  37619. array, range.start, range.count );
  37620. }
  37621. bufferAttribute.clearUpdateRanges();
  37622. }
  37623. gl.bindBuffer( bufferType, null );
  37624. bufferData.version = bufferAttribute.version;
  37625. }
  37626. destroyAttribute( attribute ) {
  37627. const backend = this.backend;
  37628. const { gl } = backend;
  37629. if ( attribute.isInterleavedBufferAttribute ) {
  37630. backend.delete( attribute.data );
  37631. }
  37632. const attributeData = backend.get( attribute );
  37633. gl.deleteBuffer( attributeData.bufferGPU );
  37634. backend.delete( attribute );
  37635. }
  37636. async getArrayBufferAsync( attribute ) {
  37637. const backend = this.backend;
  37638. const { gl } = backend;
  37639. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37640. const { bufferGPU } = backend.get( bufferAttribute );
  37641. const array = attribute.array;
  37642. const byteLength = array.byteLength;
  37643. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  37644. const writeBuffer = gl.createBuffer();
  37645. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  37646. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  37647. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  37648. await backend.utils._clientWaitAsync();
  37649. const dstBuffer = new attribute.array.constructor( array.length );
  37650. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  37651. gl.deleteBuffer( writeBuffer );
  37652. return dstBuffer.buffer;
  37653. }
  37654. _createBuffer( gl, bufferType, array, usage ) {
  37655. const bufferGPU = gl.createBuffer();
  37656. gl.bindBuffer( bufferType, bufferGPU );
  37657. gl.bufferData( bufferType, array, usage );
  37658. gl.bindBuffer( bufferType, null );
  37659. return bufferGPU;
  37660. }
  37661. }
  37662. let initialized$1 = false, equationToGL, factorToGL;
  37663. class WebGLState {
  37664. constructor( backend ) {
  37665. this.backend = backend;
  37666. this.gl = this.backend.gl;
  37667. this.enabled = {};
  37668. this.currentFlipSided = null;
  37669. this.currentCullFace = null;
  37670. this.currentProgram = null;
  37671. this.currentBlendingEnabled = false;
  37672. this.currentBlending = null;
  37673. this.currentBlendSrc = null;
  37674. this.currentBlendDst = null;
  37675. this.currentBlendSrcAlpha = null;
  37676. this.currentBlendDstAlpha = null;
  37677. this.currentPremultipledAlpha = null;
  37678. this.currentPolygonOffsetFactor = null;
  37679. this.currentPolygonOffsetUnits = null;
  37680. this.currentColorMask = null;
  37681. this.currentDepthFunc = null;
  37682. this.currentDepthMask = null;
  37683. this.currentStencilFunc = null;
  37684. this.currentStencilRef = null;
  37685. this.currentStencilFuncMask = null;
  37686. this.currentStencilFail = null;
  37687. this.currentStencilZFail = null;
  37688. this.currentStencilZPass = null;
  37689. this.currentStencilMask = null;
  37690. this.currentLineWidth = null;
  37691. this.currentBoundFramebuffers = {};
  37692. this.currentDrawbuffers = new WeakMap();
  37693. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  37694. this.currentTextureSlot = null;
  37695. this.currentBoundTextures = {};
  37696. if ( initialized$1 === false ) {
  37697. this._init( this.gl );
  37698. initialized$1 = true;
  37699. }
  37700. }
  37701. _init( gl ) {
  37702. // Store only WebGL constants here.
  37703. equationToGL = {
  37704. [ AddEquation ]: gl.FUNC_ADD,
  37705. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  37706. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  37707. };
  37708. factorToGL = {
  37709. [ ZeroFactor ]: gl.ZERO,
  37710. [ OneFactor ]: gl.ONE,
  37711. [ SrcColorFactor ]: gl.SRC_COLOR,
  37712. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  37713. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  37714. [ DstColorFactor ]: gl.DST_COLOR,
  37715. [ DstAlphaFactor ]: gl.DST_ALPHA,
  37716. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  37717. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  37718. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  37719. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  37720. };
  37721. }
  37722. enable( id ) {
  37723. const { enabled } = this;
  37724. if ( enabled[ id ] !== true ) {
  37725. this.gl.enable( id );
  37726. enabled[ id ] = true;
  37727. }
  37728. }
  37729. disable( id ) {
  37730. const { enabled } = this;
  37731. if ( enabled[ id ] !== false ) {
  37732. this.gl.disable( id );
  37733. enabled[ id ] = false;
  37734. }
  37735. }
  37736. setFlipSided( flipSided ) {
  37737. if ( this.currentFlipSided !== flipSided ) {
  37738. const { gl } = this;
  37739. if ( flipSided ) {
  37740. gl.frontFace( gl.CW );
  37741. } else {
  37742. gl.frontFace( gl.CCW );
  37743. }
  37744. this.currentFlipSided = flipSided;
  37745. }
  37746. }
  37747. setCullFace( cullFace ) {
  37748. const { gl } = this;
  37749. if ( cullFace !== CullFaceNone ) {
  37750. this.enable( gl.CULL_FACE );
  37751. if ( cullFace !== this.currentCullFace ) {
  37752. if ( cullFace === CullFaceBack ) {
  37753. gl.cullFace( gl.BACK );
  37754. } else if ( cullFace === CullFaceFront ) {
  37755. gl.cullFace( gl.FRONT );
  37756. } else {
  37757. gl.cullFace( gl.FRONT_AND_BACK );
  37758. }
  37759. }
  37760. } else {
  37761. this.disable( gl.CULL_FACE );
  37762. }
  37763. this.currentCullFace = cullFace;
  37764. }
  37765. setLineWidth( width ) {
  37766. const { currentLineWidth, gl } = this;
  37767. if ( width !== currentLineWidth ) {
  37768. gl.lineWidth( width );
  37769. this.currentLineWidth = width;
  37770. }
  37771. }
  37772. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  37773. const { gl } = this;
  37774. if ( blending === NoBlending ) {
  37775. if ( this.currentBlendingEnabled === true ) {
  37776. this.disable( gl.BLEND );
  37777. this.currentBlendingEnabled = false;
  37778. }
  37779. return;
  37780. }
  37781. if ( this.currentBlendingEnabled === false ) {
  37782. this.enable( gl.BLEND );
  37783. this.currentBlendingEnabled = true;
  37784. }
  37785. if ( blending !== CustomBlending ) {
  37786. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  37787. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  37788. gl.blendEquation( gl.FUNC_ADD );
  37789. this.currentBlendEquation = AddEquation;
  37790. this.currentBlendEquationAlpha = AddEquation;
  37791. }
  37792. if ( premultipliedAlpha ) {
  37793. switch ( blending ) {
  37794. case NormalBlending:
  37795. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37796. break;
  37797. case AdditiveBlending:
  37798. gl.blendFunc( gl.ONE, gl.ONE );
  37799. break;
  37800. case SubtractiveBlending:
  37801. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37802. break;
  37803. case MultiplyBlending:
  37804. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  37805. break;
  37806. default:
  37807. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37808. break;
  37809. }
  37810. } else {
  37811. switch ( blending ) {
  37812. case NormalBlending:
  37813. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37814. break;
  37815. case AdditiveBlending:
  37816. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  37817. break;
  37818. case SubtractiveBlending:
  37819. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37820. break;
  37821. case MultiplyBlending:
  37822. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  37823. break;
  37824. default:
  37825. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37826. break;
  37827. }
  37828. }
  37829. this.currentBlendSrc = null;
  37830. this.currentBlendDst = null;
  37831. this.currentBlendSrcAlpha = null;
  37832. this.currentBlendDstAlpha = null;
  37833. this.currentBlending = blending;
  37834. this.currentPremultipledAlpha = premultipliedAlpha;
  37835. }
  37836. return;
  37837. }
  37838. // custom blending
  37839. blendEquationAlpha = blendEquationAlpha || blendEquation;
  37840. blendSrcAlpha = blendSrcAlpha || blendSrc;
  37841. blendDstAlpha = blendDstAlpha || blendDst;
  37842. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  37843. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  37844. this.currentBlendEquation = blendEquation;
  37845. this.currentBlendEquationAlpha = blendEquationAlpha;
  37846. }
  37847. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  37848. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  37849. this.currentBlendSrc = blendSrc;
  37850. this.currentBlendDst = blendDst;
  37851. this.currentBlendSrcAlpha = blendSrcAlpha;
  37852. this.currentBlendDstAlpha = blendDstAlpha;
  37853. }
  37854. this.currentBlending = blending;
  37855. this.currentPremultipledAlpha = false;
  37856. }
  37857. setColorMask( colorMask ) {
  37858. if ( this.currentColorMask !== colorMask ) {
  37859. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  37860. this.currentColorMask = colorMask;
  37861. }
  37862. }
  37863. setDepthTest( depthTest ) {
  37864. const { gl } = this;
  37865. if ( depthTest ) {
  37866. this.enable( gl.DEPTH_TEST );
  37867. } else {
  37868. this.disable( gl.DEPTH_TEST );
  37869. }
  37870. }
  37871. setDepthMask( depthMask ) {
  37872. if ( this.currentDepthMask !== depthMask ) {
  37873. this.gl.depthMask( depthMask );
  37874. this.currentDepthMask = depthMask;
  37875. }
  37876. }
  37877. setDepthFunc( depthFunc ) {
  37878. if ( this.currentDepthFunc !== depthFunc ) {
  37879. const { gl } = this;
  37880. switch ( depthFunc ) {
  37881. case NeverDepth:
  37882. gl.depthFunc( gl.NEVER );
  37883. break;
  37884. case AlwaysDepth:
  37885. gl.depthFunc( gl.ALWAYS );
  37886. break;
  37887. case LessDepth:
  37888. gl.depthFunc( gl.LESS );
  37889. break;
  37890. case LessEqualDepth:
  37891. gl.depthFunc( gl.LEQUAL );
  37892. break;
  37893. case EqualDepth:
  37894. gl.depthFunc( gl.EQUAL );
  37895. break;
  37896. case GreaterEqualDepth:
  37897. gl.depthFunc( gl.GEQUAL );
  37898. break;
  37899. case GreaterDepth:
  37900. gl.depthFunc( gl.GREATER );
  37901. break;
  37902. case NotEqualDepth:
  37903. gl.depthFunc( gl.NOTEQUAL );
  37904. break;
  37905. default:
  37906. gl.depthFunc( gl.LEQUAL );
  37907. }
  37908. this.currentDepthFunc = depthFunc;
  37909. }
  37910. }
  37911. setStencilTest( stencilTest ) {
  37912. const { gl } = this;
  37913. if ( stencilTest ) {
  37914. this.enable( gl.STENCIL_TEST );
  37915. } else {
  37916. this.disable( gl.STENCIL_TEST );
  37917. }
  37918. }
  37919. setStencilMask( stencilMask ) {
  37920. if ( this.currentStencilMask !== stencilMask ) {
  37921. this.gl.stencilMask( stencilMask );
  37922. this.currentStencilMask = stencilMask;
  37923. }
  37924. }
  37925. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  37926. if ( this.currentStencilFunc !== stencilFunc ||
  37927. this.currentStencilRef !== stencilRef ||
  37928. this.currentStencilFuncMask !== stencilMask ) {
  37929. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  37930. this.currentStencilFunc = stencilFunc;
  37931. this.currentStencilRef = stencilRef;
  37932. this.currentStencilFuncMask = stencilMask;
  37933. }
  37934. }
  37935. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  37936. if ( this.currentStencilFail !== stencilFail ||
  37937. this.currentStencilZFail !== stencilZFail ||
  37938. this.currentStencilZPass !== stencilZPass ) {
  37939. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  37940. this.currentStencilFail = stencilFail;
  37941. this.currentStencilZFail = stencilZFail;
  37942. this.currentStencilZPass = stencilZPass;
  37943. }
  37944. }
  37945. setMaterial( material, frontFaceCW ) {
  37946. const { gl } = this;
  37947. material.side === DoubleSide
  37948. ? this.disable( gl.CULL_FACE )
  37949. : this.enable( gl.CULL_FACE );
  37950. let flipSided = ( material.side === BackSide );
  37951. if ( frontFaceCW ) flipSided = ! flipSided;
  37952. this.setFlipSided( flipSided );
  37953. ( material.blending === NormalBlending && material.transparent === false )
  37954. ? this.setBlending( NoBlending )
  37955. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  37956. this.setDepthFunc( material.depthFunc );
  37957. this.setDepthTest( material.depthTest );
  37958. this.setDepthMask( material.depthWrite );
  37959. this.setColorMask( material.colorWrite );
  37960. const stencilWrite = material.stencilWrite;
  37961. this.setStencilTest( stencilWrite );
  37962. if ( stencilWrite ) {
  37963. this.setStencilMask( material.stencilWriteMask );
  37964. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  37965. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  37966. }
  37967. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  37968. material.alphaToCoverage === true
  37969. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  37970. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  37971. }
  37972. setPolygonOffset( polygonOffset, factor, units ) {
  37973. const { gl } = this;
  37974. if ( polygonOffset ) {
  37975. this.enable( gl.POLYGON_OFFSET_FILL );
  37976. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  37977. gl.polygonOffset( factor, units );
  37978. this.currentPolygonOffsetFactor = factor;
  37979. this.currentPolygonOffsetUnits = units;
  37980. }
  37981. } else {
  37982. this.disable( gl.POLYGON_OFFSET_FILL );
  37983. }
  37984. }
  37985. useProgram( program ) {
  37986. if ( this.currentProgram !== program ) {
  37987. this.gl.useProgram( program );
  37988. this.currentProgram = program;
  37989. return true;
  37990. }
  37991. return false;
  37992. }
  37993. // framebuffer
  37994. bindFramebuffer( target, framebuffer ) {
  37995. const { gl, currentBoundFramebuffers } = this;
  37996. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  37997. gl.bindFramebuffer( target, framebuffer );
  37998. currentBoundFramebuffers[ target ] = framebuffer;
  37999. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  38000. if ( target === gl.DRAW_FRAMEBUFFER ) {
  38001. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  38002. }
  38003. if ( target === gl.FRAMEBUFFER ) {
  38004. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  38005. }
  38006. return true;
  38007. }
  38008. return false;
  38009. }
  38010. drawBuffers( renderContext, framebuffer ) {
  38011. const { gl } = this;
  38012. let drawBuffers = [];
  38013. let needsUpdate = false;
  38014. if ( renderContext.textures !== null ) {
  38015. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  38016. if ( drawBuffers === undefined ) {
  38017. drawBuffers = [];
  38018. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  38019. }
  38020. const textures = renderContext.textures;
  38021. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  38022. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  38023. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  38024. }
  38025. drawBuffers.length = textures.length;
  38026. needsUpdate = true;
  38027. }
  38028. } else {
  38029. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  38030. drawBuffers[ 0 ] = gl.BACK;
  38031. needsUpdate = true;
  38032. }
  38033. }
  38034. if ( needsUpdate ) {
  38035. gl.drawBuffers( drawBuffers );
  38036. }
  38037. }
  38038. // texture
  38039. activeTexture( webglSlot ) {
  38040. const { gl, currentTextureSlot, maxTextures } = this;
  38041. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38042. if ( currentTextureSlot !== webglSlot ) {
  38043. gl.activeTexture( webglSlot );
  38044. this.currentTextureSlot = webglSlot;
  38045. }
  38046. }
  38047. bindTexture( webglType, webglTexture, webglSlot ) {
  38048. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  38049. if ( webglSlot === undefined ) {
  38050. if ( currentTextureSlot === null ) {
  38051. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38052. } else {
  38053. webglSlot = currentTextureSlot;
  38054. }
  38055. }
  38056. let boundTexture = currentBoundTextures[ webglSlot ];
  38057. if ( boundTexture === undefined ) {
  38058. boundTexture = { type: undefined, texture: undefined };
  38059. currentBoundTextures[ webglSlot ] = boundTexture;
  38060. }
  38061. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  38062. if ( currentTextureSlot !== webglSlot ) {
  38063. gl.activeTexture( webglSlot );
  38064. this.currentTextureSlot = webglSlot;
  38065. }
  38066. gl.bindTexture( webglType, webglTexture );
  38067. boundTexture.type = webglType;
  38068. boundTexture.texture = webglTexture;
  38069. }
  38070. }
  38071. unbindTexture() {
  38072. const { gl, currentTextureSlot, currentBoundTextures } = this;
  38073. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  38074. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  38075. gl.bindTexture( boundTexture.type, null );
  38076. boundTexture.type = undefined;
  38077. boundTexture.texture = undefined;
  38078. }
  38079. }
  38080. }
  38081. class WebGLUtils {
  38082. constructor( backend ) {
  38083. this.backend = backend;
  38084. this.gl = this.backend.gl;
  38085. this.extensions = backend.extensions;
  38086. }
  38087. convert( p, colorSpace = NoColorSpace ) {
  38088. const { gl, extensions } = this;
  38089. let extension;
  38090. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  38091. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  38092. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  38093. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  38094. if ( p === ByteType ) return gl.BYTE;
  38095. if ( p === ShortType ) return gl.SHORT;
  38096. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  38097. if ( p === IntType ) return gl.INT;
  38098. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  38099. if ( p === FloatType ) return gl.FLOAT;
  38100. if ( p === HalfFloatType ) {
  38101. return gl.HALF_FLOAT;
  38102. }
  38103. if ( p === AlphaFormat ) return gl.ALPHA;
  38104. if ( p === RGBFormat ) return gl.RGB;
  38105. if ( p === RGBAFormat ) return gl.RGBA;
  38106. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  38107. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  38108. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  38109. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  38110. // WebGL2 formats.
  38111. if ( p === RedFormat ) return gl.RED;
  38112. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  38113. if ( p === RGFormat ) return gl.RG;
  38114. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  38115. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  38116. // S3TC
  38117. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  38118. if ( colorSpace === SRGBColorSpace ) {
  38119. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  38120. if ( extension !== null ) {
  38121. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  38122. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  38123. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  38124. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  38125. } else {
  38126. return null;
  38127. }
  38128. } else {
  38129. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  38130. if ( extension !== null ) {
  38131. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  38132. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  38133. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  38134. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  38135. } else {
  38136. return null;
  38137. }
  38138. }
  38139. }
  38140. // PVRTC
  38141. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  38142. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  38143. if ( extension !== null ) {
  38144. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  38145. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  38146. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  38147. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  38148. } else {
  38149. return null;
  38150. }
  38151. }
  38152. // ETC
  38153. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  38154. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  38155. if ( extension !== null ) {
  38156. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  38157. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  38158. } else {
  38159. return null;
  38160. }
  38161. }
  38162. // ASTC
  38163. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  38164. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  38165. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  38166. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  38167. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  38168. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  38169. if ( extension !== null ) {
  38170. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  38171. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  38172. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  38173. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  38174. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  38175. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  38176. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  38177. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  38178. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  38179. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  38180. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  38181. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  38182. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  38183. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  38184. } else {
  38185. return null;
  38186. }
  38187. }
  38188. // BPTC
  38189. if ( p === RGBA_BPTC_Format ) {
  38190. extension = extensions.get( 'EXT_texture_compression_bptc' );
  38191. if ( extension !== null ) {
  38192. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  38193. } else {
  38194. return null;
  38195. }
  38196. }
  38197. // RGTC
  38198. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  38199. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  38200. if ( extension !== null ) {
  38201. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  38202. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  38203. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  38204. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  38205. } else {
  38206. return null;
  38207. }
  38208. }
  38209. //
  38210. if ( p === UnsignedInt248Type ) {
  38211. return gl.UNSIGNED_INT_24_8;
  38212. }
  38213. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  38214. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  38215. }
  38216. _clientWaitAsync() {
  38217. const { gl } = this;
  38218. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  38219. gl.flush();
  38220. return new Promise( ( resolve, reject ) => {
  38221. function test() {
  38222. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  38223. if ( res === gl.WAIT_FAILED ) {
  38224. gl.deleteSync( sync );
  38225. reject();
  38226. return;
  38227. }
  38228. if ( res === gl.TIMEOUT_EXPIRED ) {
  38229. requestAnimationFrame( test );
  38230. return;
  38231. }
  38232. gl.deleteSync( sync );
  38233. resolve();
  38234. }
  38235. test();
  38236. } );
  38237. }
  38238. }
  38239. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  38240. class WebGLTextureUtils {
  38241. constructor( backend ) {
  38242. this.backend = backend;
  38243. this.gl = backend.gl;
  38244. this.extensions = backend.extensions;
  38245. this.defaultTextures = {};
  38246. if ( initialized === false ) {
  38247. this._init( this.gl );
  38248. initialized = true;
  38249. }
  38250. }
  38251. _init( gl ) {
  38252. // Store only WebGL constants here.
  38253. wrappingToGL = {
  38254. [ RepeatWrapping ]: gl.REPEAT,
  38255. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  38256. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  38257. };
  38258. filterToGL = {
  38259. [ NearestFilter ]: gl.NEAREST,
  38260. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  38261. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  38262. [ LinearFilter ]: gl.LINEAR,
  38263. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  38264. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  38265. };
  38266. compareToGL = {
  38267. [ NeverCompare ]: gl.NEVER,
  38268. [ AlwaysCompare ]: gl.ALWAYS,
  38269. [ LessCompare ]: gl.LESS,
  38270. [ LessEqualCompare ]: gl.LEQUAL,
  38271. [ EqualCompare ]: gl.EQUAL,
  38272. [ GreaterEqualCompare ]: gl.GEQUAL,
  38273. [ GreaterCompare ]: gl.GREATER,
  38274. [ NotEqualCompare ]: gl.NOTEQUAL
  38275. };
  38276. }
  38277. filterFallback( f ) {
  38278. const { gl } = this;
  38279. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  38280. return gl.NEAREST;
  38281. }
  38282. return gl.LINEAR;
  38283. }
  38284. getGLTextureType( texture ) {
  38285. const { gl } = this;
  38286. let glTextureType;
  38287. if ( texture.isCubeTexture === true ) {
  38288. glTextureType = gl.TEXTURE_CUBE_MAP;
  38289. } else if ( texture.isDataArrayTexture === true ) {
  38290. glTextureType = gl.TEXTURE_2D_ARRAY;
  38291. } else if ( texture.isData3DTexture === true ) {
  38292. glTextureType = gl.TEXTURE_3D;
  38293. } else {
  38294. glTextureType = gl.TEXTURE_2D;
  38295. }
  38296. return glTextureType;
  38297. }
  38298. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  38299. const { gl, extensions } = this;
  38300. if ( internalFormatName !== null ) {
  38301. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  38302. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  38303. }
  38304. let internalFormat = glFormat;
  38305. if ( glFormat === gl.RED ) {
  38306. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  38307. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  38308. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  38309. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  38310. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38311. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38312. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38313. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38314. }
  38315. if ( glFormat === gl.RED_INTEGER ) {
  38316. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  38317. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  38318. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38319. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38320. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38321. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38322. }
  38323. if ( glFormat === gl.RG ) {
  38324. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  38325. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  38326. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  38327. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  38328. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38329. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38330. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38331. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38332. }
  38333. if ( glFormat === gl.RG_INTEGER ) {
  38334. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  38335. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  38336. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38337. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38338. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38339. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38340. }
  38341. if ( glFormat === gl.RGB ) {
  38342. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  38343. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  38344. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  38345. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  38346. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38347. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38348. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38349. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38350. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  38351. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  38352. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38353. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  38354. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  38355. }
  38356. if ( glFormat === gl.RGB_INTEGER ) {
  38357. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  38358. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  38359. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38360. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38361. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38362. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38363. }
  38364. if ( glFormat === gl.RGBA ) {
  38365. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  38366. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  38367. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  38368. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  38369. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38370. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38371. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38372. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38373. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  38374. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  38375. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38376. }
  38377. if ( glFormat === gl.RGBA_INTEGER ) {
  38378. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  38379. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  38380. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38381. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38382. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38383. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38384. }
  38385. if ( glFormat === gl.DEPTH_COMPONENT ) {
  38386. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  38387. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  38388. }
  38389. if ( glFormat === gl.DEPTH_STENCIL ) {
  38390. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  38391. }
  38392. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  38393. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  38394. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  38395. extensions.get( 'EXT_color_buffer_float' );
  38396. }
  38397. return internalFormat;
  38398. }
  38399. setTextureParameters( textureType, texture ) {
  38400. const { gl, extensions, backend } = this;
  38401. const { currentAnisotropy } = backend.get( texture );
  38402. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  38403. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  38404. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  38405. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  38406. }
  38407. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  38408. // follow WebGPU backend mapping for texture filtering
  38409. const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter;
  38410. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  38411. if ( texture.compareFunction ) {
  38412. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  38413. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  38414. }
  38415. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38416. if ( texture.magFilter === NearestFilter ) return;
  38417. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  38418. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  38419. if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) {
  38420. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38421. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  38422. backend.get( texture ).currentAnisotropy = texture.anisotropy;
  38423. }
  38424. }
  38425. }
  38426. createDefaultTexture( texture ) {
  38427. const { gl, backend, defaultTextures } = this;
  38428. const glTextureType = this.getGLTextureType( texture );
  38429. let textureGPU = defaultTextures[ glTextureType ];
  38430. if ( textureGPU === undefined ) {
  38431. textureGPU = gl.createTexture();
  38432. backend.state.bindTexture( glTextureType, textureGPU );
  38433. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  38434. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  38435. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  38436. defaultTextures[ glTextureType ] = textureGPU;
  38437. }
  38438. backend.set( texture, {
  38439. textureGPU,
  38440. glTextureType,
  38441. isDefault: true
  38442. } );
  38443. }
  38444. createTexture( texture, options ) {
  38445. const { gl, backend } = this;
  38446. const { levels, width, height, depth } = options;
  38447. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  38448. const glType = backend.utils.convert( texture.type );
  38449. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  38450. const textureGPU = gl.createTexture();
  38451. const glTextureType = this.getGLTextureType( texture );
  38452. backend.state.bindTexture( glTextureType, textureGPU );
  38453. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  38454. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  38455. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  38456. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  38457. this.setTextureParameters( glTextureType, texture );
  38458. if ( texture.isDataArrayTexture ) {
  38459. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  38460. } else if ( texture.isData3DTexture ) {
  38461. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  38462. } else if ( ! texture.isVideoTexture ) {
  38463. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  38464. }
  38465. backend.set( texture, {
  38466. textureGPU,
  38467. glTextureType,
  38468. glFormat,
  38469. glType,
  38470. glInternalFormat
  38471. } );
  38472. }
  38473. copyBufferToTexture( buffer, texture ) {
  38474. const { gl, backend } = this;
  38475. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  38476. const { width, height } = texture.source.data;
  38477. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  38478. backend.state.bindTexture( glTextureType, textureGPU );
  38479. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  38480. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  38481. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  38482. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  38483. backend.state.unbindTexture();
  38484. // debug
  38485. // const framebuffer = gl.createFramebuffer();
  38486. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  38487. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  38488. // const readout = new Float32Array( width * height * 4 );
  38489. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  38490. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  38491. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  38492. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  38493. // console.log( readout );
  38494. }
  38495. updateTexture( texture, options ) {
  38496. const { gl } = this;
  38497. const { width, height } = options;
  38498. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  38499. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  38500. return;
  38501. const getImage = ( source ) => {
  38502. if ( source.isDataTexture ) {
  38503. return source.image.data;
  38504. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  38505. return source;
  38506. }
  38507. return source.data;
  38508. };
  38509. this.backend.state.bindTexture( glTextureType, textureGPU );
  38510. if ( texture.isCompressedTexture ) {
  38511. const mipmaps = texture.mipmaps;
  38512. for ( let i = 0; i < mipmaps.length; i ++ ) {
  38513. const mipmap = mipmaps[ i ];
  38514. if ( texture.isCompressedArrayTexture ) {
  38515. const image = options.image;
  38516. if ( texture.format !== gl.RGBA ) {
  38517. if ( glFormat !== null ) {
  38518. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  38519. } else {
  38520. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  38521. }
  38522. } else {
  38523. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  38524. }
  38525. } else {
  38526. if ( glFormat !== null ) {
  38527. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  38528. } else {
  38529. console.warn( 'Unsupported compressed texture format' );
  38530. }
  38531. }
  38532. }
  38533. } else if ( texture.isCubeTexture ) {
  38534. const images = options.images;
  38535. for ( let i = 0; i < 6; i ++ ) {
  38536. const image = getImage( images[ i ] );
  38537. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  38538. }
  38539. } else if ( texture.isDataArrayTexture ) {
  38540. const image = options.image;
  38541. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38542. } else if ( texture.isData3DTexture ) {
  38543. const image = options.image;
  38544. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38545. } else if ( texture.isVideoTexture ) {
  38546. texture.update();
  38547. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  38548. } else {
  38549. const image = getImage( options.image );
  38550. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  38551. }
  38552. }
  38553. generateMipmaps( texture ) {
  38554. const { gl, backend } = this;
  38555. const { textureGPU, glTextureType } = backend.get( texture );
  38556. backend.state.bindTexture( glTextureType, textureGPU );
  38557. gl.generateMipmap( glTextureType );
  38558. }
  38559. deallocateRenderBuffers( renderTarget ) {
  38560. const { gl, backend } = this;
  38561. // remove framebuffer reference
  38562. if ( renderTarget ) {
  38563. const renderContextData = backend.get( renderTarget );
  38564. renderContextData.renderBufferStorageSetup = undefined;
  38565. if ( renderContextData.framebuffer ) {
  38566. gl.deleteFramebuffer( renderContextData.framebuffer );
  38567. renderContextData.framebuffer = undefined;
  38568. }
  38569. if ( renderContextData.depthRenderbuffer ) {
  38570. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  38571. renderContextData.depthRenderbuffer = undefined;
  38572. }
  38573. if ( renderContextData.stencilRenderbuffer ) {
  38574. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  38575. renderContextData.stencilRenderbuffer = undefined;
  38576. }
  38577. if ( renderContextData.msaaFrameBuffer ) {
  38578. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  38579. renderContextData.msaaFrameBuffer = undefined;
  38580. }
  38581. if ( renderContextData.msaaRenderbuffers ) {
  38582. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  38583. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  38584. }
  38585. renderContextData.msaaRenderbuffers = undefined;
  38586. }
  38587. }
  38588. }
  38589. destroyTexture( texture ) {
  38590. const { gl, backend } = this;
  38591. const { textureGPU, renderTarget } = backend.get( texture );
  38592. this.deallocateRenderBuffers( renderTarget );
  38593. gl.deleteTexture( textureGPU );
  38594. backend.delete( texture );
  38595. }
  38596. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38597. const { gl, backend } = this;
  38598. const { state } = this.backend;
  38599. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  38600. let width, height, minX, minY;
  38601. let dstX, dstY;
  38602. if ( srcRegion !== null ) {
  38603. width = srcRegion.max.x - srcRegion.min.x;
  38604. height = srcRegion.max.y - srcRegion.min.y;
  38605. minX = srcRegion.min.x;
  38606. minY = srcRegion.min.y;
  38607. } else {
  38608. width = srcTexture.image.width;
  38609. height = srcTexture.image.height;
  38610. minX = 0;
  38611. minY = 0;
  38612. }
  38613. if ( dstPosition !== null ) {
  38614. dstX = dstPosition.x;
  38615. dstY = dstPosition.y;
  38616. } else {
  38617. dstX = 0;
  38618. dstY = 0;
  38619. }
  38620. state.bindTexture( glTextureType, dstTextureGPU );
  38621. // As another texture upload may have changed pixelStorei
  38622. // parameters, make sure they are correct for the dstTexture
  38623. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38624. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  38625. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  38626. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38627. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  38628. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  38629. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  38630. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  38631. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  38632. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  38633. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  38634. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  38635. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  38636. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  38637. if ( srcTexture.isDataTexture ) {
  38638. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  38639. } else {
  38640. if ( srcTexture.isCompressedTexture ) {
  38641. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  38642. } else {
  38643. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  38644. }
  38645. }
  38646. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  38647. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  38648. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  38649. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  38650. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  38651. // Generate mipmaps only when copying level 0
  38652. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  38653. state.unbindTexture();
  38654. }
  38655. copyFramebufferToTexture( texture, renderContext ) {
  38656. const { gl } = this;
  38657. const { state } = this.backend;
  38658. const { textureGPU } = this.backend.get( texture );
  38659. const width = texture.image.width;
  38660. const height = texture.image.height;
  38661. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  38662. if ( requireDrawFrameBuffer ) {
  38663. let mask;
  38664. let attachment;
  38665. if ( texture.isDepthTexture === true ) {
  38666. mask = gl.DEPTH_BUFFER_BIT;
  38667. attachment = gl.DEPTH_ATTACHMENT;
  38668. if ( renderContext.stencil ) {
  38669. mask |= gl.STENCIL_BUFFER_BIT;
  38670. }
  38671. } else {
  38672. mask = gl.COLOR_BUFFER_BIT;
  38673. attachment = gl.COLOR_ATTACHMENT0;
  38674. }
  38675. const fb = gl.createFramebuffer();
  38676. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38677. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  38678. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  38679. gl.deleteFramebuffer( fb );
  38680. } else {
  38681. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  38682. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  38683. state.unbindTexture();
  38684. }
  38685. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  38686. this.backend._setFramebuffer( renderContext );
  38687. }
  38688. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  38689. setupRenderBufferStorage( renderbuffer, renderContext ) {
  38690. const { gl } = this;
  38691. const renderTarget = renderContext.renderTarget;
  38692. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  38693. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  38694. if ( depthBuffer && ! stencilBuffer ) {
  38695. let glInternalFormat = gl.DEPTH_COMPONENT24;
  38696. if ( samples > 0 ) {
  38697. if ( depthTexture && depthTexture.isDepthTexture ) {
  38698. if ( depthTexture.type === gl.FLOAT ) {
  38699. glInternalFormat = gl.DEPTH_COMPONENT32F;
  38700. }
  38701. }
  38702. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  38703. } else {
  38704. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  38705. }
  38706. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38707. } else if ( depthBuffer && stencilBuffer ) {
  38708. if ( samples > 0 ) {
  38709. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  38710. } else {
  38711. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  38712. }
  38713. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38714. }
  38715. }
  38716. async copyTextureToBuffer( texture, x, y, width, height ) {
  38717. const { backend, gl } = this;
  38718. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  38719. const fb = gl.createFramebuffer();
  38720. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  38721. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  38722. const typedArrayType = this._getTypedArrayType( glType );
  38723. const bytesPerTexel = this._getBytesPerTexel( glFormat );
  38724. const elementCount = width * height;
  38725. const byteLength = elementCount * bytesPerTexel;
  38726. const buffer = gl.createBuffer();
  38727. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38728. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  38729. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  38730. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38731. await backend.utils._clientWaitAsync();
  38732. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  38733. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38734. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  38735. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38736. gl.deleteFramebuffer( fb );
  38737. return dstBuffer;
  38738. }
  38739. _getTypedArrayType( glType ) {
  38740. const { gl } = this;
  38741. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  38742. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  38743. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  38744. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  38745. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  38746. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  38747. if ( glType === gl.FLOAT ) return Float32Array;
  38748. throw new Error( `Unsupported WebGL type: ${glType}` );
  38749. }
  38750. _getBytesPerTexel( glFormat ) {
  38751. const { gl } = this;
  38752. if ( glFormat === gl.RGBA ) return 4;
  38753. if ( glFormat === gl.RGB ) return 3;
  38754. if ( glFormat === gl.ALPHA ) return 1;
  38755. }
  38756. }
  38757. class WebGLExtensions {
  38758. constructor( backend ) {
  38759. this.backend = backend;
  38760. this.gl = this.backend.gl;
  38761. this.availableExtensions = this.gl.getSupportedExtensions();
  38762. this.extensions = {};
  38763. }
  38764. get( name ) {
  38765. let extension = this.extensions[ name ];
  38766. if ( extension === undefined ) {
  38767. extension = this.gl.getExtension( name );
  38768. this.extensions[ name ] = extension;
  38769. }
  38770. return extension;
  38771. }
  38772. has( name ) {
  38773. return this.availableExtensions.includes( name );
  38774. }
  38775. }
  38776. class WebGLCapabilities {
  38777. constructor( backend ) {
  38778. this.backend = backend;
  38779. this.maxAnisotropy = null;
  38780. }
  38781. getMaxAnisotropy() {
  38782. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  38783. const gl = this.backend.gl;
  38784. const extensions = this.backend.extensions;
  38785. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38786. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38787. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  38788. } else {
  38789. this.maxAnisotropy = 0;
  38790. }
  38791. return this.maxAnisotropy;
  38792. }
  38793. }
  38794. const GLFeatureName = {
  38795. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  38796. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  38797. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  38798. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  38799. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38800. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38801. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  38802. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  38803. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  38804. };
  38805. class WebGLBufferRenderer {
  38806. constructor( backend ) {
  38807. this.gl = backend.gl;
  38808. this.extensions = backend.extensions;
  38809. this.info = backend.renderer.info;
  38810. this.mode = null;
  38811. this.index = 0;
  38812. this.type = null;
  38813. this.object = null;
  38814. }
  38815. render( start, count ) {
  38816. const { gl, mode, object, type, info, index } = this;
  38817. if ( index !== 0 ) {
  38818. gl.drawElements( mode, count, type, start );
  38819. } else {
  38820. gl.drawArrays( mode, start, count );
  38821. }
  38822. info.update( object, count, mode, 1 );
  38823. }
  38824. renderInstances( start, count, primcount ) {
  38825. const { gl, mode, type, index, object, info } = this;
  38826. if ( primcount === 0 ) return;
  38827. if ( index !== 0 ) {
  38828. gl.drawElementsInstanced( mode, count, type, start, primcount );
  38829. } else {
  38830. gl.drawArraysInstanced( mode, start, count, primcount );
  38831. }
  38832. info.update( object, count, mode, primcount );
  38833. }
  38834. renderMultiDraw( starts, counts, drawCount ) {
  38835. const { extensions, mode, object, info } = this;
  38836. if ( drawCount === 0 ) return;
  38837. const extension = extensions.get( 'WEBGL_multi_draw' );
  38838. if ( extension === null ) {
  38839. for ( let i = 0; i < drawCount; i ++ ) {
  38840. this.render( starts[ i ], counts[ i ] );
  38841. }
  38842. } else {
  38843. if ( this.index !== 0 ) {
  38844. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  38845. } else {
  38846. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  38847. }
  38848. let elementCount = 0;
  38849. for ( let i = 0; i < drawCount; i ++ ) {
  38850. elementCount += counts[ i ];
  38851. }
  38852. info.update( object, elementCount, mode, 1 );
  38853. }
  38854. }
  38855. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  38856. const { extensions, mode, object, info } = this;
  38857. if ( drawCount === 0 ) return;
  38858. const extension = extensions.get( 'WEBGL_multi_draw' );
  38859. if ( extension === null ) {
  38860. for ( let i = 0; i < drawCount; i ++ ) {
  38861. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  38862. }
  38863. } else {
  38864. if ( this.index !== 0 ) {
  38865. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  38866. } else {
  38867. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  38868. }
  38869. let elementCount = 0;
  38870. for ( let i = 0; i < drawCount; i ++ ) {
  38871. elementCount += counts[ i ];
  38872. }
  38873. for ( let i = 0; i < primcount.length; i ++ ) {
  38874. info.update( object, elementCount, mode, primcount[ i ] );
  38875. }
  38876. }
  38877. }
  38878. //
  38879. }
  38880. //
  38881. class WebGLBackend extends Backend {
  38882. constructor( parameters = {} ) {
  38883. super( parameters );
  38884. this.isWebGLBackend = true;
  38885. }
  38886. init( renderer ) {
  38887. super.init( renderer );
  38888. //
  38889. const parameters = this.parameters;
  38890. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  38891. this.gl = glContext;
  38892. this.extensions = new WebGLExtensions( this );
  38893. this.capabilities = new WebGLCapabilities( this );
  38894. this.attributeUtils = new WebGLAttributeUtils( this );
  38895. this.textureUtils = new WebGLTextureUtils( this );
  38896. this.bufferRenderer = new WebGLBufferRenderer( this );
  38897. this.state = new WebGLState( this );
  38898. this.utils = new WebGLUtils( this );
  38899. this.vaoCache = {};
  38900. this.transformFeedbackCache = {};
  38901. this.discard = false;
  38902. this.trackTimestamp = ( parameters.trackTimestamp === true );
  38903. this.extensions.get( 'EXT_color_buffer_float' );
  38904. this.extensions.get( 'WEBGL_multi_draw' );
  38905. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  38906. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  38907. this._currentContext = null;
  38908. }
  38909. get coordinateSystem() {
  38910. return WebGLCoordinateSystem;
  38911. }
  38912. async getArrayBufferAsync( attribute ) {
  38913. return await this.attributeUtils.getArrayBufferAsync( attribute );
  38914. }
  38915. initTimestampQuery( renderContext ) {
  38916. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38917. const renderContextData = this.get( renderContext );
  38918. if ( this.queryRunning ) {
  38919. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  38920. renderContextData.queryQueue.push( renderContext );
  38921. return;
  38922. }
  38923. if ( renderContextData.activeQuery ) {
  38924. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38925. renderContextData.activeQuery = null;
  38926. }
  38927. renderContextData.activeQuery = this.gl.createQuery();
  38928. if ( renderContextData.activeQuery !== null ) {
  38929. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  38930. this.queryRunning = true;
  38931. }
  38932. }
  38933. // timestamp utils
  38934. prepareTimestampBuffer( renderContext ) {
  38935. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38936. const renderContextData = this.get( renderContext );
  38937. if ( renderContextData.activeQuery ) {
  38938. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38939. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38940. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  38941. renderContextData.activeQuery = null;
  38942. this.queryRunning = false;
  38943. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  38944. const nextRenderContext = renderContextData.queryQueue.shift();
  38945. this.initTimestampQuery( nextRenderContext );
  38946. }
  38947. }
  38948. }
  38949. async resolveTimestampAsync( renderContext, type = 'render' ) {
  38950. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38951. const renderContextData = this.get( renderContext );
  38952. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38953. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  38954. const queryInfo = renderContextData.gpuQueries[ i ];
  38955. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  38956. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  38957. if ( available && ! disjoint ) {
  38958. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  38959. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  38960. this.gl.deleteQuery( queryInfo.query );
  38961. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  38962. i --;
  38963. this.renderer.info.updateTimestamp( type, duration );
  38964. }
  38965. }
  38966. }
  38967. getContext() {
  38968. return this.gl;
  38969. }
  38970. beginRender( renderContext ) {
  38971. const { gl } = this;
  38972. const renderContextData = this.get( renderContext );
  38973. //
  38974. //
  38975. this.initTimestampQuery( renderContext );
  38976. renderContextData.previousContext = this._currentContext;
  38977. this._currentContext = renderContext;
  38978. this._setFramebuffer( renderContext );
  38979. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  38980. //
  38981. if ( renderContext.viewport ) {
  38982. this.updateViewport( renderContext );
  38983. } else {
  38984. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38985. }
  38986. if ( renderContext.scissor ) {
  38987. const { x, y, width, height } = renderContext.scissorValue;
  38988. gl.scissor( x, y, width, height );
  38989. }
  38990. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38991. if ( occlusionQueryCount > 0 ) {
  38992. // Get a reference to the array of objects with queries. The renderContextData property
  38993. // can be changed by another render pass before the async reading of all previous queries complete
  38994. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  38995. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  38996. renderContextData.lastOcclusionObject = null;
  38997. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  38998. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  38999. renderContextData.occlusionQueryIndex = 0;
  39000. }
  39001. }
  39002. finishRender( renderContext ) {
  39003. const { gl, state } = this;
  39004. const renderContextData = this.get( renderContext );
  39005. const previousContext = renderContextData.previousContext;
  39006. const textures = renderContext.textures;
  39007. if ( textures !== null ) {
  39008. for ( let i = 0; i < textures.length; i ++ ) {
  39009. const texture = textures[ i ];
  39010. if ( texture.generateMipmaps ) {
  39011. this.generateMipmaps( texture );
  39012. }
  39013. }
  39014. }
  39015. this._currentContext = previousContext;
  39016. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  39017. const renderTargetContextData = this.get( renderContext.renderTarget );
  39018. const { samples } = renderContext.renderTarget;
  39019. const fb = renderTargetContextData.framebuffer;
  39020. const mask = gl.COLOR_BUFFER_BIT;
  39021. if ( samples > 0 ) {
  39022. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39023. const textures = renderContext.textures;
  39024. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  39025. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39026. for ( let i = 0; i < textures.length; i ++ ) {
  39027. // TODO Add support for MRT
  39028. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  39029. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  39030. }
  39031. }
  39032. }
  39033. if ( previousContext !== null ) {
  39034. this._setFramebuffer( previousContext );
  39035. if ( previousContext.viewport ) {
  39036. this.updateViewport( previousContext );
  39037. } else {
  39038. const gl = this.gl;
  39039. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  39040. }
  39041. }
  39042. const occlusionQueryCount = renderContext.occlusionQueryCount;
  39043. if ( occlusionQueryCount > 0 ) {
  39044. const renderContextData = this.get( renderContext );
  39045. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  39046. const { gl } = this;
  39047. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39048. }
  39049. this.resolveOccludedAsync( renderContext );
  39050. }
  39051. this.prepareTimestampBuffer( renderContext );
  39052. }
  39053. resolveOccludedAsync( renderContext ) {
  39054. const renderContextData = this.get( renderContext );
  39055. // handle occlusion query results
  39056. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  39057. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  39058. const occluded = new WeakSet();
  39059. const { gl } = this;
  39060. renderContextData.currentOcclusionQueryObjects = null;
  39061. renderContextData.currentOcclusionQueries = null;
  39062. const check = () => {
  39063. let completed = 0;
  39064. // check all queries and requeue as appropriate
  39065. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  39066. const query = currentOcclusionQueries[ i ];
  39067. if ( query === null ) continue;
  39068. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  39069. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  39070. currentOcclusionQueries[ i ] = null;
  39071. gl.deleteQuery( query );
  39072. completed ++;
  39073. }
  39074. }
  39075. if ( completed < currentOcclusionQueries.length ) {
  39076. requestAnimationFrame( check );
  39077. } else {
  39078. renderContextData.occluded = occluded;
  39079. }
  39080. };
  39081. check();
  39082. }
  39083. }
  39084. isOccluded( renderContext, object ) {
  39085. const renderContextData = this.get( renderContext );
  39086. return renderContextData.occluded && renderContextData.occluded.has( object );
  39087. }
  39088. updateViewport( renderContext ) {
  39089. const gl = this.gl;
  39090. const { x, y, width, height } = renderContext.viewportValue;
  39091. gl.viewport( x, y, width, height );
  39092. }
  39093. setScissorTest( boolean ) {
  39094. const gl = this.gl;
  39095. if ( boolean ) {
  39096. gl.enable( gl.SCISSOR_TEST );
  39097. } else {
  39098. gl.disable( gl.SCISSOR_TEST );
  39099. }
  39100. }
  39101. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  39102. const { gl } = this;
  39103. if ( descriptor === null ) {
  39104. descriptor = {
  39105. textures: null,
  39106. clearColorValue: this.getClearColor()
  39107. };
  39108. }
  39109. //
  39110. let clear = 0;
  39111. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  39112. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  39113. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  39114. if ( clear !== 0 ) {
  39115. const clearColor = descriptor.clearColorValue || this.getClearColor();
  39116. if ( depth ) this.state.setDepthMask( true );
  39117. if ( descriptor.textures === null ) {
  39118. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  39119. gl.clear( clear );
  39120. } else {
  39121. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  39122. if ( color ) {
  39123. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  39124. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  39125. }
  39126. }
  39127. if ( depth && stencil ) {
  39128. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  39129. } else if ( depth ) {
  39130. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  39131. } else if ( stencil ) {
  39132. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  39133. }
  39134. }
  39135. }
  39136. }
  39137. beginCompute( computeGroup ) {
  39138. const gl = this.gl;
  39139. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39140. this.initTimestampQuery( computeGroup );
  39141. }
  39142. compute( computeGroup, computeNode, bindings, pipeline ) {
  39143. const gl = this.gl;
  39144. if ( ! this.discard ) {
  39145. // required here to handle async behaviour of render.compute()
  39146. gl.enable( gl.RASTERIZER_DISCARD );
  39147. this.discard = true;
  39148. }
  39149. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  39150. const vaoKey = this._getVaoKey( null, attributes );
  39151. const vaoGPU = this.vaoCache[ vaoKey ];
  39152. if ( vaoGPU === undefined ) {
  39153. this._createVao( null, attributes );
  39154. } else {
  39155. gl.bindVertexArray( vaoGPU );
  39156. }
  39157. gl.useProgram( programGPU );
  39158. this._bindUniforms( bindings );
  39159. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  39160. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39161. gl.beginTransformFeedback( gl.POINTS );
  39162. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  39163. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  39164. } else {
  39165. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  39166. }
  39167. gl.endTransformFeedback();
  39168. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39169. // switch active buffers
  39170. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39171. const dualAttributeData = transformBuffers[ i ];
  39172. if ( dualAttributeData.pbo ) {
  39173. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  39174. }
  39175. dualAttributeData.switchBuffers();
  39176. }
  39177. }
  39178. finishCompute( computeGroup ) {
  39179. const gl = this.gl;
  39180. this.discard = false;
  39181. gl.disable( gl.RASTERIZER_DISCARD );
  39182. this.prepareTimestampBuffer( computeGroup );
  39183. }
  39184. draw( renderObject/*, info*/ ) {
  39185. const { object, pipeline, material, context } = renderObject;
  39186. const { programGPU } = this.get( pipeline );
  39187. const { gl, state } = this;
  39188. const contextData = this.get( context );
  39189. //
  39190. this._bindUniforms( renderObject.getBindings() );
  39191. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  39192. state.setMaterial( material, frontFaceCW );
  39193. gl.useProgram( programGPU );
  39194. //
  39195. let vaoGPU = renderObject.staticVao;
  39196. if ( vaoGPU === undefined ) {
  39197. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  39198. vaoGPU = this.vaoCache[ vaoKey ];
  39199. if ( vaoGPU === undefined ) {
  39200. let staticVao;
  39201. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  39202. if ( staticVao ) renderObject.staticVao = vaoGPU;
  39203. }
  39204. }
  39205. gl.bindVertexArray( vaoGPU );
  39206. //
  39207. const index = renderObject.getIndex();
  39208. const geometry = renderObject.geometry;
  39209. const drawRange = renderObject.drawRange;
  39210. const firstVertex = drawRange.start;
  39211. //
  39212. const lastObject = contextData.lastOcclusionObject;
  39213. if ( lastObject !== object && lastObject !== undefined ) {
  39214. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  39215. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39216. contextData.occlusionQueryIndex ++;
  39217. }
  39218. if ( object.occlusionTest === true ) {
  39219. const query = gl.createQuery();
  39220. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  39221. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  39222. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  39223. }
  39224. contextData.lastOcclusionObject = object;
  39225. }
  39226. //
  39227. const renderer = this.bufferRenderer;
  39228. if ( object.isPoints ) renderer.mode = gl.POINTS;
  39229. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  39230. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  39231. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  39232. else {
  39233. if ( material.wireframe === true ) {
  39234. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  39235. renderer.mode = gl.LINES;
  39236. } else {
  39237. renderer.mode = gl.TRIANGLES;
  39238. }
  39239. }
  39240. //
  39241. let count;
  39242. renderer.object = object;
  39243. if ( index !== null ) {
  39244. const indexData = this.get( index );
  39245. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  39246. renderer.index = index.count;
  39247. renderer.type = indexData.type;
  39248. count = indexCount;
  39249. } else {
  39250. renderer.index = 0;
  39251. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  39252. count = vertexCount;
  39253. }
  39254. const instanceCount = this.getInstanceCount( renderObject );
  39255. if ( object.isBatchedMesh ) {
  39256. if ( object._multiDrawInstances !== null ) {
  39257. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  39258. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  39259. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  39260. } else {
  39261. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  39262. }
  39263. } else if ( instanceCount > 1 ) {
  39264. renderer.renderInstances( firstVertex, count, instanceCount );
  39265. } else {
  39266. renderer.render( firstVertex, count );
  39267. }
  39268. //
  39269. gl.bindVertexArray( null );
  39270. }
  39271. needsRenderUpdate( /*renderObject*/ ) {
  39272. return false;
  39273. }
  39274. getRenderCacheKey( renderObject ) {
  39275. return renderObject.id;
  39276. }
  39277. // textures
  39278. createDefaultTexture( texture ) {
  39279. this.textureUtils.createDefaultTexture( texture );
  39280. }
  39281. createTexture( texture, options ) {
  39282. this.textureUtils.createTexture( texture, options );
  39283. }
  39284. updateTexture( texture, options ) {
  39285. this.textureUtils.updateTexture( texture, options );
  39286. }
  39287. generateMipmaps( texture ) {
  39288. this.textureUtils.generateMipmaps( texture );
  39289. }
  39290. destroyTexture( texture ) {
  39291. this.textureUtils.destroyTexture( texture );
  39292. }
  39293. copyTextureToBuffer( texture, x, y, width, height ) {
  39294. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  39295. }
  39296. createSampler( /*texture*/ ) {
  39297. //console.warn( 'Abstract class.' );
  39298. }
  39299. destroySampler() {}
  39300. // node builder
  39301. createNodeBuilder( object, renderer ) {
  39302. return new GLSLNodeBuilder( object, renderer );
  39303. }
  39304. // program
  39305. createProgram( program ) {
  39306. const gl = this.gl;
  39307. const { stage, code } = program;
  39308. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  39309. gl.shaderSource( shader, code );
  39310. gl.compileShader( shader );
  39311. this.set( program, {
  39312. shaderGPU: shader
  39313. } );
  39314. }
  39315. destroyProgram( /*program*/ ) {
  39316. console.warn( 'Abstract class.' );
  39317. }
  39318. createRenderPipeline( renderObject, promises ) {
  39319. const gl = this.gl;
  39320. const pipeline = renderObject.pipeline;
  39321. // Program
  39322. const { fragmentProgram, vertexProgram } = pipeline;
  39323. const programGPU = gl.createProgram();
  39324. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39325. const vertexShader = this.get( vertexProgram ).shaderGPU;
  39326. gl.attachShader( programGPU, fragmentShader );
  39327. gl.attachShader( programGPU, vertexShader );
  39328. gl.linkProgram( programGPU );
  39329. this.set( pipeline, {
  39330. programGPU,
  39331. fragmentShader,
  39332. vertexShader
  39333. } );
  39334. if ( promises !== null && this.parallel ) {
  39335. const p = new Promise( ( resolve /*, reject*/ ) => {
  39336. const parallel = this.parallel;
  39337. const checkStatus = () => {
  39338. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  39339. this._completeCompile( renderObject, pipeline );
  39340. resolve();
  39341. } else {
  39342. requestAnimationFrame( checkStatus );
  39343. }
  39344. };
  39345. checkStatus();
  39346. } );
  39347. promises.push( p );
  39348. return;
  39349. }
  39350. this._completeCompile( renderObject, pipeline );
  39351. }
  39352. _handleSource( string, errorLine ) {
  39353. const lines = string.split( '\n' );
  39354. const lines2 = [];
  39355. const from = Math.max( errorLine - 6, 0 );
  39356. const to = Math.min( errorLine + 6, lines.length );
  39357. for ( let i = from; i < to; i ++ ) {
  39358. const line = i + 1;
  39359. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  39360. }
  39361. return lines2.join( '\n' );
  39362. }
  39363. _getShaderErrors( gl, shader, type ) {
  39364. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  39365. const errors = gl.getShaderInfoLog( shader ).trim();
  39366. if ( status && errors === '' ) return '';
  39367. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  39368. if ( errorMatches ) {
  39369. const errorLine = parseInt( errorMatches[ 1 ] );
  39370. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  39371. } else {
  39372. return errors;
  39373. }
  39374. }
  39375. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  39376. if ( this.renderer.debug.checkShaderErrors ) {
  39377. const gl = this.gl;
  39378. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  39379. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39380. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  39381. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  39382. } else {
  39383. // default error reporting
  39384. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  39385. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  39386. console.error(
  39387. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  39388. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  39389. 'Program Info Log: ' + programLog + '\n' +
  39390. vertexErrors + '\n' +
  39391. fragmentErrors
  39392. );
  39393. }
  39394. } else if ( programLog !== '' ) {
  39395. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  39396. }
  39397. }
  39398. }
  39399. _completeCompile( renderObject, pipeline ) {
  39400. const gl = this.gl;
  39401. const pipelineData = this.get( pipeline );
  39402. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  39403. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39404. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39405. }
  39406. gl.useProgram( programGPU );
  39407. // Bindings
  39408. const bindings = renderObject.getBindings();
  39409. this._setupBindings( bindings, programGPU );
  39410. //
  39411. this.set( pipeline, {
  39412. programGPU
  39413. } );
  39414. }
  39415. createComputePipeline( computePipeline, bindings ) {
  39416. const gl = this.gl;
  39417. // Program
  39418. const fragmentProgram = {
  39419. stage: 'fragment',
  39420. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  39421. };
  39422. this.createProgram( fragmentProgram );
  39423. const { computeProgram } = computePipeline;
  39424. const programGPU = gl.createProgram();
  39425. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39426. const vertexShader = this.get( computeProgram ).shaderGPU;
  39427. const transforms = computeProgram.transforms;
  39428. const transformVaryingNames = [];
  39429. const transformAttributeNodes = [];
  39430. for ( let i = 0; i < transforms.length; i ++ ) {
  39431. const transform = transforms[ i ];
  39432. transformVaryingNames.push( transform.varyingName );
  39433. transformAttributeNodes.push( transform.attributeNode );
  39434. }
  39435. gl.attachShader( programGPU, fragmentShader );
  39436. gl.attachShader( programGPU, vertexShader );
  39437. gl.transformFeedbackVaryings(
  39438. programGPU,
  39439. transformVaryingNames,
  39440. gl.SEPARATE_ATTRIBS
  39441. );
  39442. gl.linkProgram( programGPU );
  39443. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39444. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39445. }
  39446. gl.useProgram( programGPU );
  39447. // Bindings
  39448. this.createBindings( null, bindings );
  39449. this._setupBindings( bindings, programGPU );
  39450. const attributeNodes = computeProgram.attributes;
  39451. const attributes = [];
  39452. const transformBuffers = [];
  39453. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  39454. const attribute = attributeNodes[ i ].node.attribute;
  39455. attributes.push( attribute );
  39456. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39457. }
  39458. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  39459. const attribute = transformAttributeNodes[ i ].attribute;
  39460. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39461. const attributeData = this.get( attribute );
  39462. transformBuffers.push( attributeData );
  39463. }
  39464. //
  39465. this.set( computePipeline, {
  39466. programGPU,
  39467. transformBuffers,
  39468. attributes
  39469. } );
  39470. }
  39471. createBindings( bindGroup, bindings ) {
  39472. this.updateBindings( bindGroup, bindings );
  39473. }
  39474. updateBindings( bindGroup, bindings ) {
  39475. const { gl } = this;
  39476. let groupIndex = 0;
  39477. let textureIndex = 0;
  39478. for ( const bindGroup of bindings ) {
  39479. for ( const binding of bindGroup.bindings ) {
  39480. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39481. const bufferGPU = gl.createBuffer();
  39482. const data = binding.buffer;
  39483. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39484. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39485. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  39486. this.set( binding, {
  39487. index: groupIndex ++,
  39488. bufferGPU
  39489. } );
  39490. } else if ( binding.isSampledTexture ) {
  39491. const { textureGPU, glTextureType } = this.get( binding.texture );
  39492. this.set( binding, {
  39493. index: textureIndex ++,
  39494. textureGPU,
  39495. glTextureType
  39496. } );
  39497. }
  39498. }
  39499. }
  39500. }
  39501. updateBinding( binding ) {
  39502. const gl = this.gl;
  39503. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39504. const bindingData = this.get( binding );
  39505. const bufferGPU = bindingData.bufferGPU;
  39506. const data = binding.buffer;
  39507. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39508. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39509. }
  39510. }
  39511. // attributes
  39512. createIndexAttribute( attribute ) {
  39513. const gl = this.gl;
  39514. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  39515. }
  39516. createAttribute( attribute ) {
  39517. if ( this.has( attribute ) ) return;
  39518. const gl = this.gl;
  39519. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39520. }
  39521. createStorageAttribute( attribute ) {
  39522. if ( this.has( attribute ) ) return;
  39523. const gl = this.gl;
  39524. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39525. }
  39526. updateAttribute( attribute ) {
  39527. this.attributeUtils.updateAttribute( attribute );
  39528. }
  39529. destroyAttribute( attribute ) {
  39530. this.attributeUtils.destroyAttribute( attribute );
  39531. }
  39532. updateSize() {
  39533. //console.warn( 'Abstract class.' );
  39534. }
  39535. hasFeature( name ) {
  39536. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  39537. const extensions = this.extensions;
  39538. for ( let i = 0; i < keysMatching.length; i ++ ) {
  39539. if ( extensions.has( keysMatching[ i ] ) ) return true;
  39540. }
  39541. return false;
  39542. }
  39543. getMaxAnisotropy() {
  39544. return this.capabilities.getMaxAnisotropy();
  39545. }
  39546. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  39547. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  39548. }
  39549. copyFramebufferToTexture( texture, renderContext ) {
  39550. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  39551. }
  39552. _setFramebuffer( renderContext ) {
  39553. const { gl, state } = this;
  39554. let currentFrameBuffer = null;
  39555. if ( renderContext.textures !== null ) {
  39556. const renderTarget = renderContext.renderTarget;
  39557. const renderTargetContextData = this.get( renderTarget );
  39558. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  39559. const cubeFace = this.renderer._activeCubeFace;
  39560. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  39561. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  39562. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  39563. let fb;
  39564. if ( isCube ) {
  39565. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  39566. renderTargetContextData.cubeFramebuffers = [];
  39567. }
  39568. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  39569. } else {
  39570. fb = renderTargetContextData.framebuffer;
  39571. }
  39572. if ( fb === undefined ) {
  39573. fb = gl.createFramebuffer();
  39574. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  39575. const textures = renderContext.textures;
  39576. if ( isCube ) {
  39577. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  39578. const { textureGPU } = this.get( textures[ 0 ] );
  39579. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  39580. } else {
  39581. for ( let i = 0; i < textures.length; i ++ ) {
  39582. const texture = textures[ i ];
  39583. const textureData = this.get( texture );
  39584. textureData.renderTarget = renderContext.renderTarget;
  39585. const attachment = gl.COLOR_ATTACHMENT0 + i;
  39586. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39587. }
  39588. renderTargetContextData.framebuffer = fb;
  39589. state.drawBuffers( renderContext, fb );
  39590. }
  39591. if ( renderContext.depthTexture !== null ) {
  39592. const textureData = this.get( renderContext.depthTexture );
  39593. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39594. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39595. }
  39596. }
  39597. if ( samples > 0 ) {
  39598. if ( msaaFb === undefined ) {
  39599. const invalidationArray = [];
  39600. msaaFb = gl.createFramebuffer();
  39601. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  39602. const msaaRenderbuffers = [];
  39603. const textures = renderContext.textures;
  39604. for ( let i = 0; i < textures.length; i ++ ) {
  39605. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  39606. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39607. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  39608. if ( depthBuffer ) {
  39609. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39610. invalidationArray.push( depthStyle );
  39611. }
  39612. const texture = renderContext.textures[ i ];
  39613. const textureData = this.get( texture );
  39614. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  39615. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39616. }
  39617. renderTargetContextData.msaaFrameBuffer = msaaFb;
  39618. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  39619. if ( depthRenderbuffer === undefined ) {
  39620. depthRenderbuffer = gl.createRenderbuffer();
  39621. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  39622. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  39623. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39624. invalidationArray.push( depthStyle );
  39625. }
  39626. renderTargetContextData.invalidationArray = invalidationArray;
  39627. }
  39628. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39629. } else {
  39630. currentFrameBuffer = fb;
  39631. }
  39632. }
  39633. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  39634. }
  39635. _getVaoKey( index, attributes ) {
  39636. let key = [];
  39637. if ( index !== null ) {
  39638. const indexData = this.get( index );
  39639. key += ':' + indexData.id;
  39640. }
  39641. for ( let i = 0; i < attributes.length; i ++ ) {
  39642. const attributeData = this.get( attributes[ i ] );
  39643. key += ':' + attributeData.id;
  39644. }
  39645. return key;
  39646. }
  39647. _createVao( index, attributes ) {
  39648. const { gl } = this;
  39649. const vaoGPU = gl.createVertexArray();
  39650. let key = '';
  39651. let staticVao = true;
  39652. gl.bindVertexArray( vaoGPU );
  39653. if ( index !== null ) {
  39654. const indexData = this.get( index );
  39655. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  39656. key += ':' + indexData.id;
  39657. }
  39658. for ( let i = 0; i < attributes.length; i ++ ) {
  39659. const attribute = attributes[ i ];
  39660. const attributeData = this.get( attribute );
  39661. key += ':' + attributeData.id;
  39662. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  39663. gl.enableVertexAttribArray( i );
  39664. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  39665. let stride, offset;
  39666. if ( attribute.isInterleavedBufferAttribute === true ) {
  39667. stride = attribute.data.stride * attributeData.bytesPerElement;
  39668. offset = attribute.offset * attributeData.bytesPerElement;
  39669. } else {
  39670. stride = 0;
  39671. offset = 0;
  39672. }
  39673. if ( attributeData.isInteger ) {
  39674. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  39675. } else {
  39676. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  39677. }
  39678. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  39679. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  39680. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  39681. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  39682. }
  39683. }
  39684. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  39685. this.vaoCache[ key ] = vaoGPU;
  39686. return { vaoGPU, staticVao };
  39687. }
  39688. _getTransformFeedback( transformBuffers ) {
  39689. let key = '';
  39690. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39691. key += ':' + transformBuffers[ i ].id;
  39692. }
  39693. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  39694. if ( transformFeedbackGPU !== undefined ) {
  39695. return transformFeedbackGPU;
  39696. }
  39697. const gl = this.gl;
  39698. transformFeedbackGPU = gl.createTransformFeedback();
  39699. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39700. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39701. const attributeData = transformBuffers[ i ];
  39702. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  39703. }
  39704. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39705. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  39706. return transformFeedbackGPU;
  39707. }
  39708. _setupBindings( bindings, programGPU ) {
  39709. const gl = this.gl;
  39710. for ( const bindGroup of bindings ) {
  39711. for ( const binding of bindGroup.bindings ) {
  39712. const bindingData = this.get( binding );
  39713. const index = bindingData.index;
  39714. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39715. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  39716. gl.uniformBlockBinding( programGPU, location, index );
  39717. } else if ( binding.isSampledTexture ) {
  39718. const location = gl.getUniformLocation( programGPU, binding.name );
  39719. gl.uniform1i( location, index );
  39720. }
  39721. }
  39722. }
  39723. }
  39724. _bindUniforms( bindings ) {
  39725. const { gl, state } = this;
  39726. for ( const bindGroup of bindings ) {
  39727. for ( const binding of bindGroup.bindings ) {
  39728. const bindingData = this.get( binding );
  39729. const index = bindingData.index;
  39730. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39731. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  39732. } else if ( binding.isSampledTexture ) {
  39733. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  39734. }
  39735. }
  39736. }
  39737. }
  39738. }
  39739. class Sampler extends Binding {
  39740. constructor( name, texture ) {
  39741. super( name );
  39742. this.texture = texture;
  39743. this.version = texture ? texture.version : 0;
  39744. this.isSampler = true;
  39745. }
  39746. }
  39747. class NodeSampler extends Sampler {
  39748. constructor( name, textureNode, groupNode ) {
  39749. super( name, textureNode ? textureNode.value : null );
  39750. this.textureNode = textureNode;
  39751. this.groupNode = groupNode;
  39752. }
  39753. update() {
  39754. this.texture = this.textureNode.value;
  39755. }
  39756. }
  39757. class StorageBuffer extends Buffer {
  39758. constructor( name, attribute ) {
  39759. super( name, attribute ? attribute.array : null );
  39760. this.attribute = attribute;
  39761. this.isStorageBuffer = true;
  39762. }
  39763. }
  39764. let _id = 0;
  39765. class NodeStorageBuffer extends StorageBuffer {
  39766. constructor( nodeUniform, groupNode ) {
  39767. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  39768. this.nodeUniform = nodeUniform;
  39769. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  39770. this.groupNode = groupNode;
  39771. }
  39772. get buffer() {
  39773. return this.nodeUniform.value;
  39774. }
  39775. }
  39776. class WebGPUTexturePassUtils {
  39777. constructor( device ) {
  39778. this.device = device;
  39779. const mipmapVertexSource = `
  39780. struct VarysStruct {
  39781. @builtin( position ) Position: vec4<f32>,
  39782. @location( 0 ) vTex : vec2<f32>
  39783. };
  39784. @vertex
  39785. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  39786. var Varys : VarysStruct;
  39787. var pos = array< vec2<f32>, 4 >(
  39788. vec2<f32>( -1.0, 1.0 ),
  39789. vec2<f32>( 1.0, 1.0 ),
  39790. vec2<f32>( -1.0, -1.0 ),
  39791. vec2<f32>( 1.0, -1.0 )
  39792. );
  39793. var tex = array< vec2<f32>, 4 >(
  39794. vec2<f32>( 0.0, 0.0 ),
  39795. vec2<f32>( 1.0, 0.0 ),
  39796. vec2<f32>( 0.0, 1.0 ),
  39797. vec2<f32>( 1.0, 1.0 )
  39798. );
  39799. Varys.vTex = tex[ vertexIndex ];
  39800. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  39801. return Varys;
  39802. }
  39803. `;
  39804. const mipmapFragmentSource = `
  39805. @group( 0 ) @binding( 0 )
  39806. var imgSampler : sampler;
  39807. @group( 0 ) @binding( 1 )
  39808. var img : texture_2d<f32>;
  39809. @fragment
  39810. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39811. return textureSample( img, imgSampler, vTex );
  39812. }
  39813. `;
  39814. const flipYFragmentSource = `
  39815. @group( 0 ) @binding( 0 )
  39816. var imgSampler : sampler;
  39817. @group( 0 ) @binding( 1 )
  39818. var img : texture_2d<f32>;
  39819. @fragment
  39820. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39821. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  39822. }
  39823. `;
  39824. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  39825. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  39826. // We'll need a new pipeline for every texture format used.
  39827. this.transferPipelines = {};
  39828. this.flipYPipelines = {};
  39829. this.mipmapVertexShaderModule = device.createShaderModule( {
  39830. label: 'mipmapVertex',
  39831. code: mipmapVertexSource
  39832. } );
  39833. this.mipmapFragmentShaderModule = device.createShaderModule( {
  39834. label: 'mipmapFragment',
  39835. code: mipmapFragmentSource
  39836. } );
  39837. this.flipYFragmentShaderModule = device.createShaderModule( {
  39838. label: 'flipYFragment',
  39839. code: flipYFragmentSource
  39840. } );
  39841. }
  39842. getTransferPipeline( format ) {
  39843. let pipeline = this.transferPipelines[ format ];
  39844. if ( pipeline === undefined ) {
  39845. pipeline = this.device.createRenderPipeline( {
  39846. vertex: {
  39847. module: this.mipmapVertexShaderModule,
  39848. entryPoint: 'main'
  39849. },
  39850. fragment: {
  39851. module: this.mipmapFragmentShaderModule,
  39852. entryPoint: 'main',
  39853. targets: [ { format } ]
  39854. },
  39855. primitive: {
  39856. topology: GPUPrimitiveTopology.TriangleStrip,
  39857. stripIndexFormat: GPUIndexFormat.Uint32
  39858. },
  39859. layout: 'auto'
  39860. } );
  39861. this.transferPipelines[ format ] = pipeline;
  39862. }
  39863. return pipeline;
  39864. }
  39865. getFlipYPipeline( format ) {
  39866. let pipeline = this.flipYPipelines[ format ];
  39867. if ( pipeline === undefined ) {
  39868. pipeline = this.device.createRenderPipeline( {
  39869. vertex: {
  39870. module: this.mipmapVertexShaderModule,
  39871. entryPoint: 'main'
  39872. },
  39873. fragment: {
  39874. module: this.flipYFragmentShaderModule,
  39875. entryPoint: 'main',
  39876. targets: [ { format } ]
  39877. },
  39878. primitive: {
  39879. topology: GPUPrimitiveTopology.TriangleStrip,
  39880. stripIndexFormat: GPUIndexFormat.Uint32
  39881. },
  39882. layout: 'auto'
  39883. } );
  39884. this.flipYPipelines[ format ] = pipeline;
  39885. }
  39886. return pipeline;
  39887. }
  39888. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39889. const format = textureGPUDescriptor.format;
  39890. const { width, height } = textureGPUDescriptor.size;
  39891. const transferPipeline = this.getTransferPipeline( format );
  39892. const flipYPipeline = this.getFlipYPipeline( format );
  39893. const tempTexture = this.device.createTexture( {
  39894. size: { width, height, depthOrArrayLayers: 1 },
  39895. format,
  39896. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  39897. } );
  39898. const srcView = textureGPU.createView( {
  39899. baseMipLevel: 0,
  39900. mipLevelCount: 1,
  39901. dimension: GPUTextureViewDimension.TwoD,
  39902. baseArrayLayer
  39903. } );
  39904. const dstView = tempTexture.createView( {
  39905. baseMipLevel: 0,
  39906. mipLevelCount: 1,
  39907. dimension: GPUTextureViewDimension.TwoD,
  39908. baseArrayLayer: 0
  39909. } );
  39910. const commandEncoder = this.device.createCommandEncoder( {} );
  39911. const pass = ( pipeline, sourceView, destinationView ) => {
  39912. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39913. const bindGroup = this.device.createBindGroup( {
  39914. layout: bindGroupLayout,
  39915. entries: [ {
  39916. binding: 0,
  39917. resource: this.flipYSampler
  39918. }, {
  39919. binding: 1,
  39920. resource: sourceView
  39921. } ]
  39922. } );
  39923. const passEncoder = commandEncoder.beginRenderPass( {
  39924. colorAttachments: [ {
  39925. view: destinationView,
  39926. loadOp: GPULoadOp.Clear,
  39927. storeOp: GPUStoreOp.Store,
  39928. clearValue: [ 0, 0, 0, 0 ]
  39929. } ]
  39930. } );
  39931. passEncoder.setPipeline( pipeline );
  39932. passEncoder.setBindGroup( 0, bindGroup );
  39933. passEncoder.draw( 4, 1, 0, 0 );
  39934. passEncoder.end();
  39935. };
  39936. pass( transferPipeline, srcView, dstView );
  39937. pass( flipYPipeline, dstView, srcView );
  39938. this.device.queue.submit( [ commandEncoder.finish() ] );
  39939. tempTexture.destroy();
  39940. }
  39941. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39942. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  39943. const commandEncoder = this.device.createCommandEncoder( {} );
  39944. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39945. let srcView = textureGPU.createView( {
  39946. baseMipLevel: 0,
  39947. mipLevelCount: 1,
  39948. dimension: GPUTextureViewDimension.TwoD,
  39949. baseArrayLayer
  39950. } );
  39951. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  39952. const bindGroup = this.device.createBindGroup( {
  39953. layout: bindGroupLayout,
  39954. entries: [ {
  39955. binding: 0,
  39956. resource: this.mipmapSampler
  39957. }, {
  39958. binding: 1,
  39959. resource: srcView
  39960. } ]
  39961. } );
  39962. const dstView = textureGPU.createView( {
  39963. baseMipLevel: i,
  39964. mipLevelCount: 1,
  39965. dimension: GPUTextureViewDimension.TwoD,
  39966. baseArrayLayer
  39967. } );
  39968. const passEncoder = commandEncoder.beginRenderPass( {
  39969. colorAttachments: [ {
  39970. view: dstView,
  39971. loadOp: GPULoadOp.Clear,
  39972. storeOp: GPUStoreOp.Store,
  39973. clearValue: [ 0, 0, 0, 0 ]
  39974. } ]
  39975. } );
  39976. passEncoder.setPipeline( pipeline );
  39977. passEncoder.setBindGroup( 0, bindGroup );
  39978. passEncoder.draw( 4, 1, 0, 0 );
  39979. passEncoder.end();
  39980. srcView = dstView;
  39981. }
  39982. this.device.queue.submit( [ commandEncoder.finish() ] );
  39983. }
  39984. }
  39985. const _compareToWebGPU = {
  39986. [ NeverCompare ]: 'never',
  39987. [ LessCompare ]: 'less',
  39988. [ EqualCompare ]: 'equal',
  39989. [ LessEqualCompare ]: 'less-equal',
  39990. [ GreaterCompare ]: 'greater',
  39991. [ GreaterEqualCompare ]: 'greater-equal',
  39992. [ AlwaysCompare ]: 'always',
  39993. [ NotEqualCompare ]: 'not-equal'
  39994. };
  39995. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  39996. class WebGPUTextureUtils {
  39997. constructor( backend ) {
  39998. this.backend = backend;
  39999. this._passUtils = null;
  40000. this.defaultTexture = {};
  40001. this.defaultCubeTexture = {};
  40002. this.colorBuffer = null;
  40003. this.depthTexture = new DepthTexture();
  40004. this.depthTexture.name = 'depthBuffer';
  40005. }
  40006. createSampler( texture ) {
  40007. const backend = this.backend;
  40008. const device = backend.device;
  40009. const textureGPU = backend.get( texture );
  40010. const samplerDescriptorGPU = {
  40011. addressModeU: this._convertAddressMode( texture.wrapS ),
  40012. addressModeV: this._convertAddressMode( texture.wrapT ),
  40013. addressModeW: this._convertAddressMode( texture.wrapR ),
  40014. magFilter: this._convertFilterMode( texture.magFilter ),
  40015. minFilter: this._convertFilterMode( texture.minFilter ),
  40016. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  40017. maxAnisotropy: texture.anisotropy
  40018. };
  40019. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  40020. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  40021. }
  40022. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  40023. }
  40024. createDefaultTexture( texture ) {
  40025. let textureGPU;
  40026. const format = getFormat( texture );
  40027. if ( texture.isCubeTexture ) {
  40028. textureGPU = this._getDefaultCubeTextureGPU( format );
  40029. } else {
  40030. textureGPU = this._getDefaultTextureGPU( format );
  40031. }
  40032. this.backend.get( texture ).texture = textureGPU;
  40033. }
  40034. createTexture( texture, options = {} ) {
  40035. const backend = this.backend;
  40036. const textureData = backend.get( texture );
  40037. if ( textureData.initialized ) {
  40038. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  40039. }
  40040. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  40041. if ( options.levels === undefined ) options.levels = 1;
  40042. if ( options.depth === undefined ) options.depth = 1;
  40043. const { width, height, depth, levels } = options;
  40044. const dimension = this._getDimension( texture );
  40045. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  40046. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  40047. sampleCount = backend.utils.getSampleCount( sampleCount );
  40048. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  40049. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  40050. if ( texture.isStorageTexture === true ) {
  40051. usage |= GPUTextureUsage.STORAGE_BINDING;
  40052. }
  40053. if ( texture.isCompressedTexture !== true ) {
  40054. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  40055. }
  40056. const textureDescriptorGPU = {
  40057. label: texture.name,
  40058. size: {
  40059. width: width,
  40060. height: height,
  40061. depthOrArrayLayers: depth,
  40062. },
  40063. mipLevelCount: levels,
  40064. sampleCount: primarySampleCount,
  40065. dimension: dimension,
  40066. format: format,
  40067. usage: usage
  40068. };
  40069. // texture creation
  40070. if ( texture.isVideoTexture ) {
  40071. const video = texture.source.data;
  40072. const videoFrame = new VideoFrame( video );
  40073. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  40074. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  40075. videoFrame.close();
  40076. textureData.externalTexture = video;
  40077. } else {
  40078. if ( format === undefined ) {
  40079. console.warn( 'WebGPURenderer: Texture format not supported.' );
  40080. return this.createDefaultTexture( texture );
  40081. }
  40082. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  40083. }
  40084. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  40085. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  40086. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  40087. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  40088. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  40089. }
  40090. textureData.initialized = true;
  40091. textureData.textureDescriptorGPU = textureDescriptorGPU;
  40092. }
  40093. destroyTexture( texture ) {
  40094. const backend = this.backend;
  40095. const textureData = backend.get( texture );
  40096. textureData.texture.destroy();
  40097. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  40098. backend.delete( texture );
  40099. }
  40100. destroySampler( texture ) {
  40101. const backend = this.backend;
  40102. const textureData = backend.get( texture );
  40103. delete textureData.sampler;
  40104. }
  40105. generateMipmaps( texture ) {
  40106. const textureData = this.backend.get( texture );
  40107. if ( texture.isCubeTexture ) {
  40108. for ( let i = 0; i < 6; i ++ ) {
  40109. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  40110. }
  40111. } else {
  40112. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU );
  40113. }
  40114. }
  40115. getColorBuffer() {
  40116. if ( this.colorBuffer ) this.colorBuffer.destroy();
  40117. const backend = this.backend;
  40118. const { width, height } = backend.getDrawingBufferSize();
  40119. this.colorBuffer = backend.device.createTexture( {
  40120. label: 'colorBuffer',
  40121. size: {
  40122. width: width,
  40123. height: height,
  40124. depthOrArrayLayers: 1
  40125. },
  40126. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  40127. format: GPUTextureFormat.BGRA8Unorm,
  40128. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  40129. } );
  40130. return this.colorBuffer;
  40131. }
  40132. getDepthBuffer( depth = true, stencil = false ) {
  40133. const backend = this.backend;
  40134. const { width, height } = backend.getDrawingBufferSize();
  40135. const depthTexture = this.depthTexture;
  40136. const depthTextureGPU = backend.get( depthTexture ).texture;
  40137. let format, type;
  40138. if ( stencil ) {
  40139. format = DepthStencilFormat;
  40140. type = UnsignedInt248Type;
  40141. } else if ( depth ) {
  40142. format = DepthFormat;
  40143. type = UnsignedIntType;
  40144. }
  40145. if ( depthTextureGPU !== undefined ) {
  40146. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  40147. return depthTextureGPU;
  40148. }
  40149. this.destroyTexture( depthTexture );
  40150. }
  40151. depthTexture.name = 'depthBuffer';
  40152. depthTexture.format = format;
  40153. depthTexture.type = type;
  40154. depthTexture.image.width = width;
  40155. depthTexture.image.height = height;
  40156. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  40157. return backend.get( depthTexture ).texture;
  40158. }
  40159. updateTexture( texture, options ) {
  40160. const textureData = this.backend.get( texture );
  40161. const { textureDescriptorGPU } = textureData;
  40162. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  40163. return;
  40164. // transfer texture data
  40165. if ( texture.isDataTexture ) {
  40166. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40167. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  40168. for ( let i = 0; i < options.image.depth; i ++ ) {
  40169. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  40170. }
  40171. } else if ( texture.isCompressedTexture ) {
  40172. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  40173. } else if ( texture.isCubeTexture ) {
  40174. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  40175. } else if ( texture.isVideoTexture ) {
  40176. const video = texture.source.data;
  40177. textureData.externalTexture = video;
  40178. } else {
  40179. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40180. }
  40181. //
  40182. textureData.version = texture.version;
  40183. if ( texture.onUpdate ) texture.onUpdate( texture );
  40184. }
  40185. async copyTextureToBuffer( texture, x, y, width, height ) {
  40186. const device = this.backend.device;
  40187. const textureData = this.backend.get( texture );
  40188. const textureGPU = textureData.texture;
  40189. const format = textureData.textureDescriptorGPU.format;
  40190. const bytesPerTexel = this._getBytesPerTexel( format );
  40191. let bytesPerRow = width * bytesPerTexel;
  40192. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  40193. const readBuffer = device.createBuffer(
  40194. {
  40195. size: width * height * bytesPerTexel,
  40196. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  40197. }
  40198. );
  40199. const encoder = device.createCommandEncoder();
  40200. encoder.copyTextureToBuffer(
  40201. {
  40202. texture: textureGPU,
  40203. origin: { x, y },
  40204. },
  40205. {
  40206. buffer: readBuffer,
  40207. bytesPerRow: bytesPerRow
  40208. },
  40209. {
  40210. width: width,
  40211. height: height
  40212. }
  40213. );
  40214. const typedArrayType = this._getTypedArrayType( format );
  40215. device.queue.submit( [ encoder.finish() ] );
  40216. await readBuffer.mapAsync( GPUMapMode.READ );
  40217. const buffer = readBuffer.getMappedRange();
  40218. return new typedArrayType( buffer );
  40219. }
  40220. _isEnvironmentTexture( texture ) {
  40221. const mapping = texture.mapping;
  40222. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  40223. }
  40224. _getDefaultTextureGPU( format ) {
  40225. let defaultTexture = this.defaultTexture[ format ];
  40226. if ( defaultTexture === undefined ) {
  40227. const texture = new Texture();
  40228. texture.minFilter = NearestFilter;
  40229. texture.magFilter = NearestFilter;
  40230. this.createTexture( texture, { width: 1, height: 1, format } );
  40231. this.defaultTexture[ format ] = defaultTexture = texture;
  40232. }
  40233. return this.backend.get( defaultTexture ).texture;
  40234. }
  40235. _getDefaultCubeTextureGPU( format ) {
  40236. let defaultCubeTexture = this.defaultTexture[ format ];
  40237. if ( defaultCubeTexture === undefined ) {
  40238. const texture = new CubeTexture();
  40239. texture.minFilter = NearestFilter;
  40240. texture.magFilter = NearestFilter;
  40241. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  40242. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  40243. }
  40244. return this.backend.get( defaultCubeTexture ).texture;
  40245. }
  40246. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  40247. for ( let i = 0; i < 6; i ++ ) {
  40248. const image = images[ i ];
  40249. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  40250. if ( image.isDataTexture ) {
  40251. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40252. } else {
  40253. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40254. }
  40255. }
  40256. }
  40257. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  40258. const device = this.backend.device;
  40259. device.queue.copyExternalImageToTexture(
  40260. {
  40261. source: image
  40262. }, {
  40263. texture: textureGPU,
  40264. mipLevel: 0,
  40265. origin: { x: 0, y: 0, z: originDepth }
  40266. }, {
  40267. width: image.width,
  40268. height: image.height,
  40269. depthOrArrayLayers: 1
  40270. }
  40271. );
  40272. if ( flipY === true ) {
  40273. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40274. }
  40275. }
  40276. _getPassUtils() {
  40277. let passUtils = this._passUtils;
  40278. if ( passUtils === null ) {
  40279. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  40280. }
  40281. return passUtils;
  40282. }
  40283. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  40284. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  40285. }
  40286. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  40287. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  40288. }
  40289. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  40290. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40291. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  40292. const device = this.backend.device;
  40293. const data = image.data;
  40294. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  40295. const bytesPerRow = image.width * bytesPerTexel;
  40296. device.queue.writeTexture(
  40297. {
  40298. texture: textureGPU,
  40299. mipLevel: 0,
  40300. origin: { x: 0, y: 0, z: originDepth }
  40301. },
  40302. data,
  40303. {
  40304. offset: image.width * image.height * bytesPerTexel * depth,
  40305. bytesPerRow
  40306. },
  40307. {
  40308. width: image.width,
  40309. height: image.height,
  40310. depthOrArrayLayers: 1
  40311. } );
  40312. if ( flipY === true ) {
  40313. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40314. }
  40315. }
  40316. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  40317. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40318. const device = this.backend.device;
  40319. const blockData = this._getBlockData( textureDescriptorGPU.format );
  40320. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40321. const mipmap = mipmaps[ i ];
  40322. const width = mipmap.width;
  40323. const height = mipmap.height;
  40324. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  40325. device.queue.writeTexture(
  40326. {
  40327. texture: textureGPU,
  40328. mipLevel: i
  40329. },
  40330. mipmap.data,
  40331. {
  40332. offset: 0,
  40333. bytesPerRow
  40334. },
  40335. {
  40336. width: Math.ceil( width / blockData.width ) * blockData.width,
  40337. height: Math.ceil( height / blockData.width ) * blockData.width,
  40338. depthOrArrayLayers: 1
  40339. }
  40340. );
  40341. }
  40342. }
  40343. _getBlockData( format ) {
  40344. // this method is only relevant for compressed texture formats
  40345. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  40346. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  40347. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  40348. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  40349. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  40350. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  40351. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  40352. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40353. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40354. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40355. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  40356. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  40357. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  40358. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  40359. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40360. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  40361. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  40362. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  40363. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  40364. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  40365. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  40366. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  40367. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  40368. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  40369. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  40370. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  40371. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  40372. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  40373. }
  40374. _convertAddressMode( value ) {
  40375. let addressMode = GPUAddressMode.ClampToEdge;
  40376. if ( value === RepeatWrapping ) {
  40377. addressMode = GPUAddressMode.Repeat;
  40378. } else if ( value === MirroredRepeatWrapping ) {
  40379. addressMode = GPUAddressMode.MirrorRepeat;
  40380. }
  40381. return addressMode;
  40382. }
  40383. _convertFilterMode( value ) {
  40384. let filterMode = GPUFilterMode.Linear;
  40385. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  40386. filterMode = GPUFilterMode.Nearest;
  40387. }
  40388. return filterMode;
  40389. }
  40390. _getBytesPerTexel( format ) {
  40391. // 8-bit formats
  40392. if ( format === GPUTextureFormat.R8Unorm ||
  40393. format === GPUTextureFormat.R8Snorm ||
  40394. format === GPUTextureFormat.R8Uint ||
  40395. format === GPUTextureFormat.R8Sint ) return 1;
  40396. // 16-bit formats
  40397. if ( format === GPUTextureFormat.R16Uint ||
  40398. format === GPUTextureFormat.R16Sint ||
  40399. format === GPUTextureFormat.R16Float ||
  40400. format === GPUTextureFormat.RG8Unorm ||
  40401. format === GPUTextureFormat.RG8Snorm ||
  40402. format === GPUTextureFormat.RG8Uint ||
  40403. format === GPUTextureFormat.RG8Sint ) return 2;
  40404. // 32-bit formats
  40405. if ( format === GPUTextureFormat.R32Uint ||
  40406. format === GPUTextureFormat.R32Sint ||
  40407. format === GPUTextureFormat.R32Float ||
  40408. format === GPUTextureFormat.RG16Uint ||
  40409. format === GPUTextureFormat.RG16Sint ||
  40410. format === GPUTextureFormat.RG16Float ||
  40411. format === GPUTextureFormat.RGBA8Unorm ||
  40412. format === GPUTextureFormat.RGBA8UnormSRGB ||
  40413. format === GPUTextureFormat.RGBA8Snorm ||
  40414. format === GPUTextureFormat.RGBA8Uint ||
  40415. format === GPUTextureFormat.RGBA8Sint ||
  40416. format === GPUTextureFormat.BGRA8Unorm ||
  40417. format === GPUTextureFormat.BGRA8UnormSRGB ||
  40418. // Packed 32-bit formats
  40419. format === GPUTextureFormat.RGB9E5UFloat ||
  40420. format === GPUTextureFormat.RGB10A2Unorm ||
  40421. format === GPUTextureFormat.RG11B10UFloat ||
  40422. format === GPUTextureFormat.Depth32Float ||
  40423. format === GPUTextureFormat.Depth24Plus ||
  40424. format === GPUTextureFormat.Depth24PlusStencil8 ||
  40425. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  40426. // 64-bit formats
  40427. if ( format === GPUTextureFormat.RG32Uint ||
  40428. format === GPUTextureFormat.RG32Sint ||
  40429. format === GPUTextureFormat.RG32Float ||
  40430. format === GPUTextureFormat.RGBA16Uint ||
  40431. format === GPUTextureFormat.RGBA16Sint ||
  40432. format === GPUTextureFormat.RGBA16Float ) return 8;
  40433. // 128-bit formats
  40434. if ( format === GPUTextureFormat.RGBA32Uint ||
  40435. format === GPUTextureFormat.RGBA32Sint ||
  40436. format === GPUTextureFormat.RGBA32Float ) return 16;
  40437. }
  40438. _getTypedArrayType( format ) {
  40439. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  40440. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  40441. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  40442. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  40443. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  40444. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  40445. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  40446. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  40447. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  40448. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  40449. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  40450. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  40451. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  40452. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  40453. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  40454. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  40455. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  40456. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  40457. if ( format === GPUTextureFormat.R16Float ) return Float32Array;
  40458. if ( format === GPUTextureFormat.RG16Float ) return Float32Array;
  40459. if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array;
  40460. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  40461. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  40462. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  40463. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  40464. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  40465. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  40466. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  40467. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  40468. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  40469. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  40470. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  40471. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  40472. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  40473. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  40474. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  40475. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  40476. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  40477. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  40478. }
  40479. _getDimension( texture ) {
  40480. let dimension;
  40481. if ( texture.isData3DTexture ) {
  40482. dimension = GPUTextureDimension.ThreeD;
  40483. } else {
  40484. dimension = GPUTextureDimension.TwoD;
  40485. }
  40486. return dimension;
  40487. }
  40488. }
  40489. function getFormat( texture, device = null ) {
  40490. const format = texture.format;
  40491. const type = texture.type;
  40492. const colorSpace = texture.colorSpace;
  40493. let formatGPU;
  40494. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  40495. formatGPU = GPUTextureFormat.BGRA8Unorm;
  40496. } else if ( texture.isCompressedTexture === true ) {
  40497. switch ( format ) {
  40498. case RGBA_S3TC_DXT1_Format:
  40499. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  40500. break;
  40501. case RGBA_S3TC_DXT3_Format:
  40502. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  40503. break;
  40504. case RGBA_S3TC_DXT5_Format:
  40505. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  40506. break;
  40507. case RGB_ETC2_Format:
  40508. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  40509. break;
  40510. case RGBA_ETC2_EAC_Format:
  40511. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  40512. break;
  40513. case RGBA_ASTC_4x4_Format:
  40514. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  40515. break;
  40516. case RGBA_ASTC_5x4_Format:
  40517. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  40518. break;
  40519. case RGBA_ASTC_5x5_Format:
  40520. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  40521. break;
  40522. case RGBA_ASTC_6x5_Format:
  40523. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  40524. break;
  40525. case RGBA_ASTC_6x6_Format:
  40526. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  40527. break;
  40528. case RGBA_ASTC_8x5_Format:
  40529. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  40530. break;
  40531. case RGBA_ASTC_8x6_Format:
  40532. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  40533. break;
  40534. case RGBA_ASTC_8x8_Format:
  40535. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  40536. break;
  40537. case RGBA_ASTC_10x5_Format:
  40538. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  40539. break;
  40540. case RGBA_ASTC_10x6_Format:
  40541. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  40542. break;
  40543. case RGBA_ASTC_10x8_Format:
  40544. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  40545. break;
  40546. case RGBA_ASTC_10x10_Format:
  40547. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  40548. break;
  40549. case RGBA_ASTC_12x10_Format:
  40550. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  40551. break;
  40552. case RGBA_ASTC_12x12_Format:
  40553. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  40554. break;
  40555. default:
  40556. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40557. }
  40558. } else {
  40559. switch ( format ) {
  40560. case RGBAFormat:
  40561. switch ( type ) {
  40562. case ByteType:
  40563. formatGPU = GPUTextureFormat.RGBA8Snorm;
  40564. break;
  40565. case ShortType:
  40566. formatGPU = GPUTextureFormat.RGBA16Sint;
  40567. break;
  40568. case UnsignedShortType:
  40569. formatGPU = GPUTextureFormat.RGBA16Uint;
  40570. break;
  40571. case UnsignedIntType:
  40572. formatGPU = GPUTextureFormat.RGBA32Uint;
  40573. break;
  40574. case IntType:
  40575. formatGPU = GPUTextureFormat.RGBA32Sint;
  40576. break;
  40577. case UnsignedByteType:
  40578. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  40579. break;
  40580. case HalfFloatType:
  40581. formatGPU = GPUTextureFormat.RGBA16Float;
  40582. break;
  40583. case FloatType:
  40584. formatGPU = GPUTextureFormat.RGBA32Float;
  40585. break;
  40586. default:
  40587. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  40588. }
  40589. break;
  40590. case RGBFormat:
  40591. switch ( type ) {
  40592. case UnsignedInt5999Type:
  40593. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  40594. break;
  40595. default:
  40596. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  40597. }
  40598. break;
  40599. case RedFormat:
  40600. switch ( type ) {
  40601. case ByteType:
  40602. formatGPU = GPUTextureFormat.R8Snorm;
  40603. break;
  40604. case ShortType:
  40605. formatGPU = GPUTextureFormat.R16Sint;
  40606. break;
  40607. case UnsignedShortType:
  40608. formatGPU = GPUTextureFormat.R16Uint;
  40609. break;
  40610. case UnsignedIntType:
  40611. formatGPU = GPUTextureFormat.R32Uint;
  40612. break;
  40613. case IntType:
  40614. formatGPU = GPUTextureFormat.R32Sint;
  40615. break;
  40616. case UnsignedByteType:
  40617. formatGPU = GPUTextureFormat.R8Unorm;
  40618. break;
  40619. case HalfFloatType:
  40620. formatGPU = GPUTextureFormat.R16Float;
  40621. break;
  40622. case FloatType:
  40623. formatGPU = GPUTextureFormat.R32Float;
  40624. break;
  40625. default:
  40626. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  40627. }
  40628. break;
  40629. case RGFormat:
  40630. switch ( type ) {
  40631. case ByteType:
  40632. formatGPU = GPUTextureFormat.RG8Snorm;
  40633. break;
  40634. case ShortType:
  40635. formatGPU = GPUTextureFormat.RG16Sint;
  40636. break;
  40637. case UnsignedShortType:
  40638. formatGPU = GPUTextureFormat.RG16Uint;
  40639. break;
  40640. case UnsignedIntType:
  40641. formatGPU = GPUTextureFormat.RG32Uint;
  40642. break;
  40643. case IntType:
  40644. formatGPU = GPUTextureFormat.RG32Sint;
  40645. break;
  40646. case UnsignedByteType:
  40647. formatGPU = GPUTextureFormat.RG8Unorm;
  40648. break;
  40649. case HalfFloatType:
  40650. formatGPU = GPUTextureFormat.RG16Float;
  40651. break;
  40652. case FloatType:
  40653. formatGPU = GPUTextureFormat.RG32Float;
  40654. break;
  40655. default:
  40656. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  40657. }
  40658. break;
  40659. case DepthFormat:
  40660. switch ( type ) {
  40661. case UnsignedShortType:
  40662. formatGPU = GPUTextureFormat.Depth16Unorm;
  40663. break;
  40664. case UnsignedIntType:
  40665. formatGPU = GPUTextureFormat.Depth24Plus;
  40666. break;
  40667. case FloatType:
  40668. formatGPU = GPUTextureFormat.Depth32Float;
  40669. break;
  40670. default:
  40671. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  40672. }
  40673. break;
  40674. case DepthStencilFormat:
  40675. switch ( type ) {
  40676. case UnsignedInt248Type:
  40677. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  40678. break;
  40679. case FloatType:
  40680. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  40681. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  40682. }
  40683. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  40684. break;
  40685. default:
  40686. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  40687. }
  40688. break;
  40689. case RedIntegerFormat:
  40690. switch ( type ) {
  40691. case IntType:
  40692. formatGPU = GPUTextureFormat.R32Sint;
  40693. break;
  40694. case UnsignedIntType:
  40695. formatGPU = GPUTextureFormat.R32Uint;
  40696. break;
  40697. default:
  40698. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  40699. }
  40700. break;
  40701. case RGIntegerFormat:
  40702. switch ( type ) {
  40703. case IntType:
  40704. formatGPU = GPUTextureFormat.RG32Sint;
  40705. break;
  40706. case UnsignedIntType:
  40707. formatGPU = GPUTextureFormat.RG32Uint;
  40708. break;
  40709. default:
  40710. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  40711. }
  40712. break;
  40713. case RGBAIntegerFormat:
  40714. switch ( type ) {
  40715. case IntType:
  40716. formatGPU = GPUTextureFormat.RGBA32Sint;
  40717. break;
  40718. case UnsignedIntType:
  40719. formatGPU = GPUTextureFormat.RGBA32Uint;
  40720. break;
  40721. default:
  40722. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  40723. }
  40724. break;
  40725. default:
  40726. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40727. }
  40728. }
  40729. return formatGPU;
  40730. }
  40731. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  40732. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  40733. const wgslTypeLib$1 = {
  40734. 'f32': 'float',
  40735. 'i32': 'int',
  40736. 'u32': 'uint',
  40737. 'bool': 'bool',
  40738. 'vec2<f32>': 'vec2',
  40739. 'vec2<i32>': 'ivec2',
  40740. 'vec2<u32>': 'uvec2',
  40741. 'vec2<bool>': 'bvec2',
  40742. 'vec2f': 'vec2',
  40743. 'vec2i': 'ivec2',
  40744. 'vec2u': 'uvec2',
  40745. 'vec2b': 'bvec2',
  40746. 'vec3<f32>': 'vec3',
  40747. 'vec3<i32>': 'ivec3',
  40748. 'vec3<u32>': 'uvec3',
  40749. 'vec3<bool>': 'bvec3',
  40750. 'vec3f': 'vec3',
  40751. 'vec3i': 'ivec3',
  40752. 'vec3u': 'uvec3',
  40753. 'vec3b': 'bvec3',
  40754. 'vec4<f32>': 'vec4',
  40755. 'vec4<i32>': 'ivec4',
  40756. 'vec4<u32>': 'uvec4',
  40757. 'vec4<bool>': 'bvec4',
  40758. 'vec4f': 'vec4',
  40759. 'vec4i': 'ivec4',
  40760. 'vec4u': 'uvec4',
  40761. 'vec4b': 'bvec4',
  40762. 'mat2x2<f32>': 'mat2',
  40763. 'mat2x2f': 'mat2',
  40764. 'mat3x3<f32>': 'mat3',
  40765. 'mat3x3f': 'mat3',
  40766. 'mat4x4<f32>': 'mat4',
  40767. 'mat4x4f': 'mat4',
  40768. 'sampler': 'sampler',
  40769. 'texture_2d': 'texture',
  40770. 'texture_cube': 'cubeTexture',
  40771. 'texture_depth_2d': 'depthTexture',
  40772. 'texture_storage_2d': 'storageTexture',
  40773. 'texture_3d': 'texture3D'
  40774. };
  40775. const parse = ( source ) => {
  40776. source = source.trim();
  40777. const declaration = source.match( declarationRegexp );
  40778. if ( declaration !== null && declaration.length === 4 ) {
  40779. const inputsCode = declaration[ 2 ];
  40780. const propsMatches = [];
  40781. let match = null;
  40782. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  40783. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  40784. }
  40785. // Process matches to correctly pair names and types
  40786. const inputs = [];
  40787. for ( let i = 0; i < propsMatches.length; i ++ ) {
  40788. const { name, type } = propsMatches[ i ];
  40789. let resolvedType = type;
  40790. if ( resolvedType.startsWith( 'texture' ) ) {
  40791. resolvedType = type.split( '<' )[ 0 ];
  40792. }
  40793. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  40794. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  40795. }
  40796. const blockCode = source.substring( declaration[ 0 ].length );
  40797. const outputType = declaration[ 3 ] || 'void';
  40798. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  40799. const type = wgslTypeLib$1[ outputType ] || outputType;
  40800. return {
  40801. type,
  40802. inputs,
  40803. name,
  40804. inputsCode,
  40805. blockCode,
  40806. outputType
  40807. };
  40808. } else {
  40809. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  40810. }
  40811. };
  40812. class WGSLNodeFunction extends NodeFunction {
  40813. constructor( source ) {
  40814. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  40815. super( type, inputs, name );
  40816. this.inputsCode = inputsCode;
  40817. this.blockCode = blockCode;
  40818. this.outputType = outputType;
  40819. }
  40820. getCode( name = this.name ) {
  40821. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  40822. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  40823. }
  40824. }
  40825. class WGSLNodeParser extends NodeParser {
  40826. parseFunction( source ) {
  40827. return new WGSLNodeFunction( source );
  40828. }
  40829. }
  40830. // GPUShaderStage is not defined in browsers not supporting WebGPU
  40831. const GPUShaderStage = self.GPUShaderStage;
  40832. const gpuShaderStageLib = {
  40833. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  40834. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  40835. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  40836. };
  40837. const supports = {
  40838. instance: true,
  40839. swizzleAssign: false,
  40840. storageBuffer: true
  40841. };
  40842. const wgslFnOpLib = {
  40843. '^^': 'threejs_xor'
  40844. };
  40845. const wgslTypeLib = {
  40846. float: 'f32',
  40847. int: 'i32',
  40848. uint: 'u32',
  40849. bool: 'bool',
  40850. color: 'vec3<f32>',
  40851. vec2: 'vec2<f32>',
  40852. ivec2: 'vec2<i32>',
  40853. uvec2: 'vec2<u32>',
  40854. bvec2: 'vec2<bool>',
  40855. vec3: 'vec3<f32>',
  40856. ivec3: 'vec3<i32>',
  40857. uvec3: 'vec3<u32>',
  40858. bvec3: 'vec3<bool>',
  40859. vec4: 'vec4<f32>',
  40860. ivec4: 'vec4<i32>',
  40861. uvec4: 'vec4<u32>',
  40862. bvec4: 'vec4<bool>',
  40863. mat2: 'mat2x2<f32>',
  40864. imat2: 'mat2x2<i32>',
  40865. umat2: 'mat2x2<u32>',
  40866. bmat2: 'mat2x2<bool>',
  40867. mat3: 'mat3x3<f32>',
  40868. imat3: 'mat3x3<i32>',
  40869. umat3: 'mat3x3<u32>',
  40870. bmat3: 'mat3x3<bool>',
  40871. mat4: 'mat4x4<f32>',
  40872. imat4: 'mat4x4<i32>',
  40873. umat4: 'mat4x4<u32>',
  40874. bmat4: 'mat4x4<bool>'
  40875. };
  40876. const wgslMethods = {
  40877. dFdx: 'dpdx',
  40878. dFdy: '- dpdy',
  40879. mod_float: 'threejs_mod_float',
  40880. mod_vec2: 'threejs_mod_vec2',
  40881. mod_vec3: 'threejs_mod_vec3',
  40882. mod_vec4: 'threejs_mod_vec4',
  40883. equals_bool: 'threejs_equals_bool',
  40884. equals_bvec2: 'threejs_equals_bvec2',
  40885. equals_bvec3: 'threejs_equals_bvec3',
  40886. equals_bvec4: 'threejs_equals_bvec4',
  40887. lessThanEqual: 'threejs_lessThanEqual',
  40888. greaterThan: 'threejs_greaterThan',
  40889. inversesqrt: 'inverseSqrt',
  40890. bitcast: 'bitcast<f32>'
  40891. };
  40892. const wgslPolyfill = {
  40893. threejs_xor: new CodeNode( `
  40894. fn threejs_xor( a : bool, b : bool ) -> bool {
  40895. return ( a || b ) && !( a && b );
  40896. }
  40897. ` ),
  40898. lessThanEqual: new CodeNode( `
  40899. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  40900. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  40901. }
  40902. ` ),
  40903. greaterThan: new CodeNode( `
  40904. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  40905. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  40906. }
  40907. ` ),
  40908. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  40909. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  40910. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  40911. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  40912. equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  40913. 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 ); }' ),
  40914. 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 ); }' ),
  40915. 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 ); }' ),
  40916. repeatWrapping: new CodeNode( `
  40917. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  40918. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  40919. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  40920. }
  40921. ` ),
  40922. biquadraticTexture: new CodeNode( `
  40923. fn threejs_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  40924. let res = vec2f( textureDimensions( map, level ) );
  40925. let uvScaled = coord * res;
  40926. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  40927. // https://www.shadertoy.com/view/WtyXRy
  40928. let uv = uvWrapping - 0.5;
  40929. let iuv = floor( uv );
  40930. let f = fract( uv );
  40931. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  40932. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  40933. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  40934. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  40935. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  40936. }
  40937. ` )
  40938. };
  40939. class WGSLNodeBuilder extends NodeBuilder {
  40940. constructor( object, renderer ) {
  40941. super( object, renderer, new WGSLNodeParser() );
  40942. this.uniformGroups = {};
  40943. this.builtins = {};
  40944. }
  40945. needsColorSpaceToLinear( texture ) {
  40946. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  40947. }
  40948. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40949. if ( shaderStage === 'fragment' ) {
  40950. if ( depthSnippet ) {
  40951. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  40952. } else {
  40953. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  40954. }
  40955. } else if ( this.isFilteredTexture( texture ) ) {
  40956. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  40957. } else {
  40958. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  40959. }
  40960. }
  40961. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  40962. if ( shaderStage === 'fragment' ) {
  40963. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  40964. } else {
  40965. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  40966. }
  40967. }
  40968. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40969. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  40970. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  40971. } else if ( this.isFilteredTexture( texture ) ) {
  40972. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  40973. } else {
  40974. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  40975. }
  40976. }
  40977. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  40978. this._include( 'biquadraticTexture' );
  40979. return `threejs_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  40980. }
  40981. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  40982. this._include( 'repeatWrapping' );
  40983. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  40984. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  40985. }
  40986. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  40987. if ( depthSnippet ) {
  40988. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  40989. } else {
  40990. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  40991. }
  40992. }
  40993. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  40994. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  40995. }
  40996. isUnfilterable( texture ) {
  40997. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  40998. }
  40999. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41000. let snippet = null;
  41001. if ( texture.isVideoTexture === true ) {
  41002. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  41003. } else if ( this.isUnfilterable( texture ) ) {
  41004. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  41005. } else {
  41006. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  41007. }
  41008. return snippet;
  41009. }
  41010. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41011. if ( shaderStage === 'fragment' ) {
  41012. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  41013. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  41014. } else {
  41015. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  41016. }
  41017. }
  41018. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41019. if ( shaderStage === 'fragment' ) {
  41020. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  41021. } else {
  41022. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  41023. }
  41024. }
  41025. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41026. let snippet = null;
  41027. if ( texture.isVideoTexture === true ) {
  41028. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  41029. } else {
  41030. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  41031. }
  41032. return snippet;
  41033. }
  41034. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41035. if ( shaderStage === 'fragment' ) {
  41036. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  41037. } else {
  41038. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  41039. }
  41040. }
  41041. getPropertyName( node, shaderStage = this.shaderStage ) {
  41042. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  41043. if ( shaderStage === 'vertex' ) {
  41044. return `varyings.${ node.name }`;
  41045. }
  41046. } else if ( node.isNodeUniform === true ) {
  41047. const name = node.name;
  41048. const type = node.type;
  41049. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  41050. return name;
  41051. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  41052. return `NodeBuffer_${ node.id }.${name}`;
  41053. } else {
  41054. return node.groupNode.name + '.' + name;
  41055. }
  41056. }
  41057. return super.getPropertyName( node );
  41058. }
  41059. getOutputStructName() {
  41060. return 'output';
  41061. }
  41062. _getUniformGroupCount( shaderStage ) {
  41063. return Object.keys( this.uniforms[ shaderStage ] ).length;
  41064. }
  41065. getFunctionOperator( op ) {
  41066. const fnOp = wgslFnOpLib[ op ];
  41067. if ( fnOp !== undefined ) {
  41068. this._include( fnOp );
  41069. return fnOp;
  41070. }
  41071. return null;
  41072. }
  41073. getStorageAccess( node ) {
  41074. if ( node.isStorageTextureNode ) {
  41075. switch ( node.access ) {
  41076. case GPUStorageTextureAccess.ReadOnly:
  41077. return 'read';
  41078. case GPUStorageTextureAccess.WriteOnly:
  41079. return 'write';
  41080. default:
  41081. return 'read_write';
  41082. }
  41083. } else {
  41084. switch ( node.access ) {
  41085. case GPUBufferBindingType.Storage:
  41086. return 'read_write';
  41087. case GPUBufferBindingType.ReadOnlyStorage:
  41088. return 'read';
  41089. default:
  41090. return 'write';
  41091. }
  41092. }
  41093. }
  41094. getUniformFromNode( node, type, shaderStage, name = null ) {
  41095. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  41096. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  41097. if ( nodeData.uniformGPU === undefined ) {
  41098. let uniformGPU;
  41099. const group = node.groupNode;
  41100. const groupName = group.name;
  41101. const bindings = this.getBindGroupArray( groupName, shaderStage );
  41102. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  41103. let texture = null;
  41104. if ( type === 'texture' || type === 'storageTexture' ) {
  41105. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  41106. } else if ( type === 'cubeTexture' ) {
  41107. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  41108. } else if ( type === 'texture3D' ) {
  41109. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  41110. }
  41111. texture.store = node.isStorageTextureNode === true;
  41112. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41113. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  41114. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  41115. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41116. bindings.push( sampler, texture );
  41117. uniformGPU = [ sampler, texture ];
  41118. } else {
  41119. bindings.push( texture );
  41120. uniformGPU = [ texture ];
  41121. }
  41122. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  41123. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  41124. const buffer = new bufferClass( node, group );
  41125. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41126. bindings.push( buffer );
  41127. uniformGPU = buffer;
  41128. } else {
  41129. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  41130. let uniformsGroup = uniformsStage[ groupName ];
  41131. if ( uniformsGroup === undefined ) {
  41132. uniformsGroup = new NodeUniformsGroup( groupName, group );
  41133. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41134. uniformsStage[ groupName ] = uniformsGroup;
  41135. bindings.push( uniformsGroup );
  41136. }
  41137. uniformGPU = this.getNodeUniform( uniformNode, type );
  41138. uniformsGroup.addUniform( uniformGPU );
  41139. }
  41140. nodeData.uniformGPU = uniformGPU;
  41141. }
  41142. return uniformNode;
  41143. }
  41144. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  41145. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  41146. if ( map.has( name ) === false ) {
  41147. map.set( name, {
  41148. name,
  41149. property,
  41150. type
  41151. } );
  41152. }
  41153. return property;
  41154. }
  41155. getVertexIndex() {
  41156. if ( this.shaderStage === 'vertex' ) {
  41157. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  41158. }
  41159. return 'vertexIndex';
  41160. }
  41161. buildFunctionCode( shaderNode ) {
  41162. const layout = shaderNode.layout;
  41163. const flowData = this.flowShaderNode( shaderNode );
  41164. const parameters = [];
  41165. for ( const input of layout.inputs ) {
  41166. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  41167. }
  41168. //
  41169. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  41170. ${ flowData.vars }
  41171. ${ flowData.code }
  41172. return ${ flowData.result };
  41173. }`;
  41174. //
  41175. return code;
  41176. }
  41177. getInstanceIndex() {
  41178. if ( this.shaderStage === 'vertex' ) {
  41179. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  41180. }
  41181. return 'instanceIndex';
  41182. }
  41183. getDrawIndex() {
  41184. return null;
  41185. }
  41186. getFrontFacing() {
  41187. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  41188. }
  41189. getFragCoord() {
  41190. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xyz';
  41191. }
  41192. getFragDepth() {
  41193. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  41194. }
  41195. isFlipY() {
  41196. return false;
  41197. }
  41198. getBuiltins( shaderStage ) {
  41199. const snippets = [];
  41200. const builtins = this.builtins[ shaderStage ];
  41201. if ( builtins !== undefined ) {
  41202. for ( const { name, property, type } of builtins.values() ) {
  41203. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  41204. }
  41205. }
  41206. return snippets.join( ',\n\t' );
  41207. }
  41208. getAttributes( shaderStage ) {
  41209. const snippets = [];
  41210. if ( shaderStage === 'compute' ) {
  41211. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  41212. }
  41213. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41214. const builtins = this.getBuiltins( 'attribute' );
  41215. if ( builtins ) snippets.push( builtins );
  41216. const attributes = this.getAttributesArray();
  41217. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  41218. const attribute = attributes[ index ];
  41219. const name = attribute.name;
  41220. const type = this.getType( attribute.type );
  41221. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  41222. }
  41223. }
  41224. return snippets.join( ',\n\t' );
  41225. }
  41226. getStructMembers( struct ) {
  41227. const snippets = [];
  41228. const members = struct.getMemberTypes();
  41229. for ( let i = 0; i < members.length; i ++ ) {
  41230. const member = members[ i ];
  41231. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  41232. }
  41233. const builtins = this.getBuiltins( 'output' );
  41234. if ( builtins ) snippets.push( builtins );
  41235. return snippets.join( ',\n' );
  41236. }
  41237. getStructs( shaderStage ) {
  41238. const snippets = [];
  41239. const structs = this.structs[ shaderStage ];
  41240. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  41241. const struct = structs[ index ];
  41242. const name = struct.name;
  41243. let snippet = `\struct ${ name } {\n`;
  41244. snippet += this.getStructMembers( struct );
  41245. snippet += '\n}';
  41246. snippets.push( snippet );
  41247. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  41248. }
  41249. return snippets.join( '\n\n' );
  41250. }
  41251. getVar( type, name ) {
  41252. return `var ${ name } : ${ this.getType( type ) }`;
  41253. }
  41254. getVars( shaderStage ) {
  41255. const snippets = [];
  41256. const vars = this.vars[ shaderStage ];
  41257. if ( vars !== undefined ) {
  41258. for ( const variable of vars ) {
  41259. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  41260. }
  41261. }
  41262. return `\n${ snippets.join( '\n' ) }\n`;
  41263. }
  41264. getVaryings( shaderStage ) {
  41265. const snippets = [];
  41266. if ( shaderStage === 'vertex' ) {
  41267. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  41268. }
  41269. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  41270. const varyings = this.varyings;
  41271. const vars = this.vars[ shaderStage ];
  41272. for ( let index = 0; index < varyings.length; index ++ ) {
  41273. const varying = varyings[ index ];
  41274. if ( varying.needsInterpolation ) {
  41275. let attributesSnippet = `@location( ${index} )`;
  41276. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  41277. attributesSnippet += ' @interpolate( flat )';
  41278. }
  41279. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  41280. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  41281. vars.push( varying );
  41282. }
  41283. }
  41284. }
  41285. const builtins = this.getBuiltins( shaderStage );
  41286. if ( builtins ) snippets.push( builtins );
  41287. const code = snippets.join( ',\n\t' );
  41288. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  41289. }
  41290. getUniforms( shaderStage ) {
  41291. const uniforms = this.uniforms[ shaderStage ];
  41292. const bindingSnippets = [];
  41293. const bufferSnippets = [];
  41294. const structSnippets = [];
  41295. const uniformGroups = {};
  41296. for ( const uniform of uniforms ) {
  41297. const groundName = uniform.groupNode.name;
  41298. const uniformIndexes = this.bindingsIndexes[ groundName ];
  41299. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  41300. const texture = uniform.node.value;
  41301. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  41302. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  41303. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  41304. } else {
  41305. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  41306. }
  41307. }
  41308. let textureType;
  41309. let multisampled = '';
  41310. if ( texture.isMultisampleRenderTargetTexture === true ) {
  41311. multisampled = '_multisampled';
  41312. }
  41313. if ( texture.isCubeTexture === true ) {
  41314. textureType = 'texture_cube<f32>';
  41315. } else if ( texture.isDataArrayTexture === true ) {
  41316. textureType = 'texture_2d_array<f32>';
  41317. } else if ( texture.isDepthTexture === true ) {
  41318. textureType = `texture_depth${multisampled}_2d`;
  41319. } else if ( texture.isVideoTexture === true ) {
  41320. textureType = 'texture_external';
  41321. } else if ( texture.isData3DTexture === true ) {
  41322. textureType = 'texture_3d<f32>';
  41323. } else if ( uniform.node.isStorageTextureNode === true ) {
  41324. const format = getFormat( texture );
  41325. const access = this.getStorageAccess( uniform.node );
  41326. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  41327. } else {
  41328. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  41329. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  41330. }
  41331. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  41332. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  41333. const bufferNode = uniform.node;
  41334. const bufferType = this.getType( bufferNode.bufferType );
  41335. const bufferCount = bufferNode.bufferCount;
  41336. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  41337. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferType }${ bufferCountSnippet } >\n`;
  41338. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  41339. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  41340. } else {
  41341. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  41342. const groupName = uniform.groupNode.name;
  41343. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  41344. index: uniformIndexes.binding ++,
  41345. id: uniformIndexes.group,
  41346. snippets: []
  41347. } );
  41348. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  41349. }
  41350. }
  41351. for ( const name in uniformGroups ) {
  41352. const group = uniformGroups[ name ];
  41353. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  41354. }
  41355. let code = bindingSnippets.join( '\n' );
  41356. code += bufferSnippets.join( '\n' );
  41357. code += structSnippets.join( '\n' );
  41358. return code;
  41359. }
  41360. buildCode() {
  41361. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  41362. for ( const shaderStage in shadersData ) {
  41363. const stageData = shadersData[ shaderStage ];
  41364. stageData.uniforms = this.getUniforms( shaderStage );
  41365. stageData.attributes = this.getAttributes( shaderStage );
  41366. stageData.varyings = this.getVaryings( shaderStage );
  41367. stageData.structs = this.getStructs( shaderStage );
  41368. stageData.vars = this.getVars( shaderStage );
  41369. stageData.codes = this.getCodes( shaderStage );
  41370. //
  41371. let flow = '// code\n\n';
  41372. flow += this.flowCode[ shaderStage ];
  41373. const flowNodes = this.flowNodes[ shaderStage ];
  41374. const mainNode = flowNodes[ flowNodes.length - 1 ];
  41375. const outputNode = mainNode.outputNode;
  41376. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  41377. for ( const node of flowNodes ) {
  41378. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  41379. const slotName = node.name;
  41380. if ( slotName ) {
  41381. if ( flow.length > 0 ) flow += '\n';
  41382. flow += `\t// flow -> ${ slotName }\n\t`;
  41383. }
  41384. flow += `${ flowSlotData.code }\n\t`;
  41385. if ( node === mainNode && shaderStage !== 'compute' ) {
  41386. flow += '// result\n\n\t';
  41387. if ( shaderStage === 'vertex' ) {
  41388. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  41389. } else if ( shaderStage === 'fragment' ) {
  41390. if ( isOutputStruct ) {
  41391. stageData.returnType = outputNode.nodeType;
  41392. flow += `return ${ flowSlotData.result };`;
  41393. } else {
  41394. let structSnippet = '\t@location(0) color: vec4<f32>';
  41395. const builtins = this.getBuiltins( 'output' );
  41396. if ( builtins ) structSnippet += ',\n\t' + builtins;
  41397. stageData.returnType = 'OutputStruct';
  41398. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  41399. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  41400. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  41401. }
  41402. }
  41403. }
  41404. }
  41405. stageData.flow = flow;
  41406. }
  41407. if ( this.material !== null ) {
  41408. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  41409. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  41410. } else {
  41411. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  41412. }
  41413. }
  41414. getMethod( method, output = null ) {
  41415. let wgslMethod;
  41416. if ( output !== null ) {
  41417. wgslMethod = this._getWGSLMethod( method + '_' + output );
  41418. }
  41419. if ( wgslMethod === undefined ) {
  41420. wgslMethod = this._getWGSLMethod( method );
  41421. }
  41422. return wgslMethod || method;
  41423. }
  41424. getType( type ) {
  41425. return wgslTypeLib[ type ] || type;
  41426. }
  41427. isAvailable( name ) {
  41428. let result = supports[ name ];
  41429. if ( result === undefined ) {
  41430. if ( name === 'float32Filterable' ) {
  41431. result = this.renderer.hasFeature( 'float32-filterable' );
  41432. }
  41433. supports[ name ] = result;
  41434. }
  41435. return result;
  41436. }
  41437. _getWGSLMethod( method ) {
  41438. if ( wgslPolyfill[ method ] !== undefined ) {
  41439. this._include( method );
  41440. }
  41441. return wgslMethods[ method ];
  41442. }
  41443. _include( name ) {
  41444. const codeNode = wgslPolyfill[ name ];
  41445. codeNode.build( this );
  41446. if ( this.currentFunctionNode !== null ) {
  41447. this.currentFunctionNode.includes.push( codeNode );
  41448. }
  41449. return codeNode;
  41450. }
  41451. _getWGSLVertexCode( shaderData ) {
  41452. return `${ this.getSignature() }
  41453. // uniforms
  41454. ${shaderData.uniforms}
  41455. // varyings
  41456. ${shaderData.varyings}
  41457. var<private> varyings : VaryingsStruct;
  41458. // codes
  41459. ${shaderData.codes}
  41460. @vertex
  41461. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  41462. // vars
  41463. ${shaderData.vars}
  41464. // flow
  41465. ${shaderData.flow}
  41466. return varyings;
  41467. }
  41468. `;
  41469. }
  41470. _getWGSLFragmentCode( shaderData ) {
  41471. return `${ this.getSignature() }
  41472. // uniforms
  41473. ${shaderData.uniforms}
  41474. // structs
  41475. ${shaderData.structs}
  41476. // codes
  41477. ${shaderData.codes}
  41478. @fragment
  41479. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  41480. // vars
  41481. ${shaderData.vars}
  41482. // flow
  41483. ${shaderData.flow}
  41484. }
  41485. `;
  41486. }
  41487. _getWGSLComputeCode( shaderData, workgroupSize ) {
  41488. return `${ this.getSignature() }
  41489. // system
  41490. var<private> instanceIndex : u32;
  41491. // uniforms
  41492. ${shaderData.uniforms}
  41493. // codes
  41494. ${shaderData.codes}
  41495. @compute @workgroup_size( ${workgroupSize} )
  41496. fn main( ${shaderData.attributes} ) {
  41497. // system
  41498. instanceIndex = id.x;
  41499. // vars
  41500. ${shaderData.vars}
  41501. // flow
  41502. ${shaderData.flow}
  41503. }
  41504. `;
  41505. }
  41506. _getWGSLStruct( name, vars ) {
  41507. return `
  41508. struct ${name} {
  41509. ${vars}
  41510. };`;
  41511. }
  41512. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  41513. const structName = name + 'Struct';
  41514. const structSnippet = this._getWGSLStruct( structName, vars );
  41515. return `${structSnippet}
  41516. @binding( ${binding} ) @group( ${group} )
  41517. var<${access}> ${name} : ${structName};`;
  41518. }
  41519. }
  41520. class WebGPUUtils {
  41521. constructor( backend ) {
  41522. this.backend = backend;
  41523. }
  41524. getCurrentDepthStencilFormat( renderContext ) {
  41525. let format;
  41526. if ( renderContext.depthTexture !== null ) {
  41527. format = this.getTextureFormatGPU( renderContext.depthTexture );
  41528. } else if ( renderContext.depth && renderContext.stencil ) {
  41529. format = GPUTextureFormat.Depth24PlusStencil8;
  41530. } else if ( renderContext.depth ) {
  41531. format = GPUTextureFormat.Depth24Plus;
  41532. }
  41533. return format;
  41534. }
  41535. getTextureFormatGPU( texture ) {
  41536. return this.backend.get( texture ).texture.format;
  41537. }
  41538. getCurrentColorFormat( renderContext ) {
  41539. let format;
  41540. if ( renderContext.textures !== null ) {
  41541. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  41542. } else {
  41543. format = GPUTextureFormat.BGRA8Unorm; // default context format
  41544. }
  41545. return format;
  41546. }
  41547. getCurrentColorSpace( renderContext ) {
  41548. if ( renderContext.textures !== null ) {
  41549. return renderContext.textures[ 0 ].colorSpace;
  41550. }
  41551. return this.backend.renderer.outputColorSpace;
  41552. }
  41553. getPrimitiveTopology( object, material ) {
  41554. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  41555. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  41556. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  41557. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  41558. }
  41559. getSampleCount( sampleCount ) {
  41560. let count = 1;
  41561. if ( sampleCount > 1 ) {
  41562. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  41563. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  41564. if ( count === 2 ) {
  41565. count = 4;
  41566. }
  41567. }
  41568. return count;
  41569. }
  41570. getSampleCountRenderContext( renderContext ) {
  41571. if ( renderContext.textures !== null ) {
  41572. return this.getSampleCount( renderContext.sampleCount );
  41573. }
  41574. return this.getSampleCount( this.backend.renderer.samples );
  41575. }
  41576. }
  41577. const typedArraysToVertexFormatPrefix = new Map( [
  41578. [ Int8Array, [ 'sint8', 'snorm8' ]],
  41579. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  41580. [ Int16Array, [ 'sint16', 'snorm16' ]],
  41581. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  41582. [ Int32Array, [ 'sint32', 'snorm32' ]],
  41583. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  41584. [ Float32Array, [ 'float32', ]],
  41585. ] );
  41586. const typedAttributeToVertexFormatPrefix = new Map( [
  41587. [ Float16BufferAttribute, [ 'float16', ]],
  41588. ] );
  41589. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  41590. [ Int32Array, 'sint32' ],
  41591. [ Int16Array, 'sint32' ], // patch for INT16
  41592. [ Uint32Array, 'uint32' ],
  41593. [ Uint16Array, 'uint32' ], // patch for UINT16
  41594. [ Float32Array, 'float32' ]
  41595. ] );
  41596. class WebGPUAttributeUtils {
  41597. constructor( backend ) {
  41598. this.backend = backend;
  41599. }
  41600. createAttribute( attribute, usage ) {
  41601. const bufferAttribute = this._getBufferAttribute( attribute );
  41602. const backend = this.backend;
  41603. const bufferData = backend.get( bufferAttribute );
  41604. let buffer = bufferData.buffer;
  41605. if ( buffer === undefined ) {
  41606. const device = backend.device;
  41607. let array = bufferAttribute.array;
  41608. // patch for INT16 and UINT16
  41609. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  41610. const tempArray = new Uint32Array( array.length );
  41611. for ( let i = 0; i < array.length; i ++ ) {
  41612. tempArray[ i ] = array[ i ];
  41613. }
  41614. array = tempArray;
  41615. }
  41616. bufferAttribute.array = array;
  41617. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  41618. array = new array.constructor( bufferAttribute.count * 4 );
  41619. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  41620. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  41621. }
  41622. // Update BufferAttribute
  41623. bufferAttribute.itemSize = 4;
  41624. bufferAttribute.array = array;
  41625. }
  41626. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  41627. buffer = device.createBuffer( {
  41628. label: bufferAttribute.name,
  41629. size: size,
  41630. usage: usage,
  41631. mappedAtCreation: true
  41632. } );
  41633. new array.constructor( buffer.getMappedRange() ).set( array );
  41634. buffer.unmap();
  41635. bufferData.buffer = buffer;
  41636. }
  41637. }
  41638. updateAttribute( attribute ) {
  41639. const bufferAttribute = this._getBufferAttribute( attribute );
  41640. const backend = this.backend;
  41641. const device = backend.device;
  41642. const buffer = backend.get( bufferAttribute ).buffer;
  41643. const array = bufferAttribute.array;
  41644. const updateRanges = bufferAttribute.updateRanges;
  41645. if ( updateRanges.length === 0 ) {
  41646. // Not using update ranges
  41647. device.queue.writeBuffer(
  41648. buffer,
  41649. 0,
  41650. array,
  41651. 0
  41652. );
  41653. } else {
  41654. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41655. const range = updateRanges[ i ];
  41656. device.queue.writeBuffer(
  41657. buffer,
  41658. 0,
  41659. array,
  41660. range.start * array.BYTES_PER_ELEMENT,
  41661. range.count * array.BYTES_PER_ELEMENT
  41662. );
  41663. }
  41664. bufferAttribute.clearUpdateRanges();
  41665. }
  41666. }
  41667. createShaderVertexBuffers( renderObject ) {
  41668. const attributes = renderObject.getAttributes();
  41669. const vertexBuffers = new Map();
  41670. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  41671. const geometryAttribute = attributes[ slot ];
  41672. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  41673. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  41674. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  41675. if ( vertexBufferLayout === undefined ) {
  41676. let arrayStride, stepMode;
  41677. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  41678. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  41679. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41680. } else {
  41681. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  41682. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41683. }
  41684. // patch for INT16 and UINT16
  41685. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  41686. arrayStride = 4;
  41687. }
  41688. vertexBufferLayout = {
  41689. arrayStride,
  41690. attributes: [],
  41691. stepMode
  41692. };
  41693. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  41694. }
  41695. const format = this._getVertexFormat( geometryAttribute );
  41696. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  41697. vertexBufferLayout.attributes.push( {
  41698. shaderLocation: slot,
  41699. offset,
  41700. format
  41701. } );
  41702. }
  41703. return Array.from( vertexBuffers.values() );
  41704. }
  41705. destroyAttribute( attribute ) {
  41706. const backend = this.backend;
  41707. const data = backend.get( this._getBufferAttribute( attribute ) );
  41708. data.buffer.destroy();
  41709. backend.delete( attribute );
  41710. }
  41711. async getArrayBufferAsync( attribute ) {
  41712. const backend = this.backend;
  41713. const device = backend.device;
  41714. const data = backend.get( this._getBufferAttribute( attribute ) );
  41715. const bufferGPU = data.buffer;
  41716. const size = bufferGPU.size;
  41717. let readBufferGPU = data.readBuffer;
  41718. let needsUnmap = true;
  41719. if ( readBufferGPU === undefined ) {
  41720. readBufferGPU = device.createBuffer( {
  41721. label: attribute.name,
  41722. size,
  41723. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41724. } );
  41725. needsUnmap = false;
  41726. data.readBuffer = readBufferGPU;
  41727. }
  41728. const cmdEncoder = device.createCommandEncoder( {} );
  41729. cmdEncoder.copyBufferToBuffer(
  41730. bufferGPU,
  41731. 0,
  41732. readBufferGPU,
  41733. 0,
  41734. size
  41735. );
  41736. if ( needsUnmap ) readBufferGPU.unmap();
  41737. const gpuCommands = cmdEncoder.finish();
  41738. device.queue.submit( [ gpuCommands ] );
  41739. await readBufferGPU.mapAsync( GPUMapMode.READ );
  41740. const arrayBuffer = readBufferGPU.getMappedRange();
  41741. return arrayBuffer;
  41742. }
  41743. _getVertexFormat( geometryAttribute ) {
  41744. const { itemSize, normalized } = geometryAttribute;
  41745. const ArrayType = geometryAttribute.array.constructor;
  41746. const AttributeType = geometryAttribute.constructor;
  41747. let format;
  41748. if ( itemSize == 1 ) {
  41749. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  41750. } else {
  41751. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  41752. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  41753. if ( prefix ) {
  41754. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  41755. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  41756. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  41757. if ( paddedItemSize % 1 ) {
  41758. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  41759. }
  41760. format = `${prefix}x${paddedItemSize}`;
  41761. }
  41762. }
  41763. if ( ! format ) {
  41764. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  41765. }
  41766. return format;
  41767. }
  41768. _getBufferAttribute( attribute ) {
  41769. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  41770. return attribute;
  41771. }
  41772. }
  41773. class WebGPUBindingUtils {
  41774. constructor( backend ) {
  41775. this.backend = backend;
  41776. }
  41777. createBindingsLayout( bindGroup ) {
  41778. const backend = this.backend;
  41779. const device = backend.device;
  41780. const entries = [];
  41781. let index = 0;
  41782. for ( const binding of bindGroup.bindings ) {
  41783. const bindingGPU = {
  41784. binding: index ++,
  41785. visibility: binding.visibility
  41786. };
  41787. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  41788. const buffer = {}; // GPUBufferBindingLayout
  41789. if ( binding.isStorageBuffer ) {
  41790. buffer.type = binding.access;
  41791. }
  41792. bindingGPU.buffer = buffer;
  41793. } else if ( binding.isSampler ) {
  41794. const sampler = {}; // GPUSamplerBindingLayout
  41795. if ( binding.texture.isDepthTexture ) {
  41796. if ( binding.texture.compareFunction !== null ) {
  41797. sampler.type = 'comparison';
  41798. }
  41799. }
  41800. bindingGPU.sampler = sampler;
  41801. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  41802. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  41803. } else if ( binding.isSampledTexture && binding.store ) {
  41804. const format = this.backend.get( binding.texture ).texture.format;
  41805. const access = binding.access;
  41806. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  41807. } else if ( binding.isSampledTexture ) {
  41808. const texture = {}; // GPUTextureBindingLayout
  41809. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  41810. texture.multisampled = true;
  41811. }
  41812. if ( binding.texture.isDepthTexture ) {
  41813. texture.sampleType = GPUTextureSampleType.Depth;
  41814. } else if ( binding.texture.isDataTexture ) {
  41815. const type = binding.texture.type;
  41816. if ( type === IntType ) {
  41817. texture.sampleType = GPUTextureSampleType.SInt;
  41818. } else if ( type === UnsignedIntType ) {
  41819. texture.sampleType = GPUTextureSampleType.UInt;
  41820. } else if ( type === FloatType ) {
  41821. // @TODO: Add support for this soon: backend.hasFeature( 'float32-filterable' )
  41822. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  41823. }
  41824. }
  41825. if ( binding.isSampledCubeTexture ) {
  41826. texture.viewDimension = GPUTextureViewDimension.Cube;
  41827. } else if ( binding.texture.isDataArrayTexture ) {
  41828. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  41829. } else if ( binding.isSampledTexture3D ) {
  41830. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  41831. }
  41832. bindingGPU.texture = texture;
  41833. } else {
  41834. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  41835. }
  41836. entries.push( bindingGPU );
  41837. }
  41838. return device.createBindGroupLayout( { entries } );
  41839. }
  41840. createBindings( bindGroup ) {
  41841. const backend = this.backend;
  41842. const bindingsData = backend.get( bindGroup );
  41843. // setup (static) binding layout and (dynamic) binding group
  41844. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  41845. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  41846. bindingsData.layout = bindLayoutGPU;
  41847. bindingsData.group = bindGroupGPU;
  41848. }
  41849. updateBinding( binding ) {
  41850. const backend = this.backend;
  41851. const device = backend.device;
  41852. const buffer = binding.buffer;
  41853. const bufferGPU = backend.get( binding ).buffer;
  41854. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  41855. }
  41856. createBindGroup( bindGroup, layoutGPU ) {
  41857. const backend = this.backend;
  41858. const device = backend.device;
  41859. let bindingPoint = 0;
  41860. const entriesGPU = [];
  41861. for ( const binding of bindGroup.bindings ) {
  41862. if ( binding.isUniformBuffer ) {
  41863. const bindingData = backend.get( binding );
  41864. if ( bindingData.buffer === undefined ) {
  41865. const byteLength = binding.byteLength;
  41866. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  41867. const bufferGPU = device.createBuffer( {
  41868. label: 'bindingBuffer_' + binding.name,
  41869. size: byteLength,
  41870. usage: usage
  41871. } );
  41872. bindingData.buffer = bufferGPU;
  41873. }
  41874. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  41875. } else if ( binding.isStorageBuffer ) {
  41876. const bindingData = backend.get( binding );
  41877. if ( bindingData.buffer === undefined ) {
  41878. const attribute = binding.attribute;
  41879. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  41880. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  41881. bindingData.buffer = backend.get( attribute ).buffer;
  41882. }
  41883. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  41884. } else if ( binding.isSampler ) {
  41885. const textureGPU = backend.get( binding.texture );
  41886. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  41887. } else if ( binding.isSampledTexture ) {
  41888. const textureData = backend.get( binding.texture );
  41889. let dimensionViewGPU;
  41890. if ( binding.isSampledCubeTexture ) {
  41891. dimensionViewGPU = GPUTextureViewDimension.Cube;
  41892. } else if ( binding.isSampledTexture3D ) {
  41893. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  41894. } else if ( binding.texture.isDataArrayTexture ) {
  41895. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  41896. } else {
  41897. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  41898. }
  41899. let resourceGPU;
  41900. if ( textureData.externalTexture !== undefined ) {
  41901. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  41902. } else {
  41903. const aspectGPU = GPUTextureAspect.All;
  41904. resourceGPU = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount: binding.store ? 1 : textureData.mipLevelCount } );
  41905. }
  41906. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  41907. }
  41908. bindingPoint ++;
  41909. }
  41910. return device.createBindGroup( {
  41911. label: 'bindGroup_' + bindGroup.name,
  41912. layout: layoutGPU,
  41913. entries: entriesGPU
  41914. } );
  41915. }
  41916. }
  41917. class WebGPUPipelineUtils {
  41918. constructor( backend ) {
  41919. this.backend = backend;
  41920. }
  41921. _getSampleCount( renderObjectContext ) {
  41922. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  41923. }
  41924. createRenderPipeline( renderObject, promises ) {
  41925. const { object, material, geometry, pipeline } = renderObject;
  41926. const { vertexProgram, fragmentProgram } = pipeline;
  41927. const backend = this.backend;
  41928. const device = backend.device;
  41929. const utils = backend.utils;
  41930. const pipelineData = backend.get( pipeline );
  41931. // bind group layouts
  41932. const bindGroupLayouts = [];
  41933. for ( const bindGroup of renderObject.getBindings() ) {
  41934. const bindingsData = backend.get( bindGroup );
  41935. bindGroupLayouts.push( bindingsData.layout );
  41936. }
  41937. // vertex buffers
  41938. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  41939. // blending
  41940. let blending;
  41941. if ( material.transparent === true && material.blending !== NoBlending ) {
  41942. blending = this._getBlending( material );
  41943. }
  41944. // stencil
  41945. let stencilFront = {};
  41946. if ( material.stencilWrite === true ) {
  41947. stencilFront = {
  41948. compare: this._getStencilCompare( material ),
  41949. failOp: this._getStencilOperation( material.stencilFail ),
  41950. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  41951. passOp: this._getStencilOperation( material.stencilZPass )
  41952. };
  41953. }
  41954. const colorWriteMask = this._getColorWriteMask( material );
  41955. const targets = [];
  41956. if ( renderObject.context.textures !== null ) {
  41957. const textures = renderObject.context.textures;
  41958. for ( let i = 0; i < textures.length; i ++ ) {
  41959. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  41960. targets.push( {
  41961. format: colorFormat,
  41962. blend: blending,
  41963. writeMask: colorWriteMask
  41964. } );
  41965. }
  41966. } else {
  41967. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  41968. targets.push( {
  41969. format: colorFormat,
  41970. blend: blending,
  41971. writeMask: colorWriteMask
  41972. } );
  41973. }
  41974. const vertexModule = backend.get( vertexProgram ).module;
  41975. const fragmentModule = backend.get( fragmentProgram ).module;
  41976. const primitiveState = this._getPrimitiveState( object, geometry, material );
  41977. const depthCompare = this._getDepthCompare( material );
  41978. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  41979. const sampleCount = this._getSampleCount( renderObject.context );
  41980. const pipelineDescriptor = {
  41981. label: 'renderPipeline',
  41982. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  41983. fragment: Object.assign( {}, fragmentModule, { targets } ),
  41984. primitive: primitiveState,
  41985. depthStencil: {
  41986. format: depthStencilFormat,
  41987. depthWriteEnabled: material.depthWrite,
  41988. depthCompare: depthCompare,
  41989. stencilFront: stencilFront,
  41990. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  41991. stencilReadMask: material.stencilFuncMask,
  41992. stencilWriteMask: material.stencilWriteMask
  41993. },
  41994. multisample: {
  41995. count: sampleCount,
  41996. alphaToCoverageEnabled: material.alphaToCoverage
  41997. },
  41998. layout: device.createPipelineLayout( {
  41999. bindGroupLayouts
  42000. } )
  42001. };
  42002. if ( promises === null ) {
  42003. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  42004. } else {
  42005. const p = new Promise( ( resolve /*, reject*/ ) => {
  42006. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  42007. pipelineData.pipeline = pipeline;
  42008. resolve();
  42009. } );
  42010. } );
  42011. promises.push( p );
  42012. }
  42013. }
  42014. createBundleEncoder( renderContext, renderObject ) {
  42015. const backend = this.backend;
  42016. const { utils, device } = backend;
  42017. const renderContextData = backend.get( renderContext );
  42018. const renderObjectData = backend.get( renderObject );
  42019. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  42020. const colorFormat = utils.getCurrentColorFormat( renderContext );
  42021. const sampleCount = this._getSampleCount( renderObject.context );
  42022. const descriptor = {
  42023. label: 'renderBundleEncoder',
  42024. colorFormats: [ colorFormat ],
  42025. depthStencilFormat,
  42026. sampleCount
  42027. };
  42028. const bundleEncoder = device.createRenderBundleEncoder( descriptor );
  42029. renderObjectData.bundleEncoder = bundleEncoder;
  42030. renderContextData.currentSets = { attributes: {} };
  42031. renderContextData._renderBundleViewport = renderContext.width + '_' + renderContext.height;
  42032. return bundleEncoder;
  42033. }
  42034. createComputePipeline( pipeline, bindings ) {
  42035. const backend = this.backend;
  42036. const device = backend.device;
  42037. const computeProgram = backend.get( pipeline.computeProgram ).module;
  42038. const pipelineGPU = backend.get( pipeline );
  42039. // bind group layouts
  42040. const bindGroupLayouts = [];
  42041. for ( const bindingsGroup of bindings ) {
  42042. const bindingsData = backend.get( bindingsGroup );
  42043. bindGroupLayouts.push( bindingsData.layout );
  42044. }
  42045. pipelineGPU.pipeline = device.createComputePipeline( {
  42046. compute: computeProgram,
  42047. layout: device.createPipelineLayout( {
  42048. bindGroupLayouts
  42049. } )
  42050. } );
  42051. }
  42052. _getBlending( material ) {
  42053. let color, alpha;
  42054. const blending = material.blending;
  42055. const blendSrc = material.blendSrc;
  42056. const blendDst = material.blendDst;
  42057. const blendEquation = material.blendEquation;
  42058. if ( blending === CustomBlending ) {
  42059. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  42060. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  42061. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  42062. color = {
  42063. srcFactor: this._getBlendFactor( blendSrc ),
  42064. dstFactor: this._getBlendFactor( blendDst ),
  42065. operation: this._getBlendOperation( blendEquation )
  42066. };
  42067. alpha = {
  42068. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  42069. dstFactor: this._getBlendFactor( blendDstAlpha ),
  42070. operation: this._getBlendOperation( blendEquationAlpha )
  42071. };
  42072. } else {
  42073. const premultipliedAlpha = material.premultipliedAlpha;
  42074. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  42075. color = {
  42076. srcFactor: srcRGB,
  42077. dstFactor: dstRGB,
  42078. operation: GPUBlendOperation.Add
  42079. };
  42080. alpha = {
  42081. srcFactor: srcAlpha,
  42082. dstFactor: dstAlpha,
  42083. operation: GPUBlendOperation.Add
  42084. };
  42085. };
  42086. if ( premultipliedAlpha ) {
  42087. switch ( blending ) {
  42088. case NormalBlending:
  42089. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  42090. break;
  42091. case AdditiveBlending:
  42092. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  42093. break;
  42094. case SubtractiveBlending:
  42095. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42096. break;
  42097. case MultiplyBlending:
  42098. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  42099. break;
  42100. }
  42101. } else {
  42102. switch ( blending ) {
  42103. case NormalBlending:
  42104. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  42105. break;
  42106. case AdditiveBlending:
  42107. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  42108. break;
  42109. case SubtractiveBlending:
  42110. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42111. break;
  42112. case MultiplyBlending:
  42113. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  42114. break;
  42115. }
  42116. }
  42117. }
  42118. if ( color !== undefined && alpha !== undefined ) {
  42119. return { color, alpha };
  42120. } else {
  42121. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  42122. }
  42123. }
  42124. _getBlendFactor( blend ) {
  42125. let blendFactor;
  42126. switch ( blend ) {
  42127. case ZeroFactor:
  42128. blendFactor = GPUBlendFactor.Zero;
  42129. break;
  42130. case OneFactor:
  42131. blendFactor = GPUBlendFactor.One;
  42132. break;
  42133. case SrcColorFactor:
  42134. blendFactor = GPUBlendFactor.Src;
  42135. break;
  42136. case OneMinusSrcColorFactor:
  42137. blendFactor = GPUBlendFactor.OneMinusSrc;
  42138. break;
  42139. case SrcAlphaFactor:
  42140. blendFactor = GPUBlendFactor.SrcAlpha;
  42141. break;
  42142. case OneMinusSrcAlphaFactor:
  42143. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  42144. break;
  42145. case DstColorFactor:
  42146. blendFactor = GPUBlendFactor.Dst;
  42147. break;
  42148. case OneMinusDstColorFactor:
  42149. blendFactor = GPUBlendFactor.OneMinusDstColor;
  42150. break;
  42151. case DstAlphaFactor:
  42152. blendFactor = GPUBlendFactor.DstAlpha;
  42153. break;
  42154. case OneMinusDstAlphaFactor:
  42155. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  42156. break;
  42157. case SrcAlphaSaturateFactor:
  42158. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  42159. break;
  42160. case BlendColorFactor:
  42161. blendFactor = GPUBlendFactor.Constant;
  42162. break;
  42163. case OneMinusBlendColorFactor:
  42164. blendFactor = GPUBlendFactor.OneMinusConstant;
  42165. break;
  42166. default:
  42167. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  42168. }
  42169. return blendFactor;
  42170. }
  42171. _getStencilCompare( material ) {
  42172. let stencilCompare;
  42173. const stencilFunc = material.stencilFunc;
  42174. switch ( stencilFunc ) {
  42175. case NeverStencilFunc:
  42176. stencilCompare = GPUCompareFunction.Never;
  42177. break;
  42178. case AlwaysStencilFunc:
  42179. stencilCompare = GPUCompareFunction.Always;
  42180. break;
  42181. case LessStencilFunc:
  42182. stencilCompare = GPUCompareFunction.Less;
  42183. break;
  42184. case LessEqualStencilFunc:
  42185. stencilCompare = GPUCompareFunction.LessEqual;
  42186. break;
  42187. case EqualStencilFunc:
  42188. stencilCompare = GPUCompareFunction.Equal;
  42189. break;
  42190. case GreaterEqualStencilFunc:
  42191. stencilCompare = GPUCompareFunction.GreaterEqual;
  42192. break;
  42193. case GreaterStencilFunc:
  42194. stencilCompare = GPUCompareFunction.Greater;
  42195. break;
  42196. case NotEqualStencilFunc:
  42197. stencilCompare = GPUCompareFunction.NotEqual;
  42198. break;
  42199. default:
  42200. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  42201. }
  42202. return stencilCompare;
  42203. }
  42204. _getStencilOperation( op ) {
  42205. let stencilOperation;
  42206. switch ( op ) {
  42207. case KeepStencilOp:
  42208. stencilOperation = GPUStencilOperation.Keep;
  42209. break;
  42210. case ZeroStencilOp:
  42211. stencilOperation = GPUStencilOperation.Zero;
  42212. break;
  42213. case ReplaceStencilOp:
  42214. stencilOperation = GPUStencilOperation.Replace;
  42215. break;
  42216. case InvertStencilOp:
  42217. stencilOperation = GPUStencilOperation.Invert;
  42218. break;
  42219. case IncrementStencilOp:
  42220. stencilOperation = GPUStencilOperation.IncrementClamp;
  42221. break;
  42222. case DecrementStencilOp:
  42223. stencilOperation = GPUStencilOperation.DecrementClamp;
  42224. break;
  42225. case IncrementWrapStencilOp:
  42226. stencilOperation = GPUStencilOperation.IncrementWrap;
  42227. break;
  42228. case DecrementWrapStencilOp:
  42229. stencilOperation = GPUStencilOperation.DecrementWrap;
  42230. break;
  42231. default:
  42232. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  42233. }
  42234. return stencilOperation;
  42235. }
  42236. _getBlendOperation( blendEquation ) {
  42237. let blendOperation;
  42238. switch ( blendEquation ) {
  42239. case AddEquation:
  42240. blendOperation = GPUBlendOperation.Add;
  42241. break;
  42242. case SubtractEquation:
  42243. blendOperation = GPUBlendOperation.Subtract;
  42244. break;
  42245. case ReverseSubtractEquation:
  42246. blendOperation = GPUBlendOperation.ReverseSubtract;
  42247. break;
  42248. case MinEquation:
  42249. blendOperation = GPUBlendOperation.Min;
  42250. break;
  42251. case MaxEquation:
  42252. blendOperation = GPUBlendOperation.Max;
  42253. break;
  42254. default:
  42255. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  42256. }
  42257. return blendOperation;
  42258. }
  42259. _getPrimitiveState( object, geometry, material ) {
  42260. const descriptor = {};
  42261. const utils = this.backend.utils;
  42262. descriptor.topology = utils.getPrimitiveTopology( object, material );
  42263. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  42264. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42265. }
  42266. switch ( material.side ) {
  42267. case FrontSide:
  42268. descriptor.frontFace = GPUFrontFace.CCW;
  42269. descriptor.cullMode = GPUCullMode.Back;
  42270. break;
  42271. case BackSide:
  42272. descriptor.frontFace = GPUFrontFace.CCW;
  42273. descriptor.cullMode = GPUCullMode.Front;
  42274. break;
  42275. case DoubleSide:
  42276. descriptor.frontFace = GPUFrontFace.CCW;
  42277. descriptor.cullMode = GPUCullMode.None;
  42278. break;
  42279. default:
  42280. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  42281. break;
  42282. }
  42283. return descriptor;
  42284. }
  42285. _getColorWriteMask( material ) {
  42286. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  42287. }
  42288. _getDepthCompare( material ) {
  42289. let depthCompare;
  42290. if ( material.depthTest === false ) {
  42291. depthCompare = GPUCompareFunction.Always;
  42292. } else {
  42293. const depthFunc = material.depthFunc;
  42294. switch ( depthFunc ) {
  42295. case NeverDepth:
  42296. depthCompare = GPUCompareFunction.Never;
  42297. break;
  42298. case AlwaysDepth:
  42299. depthCompare = GPUCompareFunction.Always;
  42300. break;
  42301. case LessDepth:
  42302. depthCompare = GPUCompareFunction.Less;
  42303. break;
  42304. case LessEqualDepth:
  42305. depthCompare = GPUCompareFunction.LessEqual;
  42306. break;
  42307. case EqualDepth:
  42308. depthCompare = GPUCompareFunction.Equal;
  42309. break;
  42310. case GreaterEqualDepth:
  42311. depthCompare = GPUCompareFunction.GreaterEqual;
  42312. break;
  42313. case GreaterDepth:
  42314. depthCompare = GPUCompareFunction.Greater;
  42315. break;
  42316. case NotEqualDepth:
  42317. depthCompare = GPUCompareFunction.NotEqual;
  42318. break;
  42319. default:
  42320. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  42321. }
  42322. }
  42323. return depthCompare;
  42324. }
  42325. }
  42326. /*// debugger tools
  42327. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  42328. //*/
  42329. //
  42330. class WebGPUBackend extends Backend {
  42331. constructor( parameters = {} ) {
  42332. super( parameters );
  42333. this.isWebGPUBackend = true;
  42334. // some parameters require default values other than "undefined"
  42335. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  42336. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  42337. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42338. this.device = null;
  42339. this.context = null;
  42340. this.colorBuffer = null;
  42341. this.defaultRenderPassdescriptor = null;
  42342. this.utils = new WebGPUUtils( this );
  42343. this.attributeUtils = new WebGPUAttributeUtils( this );
  42344. this.bindingUtils = new WebGPUBindingUtils( this );
  42345. this.pipelineUtils = new WebGPUPipelineUtils( this );
  42346. this.textureUtils = new WebGPUTextureUtils( this );
  42347. this.occludedResolveCache = new Map();
  42348. }
  42349. async init( renderer ) {
  42350. await super.init( renderer );
  42351. //
  42352. const parameters = this.parameters;
  42353. // create the device if it is not passed with parameters
  42354. let device;
  42355. if ( parameters.device === undefined ) {
  42356. const adapterOptions = {
  42357. powerPreference: parameters.powerPreference
  42358. };
  42359. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  42360. if ( adapter === null ) {
  42361. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  42362. }
  42363. // feature support
  42364. const features = Object.values( GPUFeatureName );
  42365. const supportedFeatures = [];
  42366. for ( const name of features ) {
  42367. if ( adapter.features.has( name ) ) {
  42368. supportedFeatures.push( name );
  42369. }
  42370. }
  42371. const deviceDescriptor = {
  42372. requiredFeatures: supportedFeatures,
  42373. requiredLimits: parameters.requiredLimits
  42374. };
  42375. device = await adapter.requestDevice( deviceDescriptor );
  42376. } else {
  42377. device = parameters.device;
  42378. }
  42379. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  42380. this.device = device;
  42381. this.context = context;
  42382. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  42383. this.context.configure( {
  42384. device: this.device,
  42385. format: GPUTextureFormat.BGRA8Unorm,
  42386. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  42387. alphaMode: alphaMode
  42388. } );
  42389. this.updateSize();
  42390. }
  42391. get coordinateSystem() {
  42392. return WebGPUCoordinateSystem;
  42393. }
  42394. async getArrayBufferAsync( attribute ) {
  42395. return await this.attributeUtils.getArrayBufferAsync( attribute );
  42396. }
  42397. getContext() {
  42398. return this.context;
  42399. }
  42400. _getDefaultRenderPassDescriptor() {
  42401. let descriptor = this.defaultRenderPassdescriptor;
  42402. if ( descriptor === null ) {
  42403. const renderer = this.renderer;
  42404. descriptor = {
  42405. colorAttachments: [ {
  42406. view: null
  42407. } ],
  42408. depthStencilAttachment: {
  42409. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  42410. }
  42411. };
  42412. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42413. if ( this.renderer.samples > 0 ) {
  42414. colorAttachment.view = this.colorBuffer.createView();
  42415. } else {
  42416. colorAttachment.resolveTarget = undefined;
  42417. }
  42418. this.defaultRenderPassdescriptor = descriptor;
  42419. }
  42420. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42421. if ( this.renderer.samples > 0 ) {
  42422. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  42423. } else {
  42424. colorAttachment.view = this.context.getCurrentTexture().createView();
  42425. }
  42426. return descriptor;
  42427. }
  42428. _getRenderPassDescriptor( renderContext ) {
  42429. const renderTarget = renderContext.renderTarget;
  42430. const renderTargetData = this.get( renderTarget );
  42431. let descriptors = renderTargetData.descriptors;
  42432. if ( descriptors === undefined ) {
  42433. descriptors = [];
  42434. renderTargetData.descriptors = descriptors;
  42435. }
  42436. if ( renderTargetData.width !== renderTarget.width ||
  42437. renderTargetData.height !== renderTarget.height ||
  42438. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  42439. renderTargetData.samples !== renderTarget.samples
  42440. ) {
  42441. descriptors.length = 0;
  42442. }
  42443. let descriptor = descriptors[ renderContext.activeCubeFace ];
  42444. if ( descriptor === undefined ) {
  42445. const textures = renderContext.textures;
  42446. const colorAttachments = [];
  42447. for ( let i = 0; i < textures.length; i ++ ) {
  42448. const textureData = this.get( textures[ i ] );
  42449. const textureView = textureData.texture.createView( {
  42450. baseMipLevel: renderContext.activeMipmapLevel,
  42451. mipLevelCount: 1,
  42452. baseArrayLayer: renderContext.activeCubeFace,
  42453. dimension: GPUTextureViewDimension.TwoD
  42454. } );
  42455. let view, resolveTarget;
  42456. if ( textureData.msaaTexture !== undefined ) {
  42457. view = textureData.msaaTexture.createView();
  42458. resolveTarget = textureView;
  42459. } else {
  42460. view = textureView;
  42461. resolveTarget = undefined;
  42462. }
  42463. colorAttachments.push( {
  42464. view,
  42465. resolveTarget,
  42466. loadOp: GPULoadOp.Load,
  42467. storeOp: GPUStoreOp.Store
  42468. } );
  42469. }
  42470. const depthTextureData = this.get( renderContext.depthTexture );
  42471. const depthStencilAttachment = {
  42472. view: depthTextureData.texture.createView()
  42473. };
  42474. descriptor = {
  42475. colorAttachments,
  42476. depthStencilAttachment
  42477. };
  42478. descriptors[ renderContext.activeCubeFace ] = descriptor;
  42479. renderTargetData.width = renderTarget.width;
  42480. renderTargetData.height = renderTarget.height;
  42481. renderTargetData.samples = renderTarget.samples;
  42482. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  42483. }
  42484. return descriptor;
  42485. }
  42486. beginRender( renderContext ) {
  42487. const renderContextData = this.get( renderContext );
  42488. const device = this.device;
  42489. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42490. let occlusionQuerySet;
  42491. if ( occlusionQueryCount > 0 ) {
  42492. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  42493. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  42494. // Get a reference to the array of objects with queries. The renderContextData property
  42495. // can be changed by another render pass before the buffer.mapAsyc() completes.
  42496. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  42497. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  42498. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42499. //
  42500. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  42501. renderContextData.occlusionQuerySet = occlusionQuerySet;
  42502. renderContextData.occlusionQueryIndex = 0;
  42503. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42504. renderContextData.lastOcclusionObject = null;
  42505. }
  42506. let descriptor;
  42507. if ( renderContext.textures === null ) {
  42508. descriptor = this._getDefaultRenderPassDescriptor();
  42509. } else {
  42510. descriptor = this._getRenderPassDescriptor( renderContext );
  42511. }
  42512. this.initTimestampQuery( renderContext, descriptor );
  42513. descriptor.occlusionQuerySet = occlusionQuerySet;
  42514. const depthStencilAttachment = descriptor.depthStencilAttachment;
  42515. if ( renderContext.textures !== null ) {
  42516. const colorAttachments = descriptor.colorAttachments;
  42517. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  42518. const colorAttachment = colorAttachments[ i ];
  42519. if ( renderContext.clearColor ) {
  42520. colorAttachment.clearValue = renderContext.clearColorValue;
  42521. colorAttachment.loadOp = GPULoadOp.Clear;
  42522. colorAttachment.storeOp = GPUStoreOp.Store;
  42523. } else {
  42524. colorAttachment.loadOp = GPULoadOp.Load;
  42525. colorAttachment.storeOp = GPUStoreOp.Store;
  42526. }
  42527. }
  42528. } else {
  42529. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42530. if ( renderContext.clearColor ) {
  42531. colorAttachment.clearValue = renderContext.clearColorValue;
  42532. colorAttachment.loadOp = GPULoadOp.Clear;
  42533. colorAttachment.storeOp = GPUStoreOp.Store;
  42534. } else {
  42535. colorAttachment.loadOp = GPULoadOp.Load;
  42536. colorAttachment.storeOp = GPUStoreOp.Store;
  42537. }
  42538. }
  42539. //
  42540. if ( renderContext.depth ) {
  42541. if ( renderContext.clearDepth ) {
  42542. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  42543. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42544. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42545. } else {
  42546. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42547. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42548. }
  42549. }
  42550. if ( renderContext.stencil ) {
  42551. if ( renderContext.clearStencil ) {
  42552. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  42553. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42554. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42555. } else {
  42556. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42557. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42558. }
  42559. }
  42560. //
  42561. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  42562. const currentPass = encoder.beginRenderPass( descriptor );
  42563. //
  42564. renderContextData.descriptor = descriptor;
  42565. renderContextData.encoder = encoder;
  42566. renderContextData.currentPass = currentPass;
  42567. renderContextData.currentSets = { attributes: {} };
  42568. //
  42569. if ( renderContext.viewport ) {
  42570. this.updateViewport( renderContext );
  42571. }
  42572. if ( renderContext.scissor ) {
  42573. const { x, y, width, height } = renderContext.scissorValue;
  42574. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  42575. }
  42576. }
  42577. finishRender( renderContext ) {
  42578. const renderContextData = this.get( renderContext );
  42579. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42580. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  42581. renderContextData.registerBundlesPhase = false;
  42582. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  42583. }
  42584. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  42585. renderContextData.currentPass.endOcclusionQuery();
  42586. }
  42587. renderContextData.currentPass.end();
  42588. if ( occlusionQueryCount > 0 ) {
  42589. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  42590. //
  42591. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  42592. if ( queryResolveBuffer === undefined ) {
  42593. queryResolveBuffer = this.device.createBuffer(
  42594. {
  42595. size: bufferSize,
  42596. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  42597. }
  42598. );
  42599. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  42600. }
  42601. //
  42602. const readBuffer = this.device.createBuffer(
  42603. {
  42604. size: bufferSize,
  42605. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42606. }
  42607. );
  42608. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  42609. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  42610. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  42611. renderContextData.occlusionQueryBuffer = readBuffer;
  42612. //
  42613. this.resolveOccludedAsync( renderContext );
  42614. }
  42615. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  42616. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  42617. //
  42618. if ( renderContext.textures !== null ) {
  42619. const textures = renderContext.textures;
  42620. for ( let i = 0; i < textures.length; i ++ ) {
  42621. const texture = textures[ i ];
  42622. if ( texture.generateMipmaps === true ) {
  42623. this.textureUtils.generateMipmaps( texture );
  42624. }
  42625. }
  42626. }
  42627. }
  42628. isOccluded( renderContext, object ) {
  42629. const renderContextData = this.get( renderContext );
  42630. return renderContextData.occluded && renderContextData.occluded.has( object );
  42631. }
  42632. async resolveOccludedAsync( renderContext ) {
  42633. const renderContextData = this.get( renderContext );
  42634. // handle occlusion query results
  42635. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  42636. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  42637. const occluded = new WeakSet();
  42638. renderContextData.currentOcclusionQueryObjects = null;
  42639. renderContextData.currentOcclusionQueryBuffer = null;
  42640. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  42641. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  42642. const results = new BigUint64Array( buffer );
  42643. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  42644. if ( results[ i ] !== BigInt( 0 ) ) {
  42645. occluded.add( currentOcclusionQueryObjects[ i ] );
  42646. }
  42647. }
  42648. currentOcclusionQueryBuffer.destroy();
  42649. renderContextData.occluded = occluded;
  42650. }
  42651. }
  42652. updateViewport( renderContext ) {
  42653. const { currentPass } = this.get( renderContext );
  42654. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  42655. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  42656. }
  42657. clear( color, depth, stencil, renderTargetData = null ) {
  42658. const device = this.device;
  42659. const renderer = this.renderer;
  42660. let colorAttachments = [];
  42661. let depthStencilAttachment;
  42662. let clearValue;
  42663. let supportsDepth;
  42664. let supportsStencil;
  42665. if ( color ) {
  42666. const clearColor = this.getClearColor();
  42667. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  42668. }
  42669. if ( renderTargetData === null ) {
  42670. supportsDepth = renderer.depth;
  42671. supportsStencil = renderer.stencil;
  42672. const descriptor = this._getDefaultRenderPassDescriptor();
  42673. if ( color ) {
  42674. colorAttachments = descriptor.colorAttachments;
  42675. const colorAttachment = colorAttachments[ 0 ];
  42676. colorAttachment.clearValue = clearValue;
  42677. colorAttachment.loadOp = GPULoadOp.Clear;
  42678. colorAttachment.storeOp = GPUStoreOp.Store;
  42679. }
  42680. if ( supportsDepth || supportsStencil ) {
  42681. depthStencilAttachment = descriptor.depthStencilAttachment;
  42682. }
  42683. } else {
  42684. supportsDepth = renderTargetData.depth;
  42685. supportsStencil = renderTargetData.stencil;
  42686. if ( color ) {
  42687. for ( const texture of renderTargetData.textures ) {
  42688. const textureData = this.get( texture );
  42689. const textureView = textureData.texture.createView();
  42690. let view, resolveTarget;
  42691. if ( textureData.msaaTexture !== undefined ) {
  42692. view = textureData.msaaTexture.createView();
  42693. resolveTarget = textureView;
  42694. } else {
  42695. view = textureView;
  42696. resolveTarget = undefined;
  42697. }
  42698. colorAttachments.push( {
  42699. view,
  42700. resolveTarget,
  42701. clearValue,
  42702. loadOp: GPULoadOp.Clear,
  42703. storeOp: GPUStoreOp.Store
  42704. } );
  42705. }
  42706. }
  42707. if ( supportsDepth || supportsStencil ) {
  42708. const depthTextureData = this.get( renderTargetData.depthTexture );
  42709. depthStencilAttachment = {
  42710. view: depthTextureData.texture.createView()
  42711. };
  42712. }
  42713. }
  42714. //
  42715. if ( supportsDepth ) {
  42716. if ( depth ) {
  42717. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42718. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  42719. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42720. } else {
  42721. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42722. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42723. }
  42724. }
  42725. //
  42726. if ( supportsStencil ) {
  42727. if ( stencil ) {
  42728. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42729. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  42730. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42731. } else {
  42732. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42733. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42734. }
  42735. }
  42736. //
  42737. const encoder = device.createCommandEncoder( {} );
  42738. const currentPass = encoder.beginRenderPass( {
  42739. colorAttachments,
  42740. depthStencilAttachment
  42741. } );
  42742. currentPass.end();
  42743. device.queue.submit( [ encoder.finish() ] );
  42744. }
  42745. // compute
  42746. beginCompute( computeGroup ) {
  42747. const groupGPU = this.get( computeGroup );
  42748. const descriptor = {};
  42749. this.initTimestampQuery( computeGroup, descriptor );
  42750. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  42751. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  42752. }
  42753. compute( computeGroup, computeNode, bindings, pipeline ) {
  42754. const { passEncoderGPU } = this.get( computeGroup );
  42755. // pipeline
  42756. const pipelineGPU = this.get( pipeline ).pipeline;
  42757. passEncoderGPU.setPipeline( pipelineGPU );
  42758. // bind groups
  42759. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42760. const bindGroup = bindings[ i ];
  42761. const bindingsData = this.get( bindGroup );
  42762. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42763. }
  42764. passEncoderGPU.dispatchWorkgroups( computeNode.dispatchCount );
  42765. }
  42766. finishCompute( computeGroup ) {
  42767. const groupData = this.get( computeGroup );
  42768. groupData.passEncoderGPU.end();
  42769. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  42770. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  42771. }
  42772. // render object
  42773. draw( renderObject, info ) {
  42774. const { object, geometry, context, pipeline } = renderObject;
  42775. const bindings = renderObject.getBindings();
  42776. const contextData = this.get( context );
  42777. const pipelineGPU = this.get( pipeline ).pipeline;
  42778. const currentSets = contextData.currentSets;
  42779. const renderObjectData = this.get( renderObject );
  42780. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  42781. const renderContextData = this.get( context );
  42782. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  42783. renderContextData.renderBundles.push( renderBundle );
  42784. return;
  42785. }
  42786. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  42787. // pipeline
  42788. if ( currentSets.pipeline !== pipelineGPU ) {
  42789. passEncoderGPU.setPipeline( pipelineGPU );
  42790. currentSets.pipeline = pipelineGPU;
  42791. }
  42792. // bind groups
  42793. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42794. const bindGroup = bindings[ i ];
  42795. const bindingsData = this.get( bindGroup );
  42796. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42797. }
  42798. // attributes
  42799. const index = renderObject.getIndex();
  42800. const hasIndex = ( index !== null );
  42801. // index
  42802. if ( hasIndex === true ) {
  42803. if ( currentSets.index !== index ) {
  42804. const buffer = this.get( index ).buffer;
  42805. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42806. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  42807. currentSets.index = index;
  42808. }
  42809. }
  42810. // vertex buffers
  42811. const vertexBuffers = renderObject.getVertexBuffers();
  42812. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  42813. const vertexBuffer = vertexBuffers[ i ];
  42814. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  42815. const buffer = this.get( vertexBuffer ).buffer;
  42816. passEncoderGPU.setVertexBuffer( i, buffer );
  42817. currentSets.attributes[ i ] = vertexBuffer;
  42818. }
  42819. }
  42820. // occlusion queries - handle multiple consecutive draw calls for an object
  42821. if ( contextData.occlusionQuerySet !== undefined ) {
  42822. const lastObject = contextData.lastOcclusionObject;
  42823. if ( lastObject !== object ) {
  42824. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42825. passEncoderGPU.endOcclusionQuery();
  42826. contextData.occlusionQueryIndex ++;
  42827. }
  42828. if ( object.occlusionTest === true ) {
  42829. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  42830. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42831. }
  42832. contextData.lastOcclusionObject = object;
  42833. }
  42834. }
  42835. // draw
  42836. const drawRange = renderObject.drawRange;
  42837. const firstVertex = drawRange.start;
  42838. const instanceCount = this.getInstanceCount( renderObject );
  42839. if ( instanceCount === 0 ) return;
  42840. if ( object.isBatchedMesh === true ) {
  42841. const starts = object._multiDrawStarts;
  42842. const counts = object._multiDrawCounts;
  42843. const drawCount = object._multiDrawCount;
  42844. const drawInstances = object._multiDrawInstances;
  42845. const bytesPerElement = index.bytesPerElement || 1;
  42846. for ( let i = 0; i < drawCount; i ++ ) {
  42847. const count = drawInstances ? drawInstances[ i ] : 1;
  42848. const firstInstance = count > 1 ? 0 : i;
  42849. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, count, starts[ i ] / 4, 0, firstInstance );
  42850. }
  42851. } else if ( hasIndex === true ) {
  42852. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  42853. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  42854. info.update( object, indexCount, instanceCount );
  42855. } else {
  42856. const positionAttribute = geometry.attributes.position;
  42857. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  42858. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  42859. info.update( object, vertexCount, instanceCount );
  42860. }
  42861. if ( this.renderer._currentRenderBundle ) {
  42862. const renderBundle = passEncoderGPU.finish();
  42863. renderObjectData.lastPipelineGPU = pipelineGPU;
  42864. renderObjectData.renderBundle = renderBundle;
  42865. renderObjectData.bundleEncoder = passEncoderGPU;
  42866. }
  42867. }
  42868. // cache key
  42869. needsRenderUpdate( renderObject ) {
  42870. const data = this.get( renderObject );
  42871. const { object, material } = renderObject;
  42872. const utils = this.utils;
  42873. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  42874. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  42875. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  42876. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  42877. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  42878. let needsUpdate = false;
  42879. if ( data.material !== material || data.materialVersion !== material.version ||
  42880. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  42881. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  42882. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  42883. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  42884. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  42885. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  42886. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  42887. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  42888. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  42889. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  42890. data.primitiveTopology !== primitiveTopology ||
  42891. data.clippingContextVersion !== renderObject.clippingContextVersion
  42892. ) {
  42893. data.material = material; data.materialVersion = material.version;
  42894. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  42895. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  42896. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  42897. data.colorWrite = material.colorWrite;
  42898. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  42899. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  42900. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  42901. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  42902. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  42903. data.sampleCount = sampleCount;
  42904. data.colorSpace = colorSpace;
  42905. data.colorFormat = colorFormat;
  42906. data.depthStencilFormat = depthStencilFormat;
  42907. data.primitiveTopology = primitiveTopology;
  42908. data.clippingContextVersion = renderObject.clippingContextVersion;
  42909. needsUpdate = true;
  42910. }
  42911. return needsUpdate;
  42912. }
  42913. getRenderCacheKey( renderObject ) {
  42914. const { object, material } = renderObject;
  42915. const utils = this.utils;
  42916. const renderContext = renderObject.context;
  42917. return [
  42918. material.transparent, material.blending, material.premultipliedAlpha,
  42919. material.blendSrc, material.blendDst, material.blendEquation,
  42920. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  42921. material.colorWrite,
  42922. material.depthWrite, material.depthTest, material.depthFunc,
  42923. material.stencilWrite, material.stencilFunc,
  42924. material.stencilFail, material.stencilZFail, material.stencilZPass,
  42925. material.stencilFuncMask, material.stencilWriteMask,
  42926. material.side,
  42927. utils.getSampleCountRenderContext( renderContext ),
  42928. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  42929. utils.getPrimitiveTopology( object, material ),
  42930. renderObject.clippingContextVersion
  42931. ].join();
  42932. }
  42933. // textures
  42934. createSampler( texture ) {
  42935. this.textureUtils.createSampler( texture );
  42936. }
  42937. destroySampler( texture ) {
  42938. this.textureUtils.destroySampler( texture );
  42939. }
  42940. createDefaultTexture( texture ) {
  42941. this.textureUtils.createDefaultTexture( texture );
  42942. }
  42943. createTexture( texture, options ) {
  42944. this.textureUtils.createTexture( texture, options );
  42945. }
  42946. updateTexture( texture, options ) {
  42947. this.textureUtils.updateTexture( texture, options );
  42948. }
  42949. generateMipmaps( texture ) {
  42950. this.textureUtils.generateMipmaps( texture );
  42951. }
  42952. destroyTexture( texture ) {
  42953. this.textureUtils.destroyTexture( texture );
  42954. }
  42955. copyTextureToBuffer( texture, x, y, width, height ) {
  42956. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  42957. }
  42958. initTimestampQuery( renderContext, descriptor ) {
  42959. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42960. const renderContextData = this.get( renderContext );
  42961. if ( ! renderContextData.timeStampQuerySet ) {
  42962. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  42963. // beginning and one for the end of compute pass execution.
  42964. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  42965. const timestampWrites = {
  42966. querySet: timeStampQuerySet,
  42967. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  42968. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  42969. };
  42970. Object.assign( descriptor, {
  42971. timestampWrites,
  42972. } );
  42973. renderContextData.timeStampQuerySet = timeStampQuerySet;
  42974. }
  42975. }
  42976. // timestamp utils
  42977. prepareTimestampBuffer( renderContext, encoder ) {
  42978. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  42979. const renderContextData = this.get( renderContext );
  42980. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  42981. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  42982. renderContextData.currentTimestampQueryBuffers = {
  42983. resolveBuffer: this.device.createBuffer( {
  42984. label: 'timestamp resolve buffer',
  42985. size: size,
  42986. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  42987. } ),
  42988. resultBuffer: this.device.createBuffer( {
  42989. label: 'timestamp result buffer',
  42990. size: size,
  42991. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  42992. } ),
  42993. isMappingPending: false,
  42994. };
  42995. }
  42996. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  42997. if ( isMappingPending === true ) return;
  42998. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  42999. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  43000. }
  43001. async resolveTimestampAsync( renderContext, type = 'render' ) {
  43002. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  43003. const renderContextData = this.get( renderContext );
  43004. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  43005. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  43006. if ( isMappingPending === true ) return;
  43007. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  43008. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  43009. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  43010. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  43011. this.renderer.info.updateTimestamp( type, duration );
  43012. resultBuffer.unmap();
  43013. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  43014. } );
  43015. }
  43016. // node builder
  43017. createNodeBuilder( object, renderer ) {
  43018. return new WGSLNodeBuilder( object, renderer );
  43019. }
  43020. // program
  43021. createProgram( program ) {
  43022. const programGPU = this.get( program );
  43023. programGPU.module = {
  43024. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  43025. entryPoint: 'main'
  43026. };
  43027. }
  43028. destroyProgram( program ) {
  43029. this.delete( program );
  43030. }
  43031. // pipelines
  43032. createRenderPipeline( renderObject, promises ) {
  43033. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  43034. }
  43035. createComputePipeline( computePipeline, bindings ) {
  43036. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  43037. }
  43038. createBundleEncoder( renderContext, renderObject ) {
  43039. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  43040. }
  43041. // bindings
  43042. createBindings( bindGroup ) {
  43043. this.bindingUtils.createBindings( bindGroup );
  43044. }
  43045. updateBindings( bindGroup ) {
  43046. this.bindingUtils.createBindings( bindGroup );
  43047. }
  43048. updateBinding( binding ) {
  43049. this.bindingUtils.updateBinding( binding );
  43050. }
  43051. // attributes
  43052. createIndexAttribute( attribute ) {
  43053. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43054. }
  43055. createAttribute( attribute ) {
  43056. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43057. }
  43058. createStorageAttribute( attribute ) {
  43059. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43060. }
  43061. updateAttribute( attribute ) {
  43062. this.attributeUtils.updateAttribute( attribute );
  43063. }
  43064. destroyAttribute( attribute ) {
  43065. this.attributeUtils.destroyAttribute( attribute );
  43066. }
  43067. // canvas
  43068. updateSize() {
  43069. this.colorBuffer = this.textureUtils.getColorBuffer();
  43070. this.defaultRenderPassdescriptor = null;
  43071. }
  43072. // utils public
  43073. getMaxAnisotropy() {
  43074. return 16;
  43075. }
  43076. hasFeature( name ) {
  43077. return this.device.features.has( name );
  43078. }
  43079. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  43080. let dstX = 0;
  43081. let dstY = 0;
  43082. let srcX = 0;
  43083. let srcY = 0;
  43084. let srcWidth = srcTexture.image.width;
  43085. let srcHeight = srcTexture.image.height;
  43086. if ( srcRegion !== null ) {
  43087. srcX = srcRegion.x;
  43088. srcY = srcRegion.y;
  43089. srcWidth = srcRegion.width;
  43090. srcHeight = srcRegion.height;
  43091. }
  43092. if ( dstPosition !== null ) {
  43093. dstX = dstPosition.x;
  43094. dstY = dstPosition.y;
  43095. }
  43096. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  43097. const sourceGPU = this.get( srcTexture ).texture;
  43098. const destinationGPU = this.get( dstTexture ).texture;
  43099. encoder.copyTextureToTexture(
  43100. {
  43101. texture: sourceGPU,
  43102. mipLevel: level,
  43103. origin: { x: srcX, y: srcY, z: 0 }
  43104. },
  43105. {
  43106. texture: destinationGPU,
  43107. mipLevel: level,
  43108. origin: { x: dstX, y: dstY, z: 0 }
  43109. },
  43110. [
  43111. srcWidth,
  43112. srcHeight
  43113. ]
  43114. );
  43115. this.device.queue.submit( [ encoder.finish() ] );
  43116. }
  43117. copyFramebufferToTexture( texture, renderContext ) {
  43118. const renderContextData = this.get( renderContext );
  43119. const { encoder, descriptor } = renderContextData;
  43120. let sourceGPU = null;
  43121. if ( renderContext.renderTarget ) {
  43122. if ( texture.isDepthTexture ) {
  43123. sourceGPU = this.get( renderContext.depthTexture ).texture;
  43124. } else {
  43125. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  43126. }
  43127. } else {
  43128. if ( texture.isDepthTexture ) {
  43129. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  43130. } else {
  43131. sourceGPU = this.context.getCurrentTexture();
  43132. }
  43133. }
  43134. const destinationGPU = this.get( texture ).texture;
  43135. if ( sourceGPU.format !== destinationGPU.format ) {
  43136. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  43137. return;
  43138. }
  43139. renderContextData.currentPass.end();
  43140. encoder.copyTextureToTexture(
  43141. {
  43142. texture: sourceGPU,
  43143. origin: { x: 0, y: 0, z: 0 }
  43144. },
  43145. {
  43146. texture: destinationGPU
  43147. },
  43148. [
  43149. texture.image.width,
  43150. texture.image.height
  43151. ]
  43152. );
  43153. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  43154. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  43155. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43156. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43157. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  43158. renderContextData.currentSets = { attributes: {} };
  43159. }
  43160. }
  43161. /*
  43162. const debugHandler = {
  43163. get: function ( target, name ) {
  43164. // Add |update
  43165. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  43166. return target[ name ];
  43167. }
  43168. };
  43169. */
  43170. class WebGPURenderer extends Renderer {
  43171. constructor( parameters = {} ) {
  43172. let BackendClass;
  43173. if ( parameters.forceWebGL ) {
  43174. BackendClass = WebGLBackend;
  43175. } else if ( WebGPU.isAvailable() ) {
  43176. BackendClass = WebGPUBackend;
  43177. } else {
  43178. BackendClass = WebGLBackend;
  43179. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  43180. }
  43181. const backend = new BackendClass( parameters );
  43182. //super( new Proxy( backend, debugHandler ) );
  43183. super( backend, parameters );
  43184. this.isWebGPURenderer = true;
  43185. }
  43186. }
  43187. const quadMesh = new QuadMesh( new NodeMaterial() );
  43188. class PostProcessing {
  43189. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  43190. this.renderer = renderer;
  43191. this.outputNode = outputNode;
  43192. this.outputColorTransform = true;
  43193. this.needsUpdate = true;
  43194. }
  43195. render() {
  43196. this.update();
  43197. const renderer = this.renderer;
  43198. const toneMapping = renderer.toneMapping;
  43199. const outputColorSpace = renderer.outputColorSpace;
  43200. renderer.toneMapping = NoToneMapping;
  43201. renderer.outputColorSpace = LinearSRGBColorSpace;
  43202. //
  43203. quadMesh.render( this.renderer );
  43204. //
  43205. renderer.toneMapping = toneMapping;
  43206. renderer.outputColorSpace = outputColorSpace;
  43207. }
  43208. update() {
  43209. if ( this.needsUpdate === true ) {
  43210. const renderer = this.renderer;
  43211. const toneMapping = renderer.toneMapping;
  43212. const outputColorSpace = renderer.outputColorSpace;
  43213. quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  43214. quadMesh.material.needsUpdate = true;
  43215. this.needsUpdate = false;
  43216. }
  43217. }
  43218. async renderAsync() {
  43219. this.update();
  43220. const renderer = this.renderer;
  43221. const toneMapping = renderer.toneMapping;
  43222. const outputColorSpace = renderer.outputColorSpace;
  43223. renderer.toneMapping = NoToneMapping;
  43224. renderer.outputColorSpace = LinearSRGBColorSpace;
  43225. //
  43226. await quadMesh.renderAsync( this.renderer );
  43227. //
  43228. renderer.toneMapping = toneMapping;
  43229. renderer.outputColorSpace = outputColorSpace;
  43230. }
  43231. }
  43232. class StorageTexture extends Texture {
  43233. constructor( width = 1, height = 1 ) {
  43234. super();
  43235. this.image = { width, height };
  43236. this.magFilter = LinearFilter;
  43237. this.minFilter = LinearFilter;
  43238. this.isStorageTexture = true;
  43239. }
  43240. }
  43241. class StorageBufferAttribute extends BufferAttribute {
  43242. constructor( array, itemSize, typeClass = Float32Array ) {
  43243. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43244. super( array, itemSize );
  43245. this.isStorageBufferAttribute = true;
  43246. }
  43247. }
  43248. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  43249. constructor( array, itemSize, typeClass = Float32Array ) {
  43250. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43251. super( array, itemSize );
  43252. this.isStorageInstancedBufferAttribute = true;
  43253. }
  43254. }
  43255. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43256. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43257. revision: REVISION,
  43258. } } ) );
  43259. }
  43260. if ( typeof window !== 'undefined' ) {
  43261. if ( window.__THREE__ ) {
  43262. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43263. } else {
  43264. window.__THREE__ = REVISION;
  43265. }
  43266. }
  43267. 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, BasicEnvironmentNode, 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, RGBDepthPacking, 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, RGDepthPacking, 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 };