three.webgpu.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301
  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. const value = material[ property ];
  21572. let valueKey;
  21573. if ( value !== null ) {
  21574. const type = typeof value;
  21575. if ( type === 'number' ) valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21576. else if ( type === 'object' ) {
  21577. valueKey = '{';
  21578. if ( value.isTexture ) {
  21579. valueKey += value.mapping;
  21580. }
  21581. valueKey += '}';
  21582. }
  21583. } else {
  21584. valueKey = String( value );
  21585. }
  21586. cacheKey += /*property + ':' +*/ valueKey + ',';
  21587. }
  21588. cacheKey += this.clippingContextVersion + ',';
  21589. if ( object.skeleton ) {
  21590. cacheKey += object.skeleton.bones.length + ',';
  21591. }
  21592. if ( object.morphTargetInfluences ) {
  21593. cacheKey += object.morphTargetInfluences.length + ',';
  21594. }
  21595. if ( object.isBatchedMesh ) {
  21596. cacheKey += object._matricesTexture.uuid + ',';
  21597. if ( object._colorsTexture !== null ) {
  21598. cacheKey += object._colorsTexture.uuid + ',';
  21599. }
  21600. }
  21601. if ( object.count > 1 ) {
  21602. cacheKey += object.count + ',';
  21603. }
  21604. return cacheKey;
  21605. }
  21606. get needsUpdate() {
  21607. return this.initialNodesCacheKey !== this.getNodesCacheKey() || this.clippingNeedsUpdate;
  21608. }
  21609. getNodesCacheKey() {
  21610. // Environment Nodes Cache Key
  21611. return this._nodes.getCacheKey( this.scene, this.lightsNode );
  21612. }
  21613. getCacheKey() {
  21614. return this.getMaterialCacheKey() + ',' + this.getNodesCacheKey();
  21615. }
  21616. dispose() {
  21617. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21618. this.onDispose();
  21619. }
  21620. }
  21621. class RenderObjects {
  21622. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21623. this.renderer = renderer;
  21624. this.nodes = nodes;
  21625. this.geometries = geometries;
  21626. this.pipelines = pipelines;
  21627. this.bindings = bindings;
  21628. this.info = info;
  21629. this.chainMaps = {};
  21630. }
  21631. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  21632. const chainMap = this.getChainMap( passId );
  21633. const chainArray = [ object, material, renderContext, lightsNode ];
  21634. let renderObject = chainMap.get( chainArray );
  21635. if ( renderObject === undefined ) {
  21636. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  21637. chainMap.set( chainArray, renderObject );
  21638. } else {
  21639. renderObject.updateClipping( renderContext.clippingContext );
  21640. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21641. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21642. renderObject.dispose();
  21643. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  21644. } else {
  21645. renderObject.version = material.version;
  21646. }
  21647. }
  21648. }
  21649. return renderObject;
  21650. }
  21651. getChainMap( passId = 'default' ) {
  21652. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21653. }
  21654. dispose() {
  21655. this.chainMaps = {};
  21656. }
  21657. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  21658. const chainMap = this.getChainMap( passId );
  21659. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  21660. renderObject.onDispose = () => {
  21661. this.pipelines.delete( renderObject );
  21662. this.bindings.delete( renderObject );
  21663. this.nodes.delete( renderObject );
  21664. chainMap.delete( renderObject.getChainArray() );
  21665. };
  21666. return renderObject;
  21667. }
  21668. }
  21669. class DataMap {
  21670. constructor() {
  21671. this.data = new WeakMap();
  21672. }
  21673. get( object ) {
  21674. let map = this.data.get( object );
  21675. if ( map === undefined ) {
  21676. map = {};
  21677. this.data.set( object, map );
  21678. }
  21679. return map;
  21680. }
  21681. delete( object ) {
  21682. let map;
  21683. if ( this.data.has( object ) ) {
  21684. map = this.data.get( object );
  21685. this.data.delete( object );
  21686. }
  21687. return map;
  21688. }
  21689. has( object ) {
  21690. return this.data.has( object );
  21691. }
  21692. dispose() {
  21693. this.data = new WeakMap();
  21694. }
  21695. }
  21696. const AttributeType = {
  21697. VERTEX: 1,
  21698. INDEX: 2,
  21699. STORAGE: 4
  21700. };
  21701. // size of a chunk in bytes (STD140 layout)
  21702. const GPU_CHUNK_BYTES = 16;
  21703. // @TODO: Move to src/constants.js
  21704. const BlendColorFactor = 211;
  21705. const OneMinusBlendColorFactor = 212;
  21706. class Attributes extends DataMap {
  21707. constructor( backend ) {
  21708. super();
  21709. this.backend = backend;
  21710. }
  21711. delete( attribute ) {
  21712. const attributeData = super.delete( attribute );
  21713. if ( attributeData !== undefined ) {
  21714. this.backend.destroyAttribute( attribute );
  21715. }
  21716. return attributeData;
  21717. }
  21718. update( attribute, type ) {
  21719. const data = this.get( attribute );
  21720. if ( data.version === undefined ) {
  21721. if ( type === AttributeType.VERTEX ) {
  21722. this.backend.createAttribute( attribute );
  21723. } else if ( type === AttributeType.INDEX ) {
  21724. this.backend.createIndexAttribute( attribute );
  21725. } else if ( type === AttributeType.STORAGE ) {
  21726. this.backend.createStorageAttribute( attribute );
  21727. }
  21728. data.version = this._getBufferAttribute( attribute ).version;
  21729. } else {
  21730. const bufferAttribute = this._getBufferAttribute( attribute );
  21731. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21732. this.backend.updateAttribute( attribute );
  21733. data.version = bufferAttribute.version;
  21734. }
  21735. }
  21736. }
  21737. _getBufferAttribute( attribute ) {
  21738. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21739. return attribute;
  21740. }
  21741. }
  21742. function arrayNeedsUint32( array ) {
  21743. // assumes larger values usually on last
  21744. for ( let i = array.length - 1; i >= 0; -- i ) {
  21745. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  21746. }
  21747. return false;
  21748. }
  21749. function getWireframeVersion( geometry ) {
  21750. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21751. }
  21752. function getWireframeIndex( geometry ) {
  21753. const indices = [];
  21754. const geometryIndex = geometry.index;
  21755. const geometryPosition = geometry.attributes.position;
  21756. if ( geometryIndex !== null ) {
  21757. const array = geometryIndex.array;
  21758. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21759. const a = array[ i + 0 ];
  21760. const b = array[ i + 1 ];
  21761. const c = array[ i + 2 ];
  21762. indices.push( a, b, b, c, c, a );
  21763. }
  21764. } else {
  21765. const array = geometryPosition.array;
  21766. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21767. const a = i + 0;
  21768. const b = i + 1;
  21769. const c = i + 2;
  21770. indices.push( a, b, b, c, c, a );
  21771. }
  21772. }
  21773. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21774. attribute.version = getWireframeVersion( geometry );
  21775. return attribute;
  21776. }
  21777. class Geometries extends DataMap {
  21778. constructor( attributes, info ) {
  21779. super();
  21780. this.attributes = attributes;
  21781. this.info = info;
  21782. this.wireframes = new WeakMap();
  21783. this.attributeCall = new WeakMap();
  21784. }
  21785. has( renderObject ) {
  21786. const geometry = renderObject.geometry;
  21787. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21788. }
  21789. updateForRender( renderObject ) {
  21790. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21791. this.updateAttributes( renderObject );
  21792. }
  21793. initGeometry( renderObject ) {
  21794. const geometry = renderObject.geometry;
  21795. const geometryData = this.get( geometry );
  21796. geometryData.initialized = true;
  21797. this.info.memory.geometries ++;
  21798. const onDispose = () => {
  21799. this.info.memory.geometries --;
  21800. const index = geometry.index;
  21801. const geometryAttributes = renderObject.getAttributes();
  21802. if ( index !== null ) {
  21803. this.attributes.delete( index );
  21804. }
  21805. for ( const geometryAttribute of geometryAttributes ) {
  21806. this.attributes.delete( geometryAttribute );
  21807. }
  21808. const wireframeAttribute = this.wireframes.get( geometry );
  21809. if ( wireframeAttribute !== undefined ) {
  21810. this.attributes.delete( wireframeAttribute );
  21811. }
  21812. geometry.removeEventListener( 'dispose', onDispose );
  21813. };
  21814. geometry.addEventListener( 'dispose', onDispose );
  21815. }
  21816. updateAttributes( renderObject ) {
  21817. const attributes = renderObject.getAttributes();
  21818. for ( const attribute of attributes ) {
  21819. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21820. this.updateAttribute( attribute, AttributeType.STORAGE );
  21821. } else {
  21822. this.updateAttribute( attribute, AttributeType.VERTEX );
  21823. }
  21824. }
  21825. const index = this.getIndex( renderObject );
  21826. if ( index !== null ) {
  21827. this.updateAttribute( index, AttributeType.INDEX );
  21828. }
  21829. }
  21830. updateAttribute( attribute, type ) {
  21831. const callId = this.info.render.calls;
  21832. if ( ! attribute.isInterleavedBufferAttribute ) {
  21833. if ( this.attributeCall.get( attribute ) !== callId ) {
  21834. this.attributes.update( attribute, type );
  21835. this.attributeCall.set( attribute, callId );
  21836. }
  21837. } else {
  21838. if ( this.attributeCall.get( attribute ) === undefined ) {
  21839. this.attributes.update( attribute, type );
  21840. this.attributeCall.set( attribute, callId );
  21841. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21842. this.attributes.update( attribute, type );
  21843. this.attributeCall.set( attribute.data, callId );
  21844. this.attributeCall.set( attribute, callId );
  21845. }
  21846. }
  21847. }
  21848. getIndex( renderObject ) {
  21849. const { geometry, material } = renderObject;
  21850. let index = geometry.index;
  21851. if ( material.wireframe === true ) {
  21852. const wireframes = this.wireframes;
  21853. let wireframeAttribute = wireframes.get( geometry );
  21854. if ( wireframeAttribute === undefined ) {
  21855. wireframeAttribute = getWireframeIndex( geometry );
  21856. wireframes.set( geometry, wireframeAttribute );
  21857. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21858. this.attributes.delete( wireframeAttribute );
  21859. wireframeAttribute = getWireframeIndex( geometry );
  21860. wireframes.set( geometry, wireframeAttribute );
  21861. }
  21862. index = wireframeAttribute;
  21863. }
  21864. return index;
  21865. }
  21866. }
  21867. class Info {
  21868. constructor() {
  21869. this.autoReset = true;
  21870. this.frame = 0;
  21871. this.calls = 0;
  21872. this.render = {
  21873. calls: 0,
  21874. frameCalls: 0,
  21875. drawCalls: 0,
  21876. triangles: 0,
  21877. points: 0,
  21878. lines: 0,
  21879. timestamp: 0,
  21880. previousFrameCalls: 0,
  21881. timestampCalls: 0
  21882. };
  21883. this.compute = {
  21884. calls: 0,
  21885. frameCalls: 0,
  21886. timestamp: 0,
  21887. previousFrameCalls: 0,
  21888. timestampCalls: 0
  21889. };
  21890. this.memory = {
  21891. geometries: 0,
  21892. textures: 0
  21893. };
  21894. }
  21895. update( object, count, instanceCount ) {
  21896. this.render.drawCalls ++;
  21897. if ( object.isMesh || object.isSprite ) {
  21898. this.render.triangles += instanceCount * ( count / 3 );
  21899. } else if ( object.isPoints ) {
  21900. this.render.points += instanceCount * count;
  21901. } else if ( object.isLineSegments ) {
  21902. this.render.lines += instanceCount * ( count / 2 );
  21903. } else if ( object.isLine ) {
  21904. this.render.lines += instanceCount * ( count - 1 );
  21905. } else {
  21906. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  21907. }
  21908. }
  21909. updateTimestamp( type, time ) {
  21910. if ( this[ type ].timestampCalls === 0 ) {
  21911. this[ type ].timestamp = 0;
  21912. }
  21913. this[ type ].timestamp += time;
  21914. this[ type ].timestampCalls ++;
  21915. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  21916. this[ type ].timestampCalls = 0;
  21917. }
  21918. }
  21919. reset() {
  21920. const previousRenderFrameCalls = this.render.frameCalls;
  21921. this.render.previousFrameCalls = previousRenderFrameCalls;
  21922. const previousComputeFrameCalls = this.compute.frameCalls;
  21923. this.compute.previousFrameCalls = previousComputeFrameCalls;
  21924. this.render.drawCalls = 0;
  21925. this.render.frameCalls = 0;
  21926. this.compute.frameCalls = 0;
  21927. this.render.triangles = 0;
  21928. this.render.points = 0;
  21929. this.render.lines = 0;
  21930. }
  21931. dispose() {
  21932. this.reset();
  21933. this.calls = 0;
  21934. this.render.calls = 0;
  21935. this.compute.calls = 0;
  21936. this.render.timestamp = 0;
  21937. this.compute.timestamp = 0;
  21938. this.memory.geometries = 0;
  21939. this.memory.textures = 0;
  21940. }
  21941. }
  21942. class Pipeline {
  21943. constructor( cacheKey ) {
  21944. this.cacheKey = cacheKey;
  21945. this.usedTimes = 0;
  21946. }
  21947. }
  21948. class RenderPipeline extends Pipeline {
  21949. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21950. super( cacheKey );
  21951. this.vertexProgram = vertexProgram;
  21952. this.fragmentProgram = fragmentProgram;
  21953. }
  21954. }
  21955. class ComputePipeline extends Pipeline {
  21956. constructor( cacheKey, computeProgram ) {
  21957. super( cacheKey );
  21958. this.computeProgram = computeProgram;
  21959. this.isComputePipeline = true;
  21960. }
  21961. }
  21962. let _id$4 = 0;
  21963. class ProgrammableStage {
  21964. constructor( code, type, transforms = null, attributes = null ) {
  21965. this.id = _id$4 ++;
  21966. this.code = code;
  21967. this.stage = type;
  21968. this.transforms = transforms;
  21969. this.attributes = attributes;
  21970. this.usedTimes = 0;
  21971. }
  21972. }
  21973. class Pipelines extends DataMap {
  21974. constructor( backend, nodes ) {
  21975. super();
  21976. this.backend = backend;
  21977. this.nodes = nodes;
  21978. this.bindings = null; // set by the bindings
  21979. this.caches = new Map();
  21980. this.programs = {
  21981. vertex: new Map(),
  21982. fragment: new Map(),
  21983. compute: new Map()
  21984. };
  21985. }
  21986. getForCompute( computeNode, bindings ) {
  21987. const { backend } = this;
  21988. const data = this.get( computeNode );
  21989. if ( this._needsComputeUpdate( computeNode ) ) {
  21990. const previousPipeline = data.pipeline;
  21991. if ( previousPipeline ) {
  21992. previousPipeline.usedTimes --;
  21993. previousPipeline.computeProgram.usedTimes --;
  21994. }
  21995. // get shader
  21996. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21997. // programmable stage
  21998. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21999. if ( stageCompute === undefined ) {
  22000. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  22001. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  22002. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  22003. backend.createProgram( stageCompute );
  22004. }
  22005. // determine compute pipeline
  22006. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  22007. let pipeline = this.caches.get( cacheKey );
  22008. if ( pipeline === undefined ) {
  22009. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22010. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22011. }
  22012. // keep track of all used times
  22013. pipeline.usedTimes ++;
  22014. stageCompute.usedTimes ++;
  22015. //
  22016. data.version = computeNode.version;
  22017. data.pipeline = pipeline;
  22018. }
  22019. return data.pipeline;
  22020. }
  22021. getForRender( renderObject, promises = null ) {
  22022. const { backend } = this;
  22023. const data = this.get( renderObject );
  22024. if ( this._needsRenderUpdate( renderObject ) ) {
  22025. const previousPipeline = data.pipeline;
  22026. if ( previousPipeline ) {
  22027. previousPipeline.usedTimes --;
  22028. previousPipeline.vertexProgram.usedTimes --;
  22029. previousPipeline.fragmentProgram.usedTimes --;
  22030. }
  22031. // get shader
  22032. const nodeBuilderState = renderObject.getNodeBuilderState();
  22033. // programmable stages
  22034. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22035. if ( stageVertex === undefined ) {
  22036. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22037. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  22038. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22039. backend.createProgram( stageVertex );
  22040. }
  22041. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22042. if ( stageFragment === undefined ) {
  22043. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22044. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  22045. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22046. backend.createProgram( stageFragment );
  22047. }
  22048. // determine render pipeline
  22049. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22050. let pipeline = this.caches.get( cacheKey );
  22051. if ( pipeline === undefined ) {
  22052. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22053. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22054. } else {
  22055. renderObject.pipeline = pipeline;
  22056. }
  22057. // keep track of all used times
  22058. pipeline.usedTimes ++;
  22059. stageVertex.usedTimes ++;
  22060. stageFragment.usedTimes ++;
  22061. //
  22062. data.pipeline = pipeline;
  22063. }
  22064. return data.pipeline;
  22065. }
  22066. delete( object ) {
  22067. const pipeline = this.get( object ).pipeline;
  22068. if ( pipeline ) {
  22069. // pipeline
  22070. pipeline.usedTimes --;
  22071. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22072. // programs
  22073. if ( pipeline.isComputePipeline ) {
  22074. pipeline.computeProgram.usedTimes --;
  22075. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22076. } else {
  22077. pipeline.fragmentProgram.usedTimes --;
  22078. pipeline.vertexProgram.usedTimes --;
  22079. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22080. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22081. }
  22082. }
  22083. return super.delete( object );
  22084. }
  22085. dispose() {
  22086. super.dispose();
  22087. this.caches = new Map();
  22088. this.programs = {
  22089. vertex: new Map(),
  22090. fragment: new Map(),
  22091. compute: new Map()
  22092. };
  22093. }
  22094. updateForRender( renderObject ) {
  22095. this.getForRender( renderObject );
  22096. }
  22097. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22098. // check for existing pipeline
  22099. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22100. let pipeline = this.caches.get( cacheKey );
  22101. if ( pipeline === undefined ) {
  22102. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22103. this.caches.set( cacheKey, pipeline );
  22104. this.backend.createComputePipeline( pipeline, bindings );
  22105. }
  22106. return pipeline;
  22107. }
  22108. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22109. // check for existing pipeline
  22110. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22111. let pipeline = this.caches.get( cacheKey );
  22112. if ( pipeline === undefined ) {
  22113. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  22114. this.caches.set( cacheKey, pipeline );
  22115. renderObject.pipeline = pipeline;
  22116. this.backend.createRenderPipeline( renderObject, promises );
  22117. }
  22118. return pipeline;
  22119. }
  22120. _getComputeCacheKey( computeNode, stageCompute ) {
  22121. return computeNode.id + ',' + stageCompute.id;
  22122. }
  22123. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22124. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22125. }
  22126. _releasePipeline( pipeline ) {
  22127. this.caches.delete( pipeline.cacheKey );
  22128. }
  22129. _releaseProgram( program ) {
  22130. const code = program.code;
  22131. const stage = program.stage;
  22132. this.programs[ stage ].delete( code );
  22133. }
  22134. _needsComputeUpdate( computeNode ) {
  22135. const data = this.get( computeNode );
  22136. return data.pipeline === undefined || data.version !== computeNode.version;
  22137. }
  22138. _needsRenderUpdate( renderObject ) {
  22139. const data = this.get( renderObject );
  22140. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22141. }
  22142. }
  22143. class Bindings extends DataMap {
  22144. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22145. super();
  22146. this.backend = backend;
  22147. this.textures = textures;
  22148. this.pipelines = pipelines;
  22149. this.attributes = attributes;
  22150. this.nodes = nodes;
  22151. this.info = info;
  22152. this.pipelines.bindings = this; // assign bindings to pipelines
  22153. }
  22154. getForRender( renderObject ) {
  22155. const bindings = renderObject.getBindings();
  22156. for ( const bindGroup of bindings ) {
  22157. const groupData = this.get( bindGroup );
  22158. if ( groupData.bindGroup === undefined ) {
  22159. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22160. this._init( bindGroup );
  22161. this.backend.createBindings( bindGroup, bindings );
  22162. groupData.bindGroup = bindGroup;
  22163. }
  22164. }
  22165. return bindings;
  22166. }
  22167. getForCompute( computeNode ) {
  22168. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22169. for ( const bindGroup of bindings ) {
  22170. const groupData = this.get( bindGroup );
  22171. if ( groupData.bindGroup === undefined ) {
  22172. this._init( bindGroup );
  22173. this.backend.createBindings( bindGroup, bindings );
  22174. groupData.bindGroup = bindGroup;
  22175. }
  22176. }
  22177. return bindings;
  22178. }
  22179. updateForCompute( computeNode ) {
  22180. this._updateBindings( computeNode, this.getForCompute( computeNode ) );
  22181. }
  22182. updateForRender( renderObject ) {
  22183. this._updateBindings( renderObject, this.getForRender( renderObject ) );
  22184. }
  22185. _updateBindings( object, bindings ) {
  22186. for ( const bindGroup of bindings ) {
  22187. this._update( object, bindGroup, bindings );
  22188. }
  22189. }
  22190. _init( bindGroup ) {
  22191. for ( const binding of bindGroup.bindings ) {
  22192. if ( binding.isSampledTexture ) {
  22193. this.textures.updateTexture( binding.texture );
  22194. } else if ( binding.isStorageBuffer ) {
  22195. const attribute = binding.attribute;
  22196. this.attributes.update( attribute, AttributeType.STORAGE );
  22197. }
  22198. }
  22199. }
  22200. _update( object, bindGroup, bindings ) {
  22201. const { backend } = this;
  22202. let needsBindingsUpdate = false;
  22203. // iterate over all bindings and check if buffer updates or a new binding group is required
  22204. for ( const binding of bindGroup.bindings ) {
  22205. if ( binding.isNodeUniformsGroup ) {
  22206. const updated = this.nodes.updateGroup( binding );
  22207. if ( ! updated ) continue;
  22208. }
  22209. if ( binding.isUniformBuffer ) {
  22210. const updated = binding.update();
  22211. if ( updated ) {
  22212. backend.updateBinding( binding );
  22213. }
  22214. } else if ( binding.isSampler ) {
  22215. binding.update();
  22216. } else if ( binding.isSampledTexture ) {
  22217. const texture = binding.texture;
  22218. if ( binding.needsBindingsUpdate ) needsBindingsUpdate = true;
  22219. const updated = binding.update();
  22220. if ( updated ) {
  22221. this.textures.updateTexture( binding.texture );
  22222. }
  22223. const textureData = backend.get( binding.texture );
  22224. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  22225. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  22226. console.error( 'Bindings._update: binding should be available:', binding, updated, binding.texture, binding.textureNode.value );
  22227. this.textures.updateTexture( binding.texture );
  22228. needsBindingsUpdate = true;
  22229. }
  22230. if ( texture.isStorageTexture === true ) {
  22231. const textureData = this.get( texture );
  22232. if ( binding.store === true ) {
  22233. textureData.needsMipmap = true;
  22234. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22235. this.backend.generateMipmaps( texture );
  22236. textureData.needsMipmap = false;
  22237. }
  22238. }
  22239. }
  22240. }
  22241. if ( needsBindingsUpdate === true ) {
  22242. const pipeline = this.pipelines.getForRender( object );
  22243. this.backend.updateBindings( bindGroup, bindings, pipeline );
  22244. }
  22245. }
  22246. }
  22247. const NodeShaderStage = {
  22248. VERTEX: 'vertex',
  22249. FRAGMENT: 'fragment'
  22250. };
  22251. const NodeUpdateType = {
  22252. NONE: 'none',
  22253. FRAME: 'frame',
  22254. RENDER: 'render',
  22255. OBJECT: 'object'
  22256. };
  22257. const NodeType = {
  22258. BOOLEAN: 'bool',
  22259. INTEGER: 'int',
  22260. FLOAT: 'float',
  22261. VECTOR2: 'vec2',
  22262. VECTOR3: 'vec3',
  22263. VECTOR4: 'vec4',
  22264. MATRIX2: 'mat2',
  22265. MATRIX3: 'mat3',
  22266. MATRIX4: 'mat4'
  22267. };
  22268. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22269. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22270. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22271. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22272. function getCacheKey( object, force = false ) {
  22273. let cacheKey = '{';
  22274. if ( object.isNode === true ) {
  22275. cacheKey += object.id;
  22276. }
  22277. for ( const { property, childNode } of getNodeChildren( object ) ) {
  22278. cacheKey += ',' + property.slice( 0, - 4 ) + ':' + childNode.getCacheKey( force );
  22279. }
  22280. cacheKey += '}';
  22281. return cacheKey;
  22282. }
  22283. function* getNodeChildren( node, toJSON = false ) {
  22284. for ( const property in node ) {
  22285. // Ignore private properties.
  22286. if ( property.startsWith( '_' ) === true ) continue;
  22287. const object = node[ property ];
  22288. if ( Array.isArray( object ) === true ) {
  22289. for ( let i = 0; i < object.length; i ++ ) {
  22290. const child = object[ i ];
  22291. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22292. yield { property, index: i, childNode: child };
  22293. }
  22294. }
  22295. } else if ( object && object.isNode === true ) {
  22296. yield { property, childNode: object };
  22297. } else if ( typeof object === 'object' ) {
  22298. for ( const subProperty in object ) {
  22299. const child = object[ subProperty ];
  22300. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22301. yield { property, index: subProperty, childNode: child };
  22302. }
  22303. }
  22304. }
  22305. }
  22306. }
  22307. function getValueType( value ) {
  22308. if ( value === undefined || value === null ) return null;
  22309. const typeOf = typeof value;
  22310. if ( value.isNode === true ) {
  22311. return 'node';
  22312. } else if ( typeOf === 'number' ) {
  22313. return 'float';
  22314. } else if ( typeOf === 'boolean' ) {
  22315. return 'bool';
  22316. } else if ( typeOf === 'string' ) {
  22317. return 'string';
  22318. } else if ( typeOf === 'function' ) {
  22319. return 'shader';
  22320. } else if ( value.isVector2 === true ) {
  22321. return 'vec2';
  22322. } else if ( value.isVector3 === true ) {
  22323. return 'vec3';
  22324. } else if ( value.isVector4 === true ) {
  22325. return 'vec4';
  22326. } else if ( value.isMatrix3 === true ) {
  22327. return 'mat3';
  22328. } else if ( value.isMatrix4 === true ) {
  22329. return 'mat4';
  22330. } else if ( value.isColor === true ) {
  22331. return 'color';
  22332. } else if ( value instanceof ArrayBuffer ) {
  22333. return 'ArrayBuffer';
  22334. }
  22335. return null;
  22336. }
  22337. function getValueFromType( type, ...params ) {
  22338. const last4 = type ? type.slice( - 4 ) : undefined;
  22339. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  22340. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  22341. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  22342. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  22343. }
  22344. if ( type === 'color' ) {
  22345. return new Color( ...params );
  22346. } else if ( last4 === 'vec2' ) {
  22347. return new Vector2( ...params );
  22348. } else if ( last4 === 'vec3' ) {
  22349. return new Vector3( ...params );
  22350. } else if ( last4 === 'vec4' ) {
  22351. return new Vector4( ...params );
  22352. } else if ( last4 === 'mat3' ) {
  22353. return new Matrix3( ...params );
  22354. } else if ( last4 === 'mat4' ) {
  22355. return new Matrix4( ...params );
  22356. } else if ( type === 'bool' ) {
  22357. return params[ 0 ] || false;
  22358. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  22359. return params[ 0 ] || 0;
  22360. } else if ( type === 'string' ) {
  22361. return params[ 0 ] || '';
  22362. } else if ( type === 'ArrayBuffer' ) {
  22363. return base64ToArrayBuffer( params[ 0 ] );
  22364. }
  22365. return null;
  22366. }
  22367. function arrayBufferToBase64( arrayBuffer ) {
  22368. let chars = '';
  22369. const array = new Uint8Array( arrayBuffer );
  22370. for ( let i = 0; i < array.length; i ++ ) {
  22371. chars += String.fromCharCode( array[ i ] );
  22372. }
  22373. return btoa( chars );
  22374. }
  22375. function base64ToArrayBuffer( base64 ) {
  22376. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  22377. }
  22378. var NodeUtils = /*#__PURE__*/Object.freeze({
  22379. __proto__: null,
  22380. arrayBufferToBase64: arrayBufferToBase64,
  22381. base64ToArrayBuffer: base64ToArrayBuffer,
  22382. getCacheKey: getCacheKey,
  22383. getNodeChildren: getNodeChildren,
  22384. getValueFromType: getValueFromType,
  22385. getValueType: getValueType
  22386. });
  22387. const NodeClasses = new Map();
  22388. let _nodeId = 0;
  22389. class Node extends EventDispatcher {
  22390. constructor( nodeType = null ) {
  22391. super();
  22392. this.nodeType = nodeType;
  22393. this.updateType = NodeUpdateType.NONE;
  22394. this.updateBeforeType = NodeUpdateType.NONE;
  22395. this.updateAfterType = NodeUpdateType.NONE;
  22396. this.uuid = MathUtils.generateUUID();
  22397. this.version = 0;
  22398. this._cacheKey = null;
  22399. this._cacheKeyVersion = 0;
  22400. this.global = false;
  22401. this.isNode = true;
  22402. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22403. }
  22404. set needsUpdate( value ) {
  22405. if ( value === true ) {
  22406. this.version ++;
  22407. }
  22408. }
  22409. get type() {
  22410. return this.constructor.type;
  22411. }
  22412. onUpdate( callback, updateType ) {
  22413. this.updateType = updateType;
  22414. this.update = callback.bind( this.getSelf() );
  22415. return this;
  22416. }
  22417. onFrameUpdate( callback ) {
  22418. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22419. }
  22420. onRenderUpdate( callback ) {
  22421. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22422. }
  22423. onObjectUpdate( callback ) {
  22424. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22425. }
  22426. onReference( callback ) {
  22427. this.updateReference = callback.bind( this.getSelf() );
  22428. return this;
  22429. }
  22430. getSelf() {
  22431. // Returns non-node object.
  22432. return this.self || this;
  22433. }
  22434. updateReference( /*state*/ ) {
  22435. return this;
  22436. }
  22437. isGlobal( /*builder*/ ) {
  22438. return this.global;
  22439. }
  22440. * getChildren() {
  22441. for ( const { childNode } of getNodeChildren( this ) ) {
  22442. yield childNode;
  22443. }
  22444. }
  22445. dispose() {
  22446. this.dispatchEvent( { type: 'dispose' } );
  22447. }
  22448. traverse( callback ) {
  22449. callback( this );
  22450. for ( const childNode of this.getChildren() ) {
  22451. childNode.traverse( callback );
  22452. }
  22453. }
  22454. getCacheKey( force = false ) {
  22455. force = force || this.version !== this._cacheKeyVersion;
  22456. if ( force === true || this._cacheKey === null ) {
  22457. this._cacheKey = getCacheKey( this, force );
  22458. this._cacheKeyVersion = this.version;
  22459. }
  22460. return this._cacheKey;
  22461. }
  22462. getHash( /*builder*/ ) {
  22463. return this.uuid;
  22464. }
  22465. getUpdateType() {
  22466. return this.updateType;
  22467. }
  22468. getUpdateBeforeType() {
  22469. return this.updateBeforeType;
  22470. }
  22471. getUpdateAfterType() {
  22472. return this.updateAfterType;
  22473. }
  22474. getElementType( builder ) {
  22475. const type = this.getNodeType( builder );
  22476. const elementType = builder.getElementType( type );
  22477. return elementType;
  22478. }
  22479. getNodeType( builder ) {
  22480. const nodeProperties = builder.getNodeProperties( this );
  22481. if ( nodeProperties.outputNode ) {
  22482. return nodeProperties.outputNode.getNodeType( builder );
  22483. }
  22484. return this.nodeType;
  22485. }
  22486. getShared( builder ) {
  22487. const hash = this.getHash( builder );
  22488. const nodeFromHash = builder.getNodeFromHash( hash );
  22489. return nodeFromHash || this;
  22490. }
  22491. setup( builder ) {
  22492. const nodeProperties = builder.getNodeProperties( this );
  22493. let index = 0;
  22494. for ( const childNode of this.getChildren() ) {
  22495. nodeProperties[ 'node' + index ++ ] = childNode;
  22496. }
  22497. // return a outputNode if exists
  22498. return null;
  22499. }
  22500. construct( builder ) { // @deprecated, r157
  22501. console.warn( 'THREE.Node: construct() is deprecated. Use setup() instead.' );
  22502. return this.setup( builder );
  22503. }
  22504. increaseUsage( builder ) {
  22505. const nodeData = builder.getDataFromNode( this );
  22506. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  22507. return nodeData.usageCount;
  22508. }
  22509. analyze( builder ) {
  22510. const usageCount = this.increaseUsage( builder );
  22511. if ( usageCount === 1 ) {
  22512. // node flow children
  22513. const nodeProperties = builder.getNodeProperties( this );
  22514. for ( const childNode of Object.values( nodeProperties ) ) {
  22515. if ( childNode && childNode.isNode === true ) {
  22516. childNode.build( builder );
  22517. }
  22518. }
  22519. }
  22520. }
  22521. generate( builder, output ) {
  22522. const { outputNode } = builder.getNodeProperties( this );
  22523. if ( outputNode && outputNode.isNode === true ) {
  22524. return outputNode.build( builder, output );
  22525. }
  22526. }
  22527. updateBefore( /*frame*/ ) {
  22528. console.warn( 'Abstract function.' );
  22529. }
  22530. updateAfter( /*frame*/ ) {
  22531. console.warn( 'Abstract function.' );
  22532. }
  22533. update( /*frame*/ ) {
  22534. console.warn( 'Abstract function.' );
  22535. }
  22536. build( builder, output = null ) {
  22537. const refNode = this.getShared( builder );
  22538. if ( this !== refNode ) {
  22539. return refNode.build( builder, output );
  22540. }
  22541. builder.addNode( this );
  22542. builder.addChain( this );
  22543. /* Build stages expected results:
  22544. - "setup" -> Node
  22545. - "analyze" -> null
  22546. - "generate" -> String
  22547. */
  22548. let result = null;
  22549. const buildStage = builder.getBuildStage();
  22550. if ( buildStage === 'setup' ) {
  22551. this.updateReference( builder );
  22552. const properties = builder.getNodeProperties( this );
  22553. if ( properties.initialized !== true ) {
  22554. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22555. properties.initialized = true;
  22556. properties.outputNode = this.setup( builder );
  22557. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  22558. properties.outputNode = builder.stack;
  22559. }
  22560. for ( const childNode of Object.values( properties ) ) {
  22561. if ( childNode && childNode.isNode === true ) {
  22562. childNode.build( builder );
  22563. }
  22564. }
  22565. }
  22566. } else if ( buildStage === 'analyze' ) {
  22567. this.analyze( builder );
  22568. } else if ( buildStage === 'generate' ) {
  22569. const isGenerateOnce = this.generate.length === 1;
  22570. if ( isGenerateOnce ) {
  22571. const type = this.getNodeType( builder );
  22572. const nodeData = builder.getDataFromNode( this );
  22573. result = nodeData.snippet;
  22574. if ( result === undefined ) {
  22575. result = this.generate( builder ) || '';
  22576. nodeData.snippet = result;
  22577. }
  22578. result = builder.format( result, type, output );
  22579. } else {
  22580. result = this.generate( builder, output ) || '';
  22581. }
  22582. }
  22583. builder.removeChain( this );
  22584. return result;
  22585. }
  22586. getSerializeChildren() {
  22587. return getNodeChildren( this );
  22588. }
  22589. serialize( json ) {
  22590. const nodeChildren = this.getSerializeChildren();
  22591. const inputNodes = {};
  22592. for ( const { property, index, childNode } of nodeChildren ) {
  22593. if ( index !== undefined ) {
  22594. if ( inputNodes[ property ] === undefined ) {
  22595. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22596. }
  22597. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22598. } else {
  22599. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22600. }
  22601. }
  22602. if ( Object.keys( inputNodes ).length > 0 ) {
  22603. json.inputNodes = inputNodes;
  22604. }
  22605. }
  22606. deserialize( json ) {
  22607. if ( json.inputNodes !== undefined ) {
  22608. const nodes = json.meta.nodes;
  22609. for ( const property in json.inputNodes ) {
  22610. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22611. const inputArray = [];
  22612. for ( const uuid of json.inputNodes[ property ] ) {
  22613. inputArray.push( nodes[ uuid ] );
  22614. }
  22615. this[ property ] = inputArray;
  22616. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22617. const inputObject = {};
  22618. for ( const subProperty in json.inputNodes[ property ] ) {
  22619. const uuid = json.inputNodes[ property ][ subProperty ];
  22620. inputObject[ subProperty ] = nodes[ uuid ];
  22621. }
  22622. this[ property ] = inputObject;
  22623. } else {
  22624. const uuid = json.inputNodes[ property ];
  22625. this[ property ] = nodes[ uuid ];
  22626. }
  22627. }
  22628. }
  22629. }
  22630. toJSON( meta ) {
  22631. const { uuid, type } = this;
  22632. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22633. if ( isRoot ) {
  22634. meta = {
  22635. textures: {},
  22636. images: {},
  22637. nodes: {}
  22638. };
  22639. }
  22640. // serialize
  22641. let data = meta.nodes[ uuid ];
  22642. if ( data === undefined ) {
  22643. data = {
  22644. uuid,
  22645. type,
  22646. meta,
  22647. metadata: {
  22648. version: 4.6,
  22649. type: 'Node',
  22650. generator: 'Node.toJSON'
  22651. }
  22652. };
  22653. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22654. this.serialize( data );
  22655. delete data.meta;
  22656. }
  22657. // TODO: Copied from Object3D.toJSON
  22658. function extractFromCache( cache ) {
  22659. const values = [];
  22660. for ( const key in cache ) {
  22661. const data = cache[ key ];
  22662. delete data.metadata;
  22663. values.push( data );
  22664. }
  22665. return values;
  22666. }
  22667. if ( isRoot ) {
  22668. const textures = extractFromCache( meta.textures );
  22669. const images = extractFromCache( meta.images );
  22670. const nodes = extractFromCache( meta.nodes );
  22671. if ( textures.length > 0 ) data.textures = textures;
  22672. if ( images.length > 0 ) data.images = images;
  22673. if ( nodes.length > 0 ) data.nodes = nodes;
  22674. }
  22675. return data;
  22676. }
  22677. }
  22678. function addNodeClass( type, nodeClass ) {
  22679. if ( typeof nodeClass !== 'function' || ! type ) throw new Error( `Node class ${ type } is not a class` );
  22680. if ( NodeClasses.has( type ) ) {
  22681. console.warn( `Redefinition of node class ${ type }` );
  22682. return;
  22683. }
  22684. NodeClasses.set( type, nodeClass );
  22685. nodeClass.type = type;
  22686. }
  22687. function createNodeFromType( type ) {
  22688. const Class = NodeClasses.get( type );
  22689. if ( Class !== undefined ) {
  22690. return new Class();
  22691. }
  22692. }
  22693. class TempNode extends Node {
  22694. constructor( type ) {
  22695. super( type );
  22696. this.isTempNode = true;
  22697. }
  22698. hasDependencies( builder ) {
  22699. return builder.getDataFromNode( this ).usageCount > 1;
  22700. }
  22701. build( builder, output ) {
  22702. const buildStage = builder.getBuildStage();
  22703. if ( buildStage === 'generate' ) {
  22704. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22705. const nodeData = builder.getDataFromNode( this );
  22706. if ( nodeData.propertyName !== undefined ) {
  22707. return builder.format( nodeData.propertyName, type, output );
  22708. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22709. const snippet = super.build( builder, type );
  22710. const nodeVar = builder.getVarFromNode( this, null, type );
  22711. const propertyName = builder.getPropertyName( nodeVar );
  22712. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  22713. nodeData.snippet = snippet;
  22714. nodeData.propertyName = propertyName;
  22715. return builder.format( nodeData.propertyName, type, output );
  22716. }
  22717. }
  22718. return super.build( builder, output );
  22719. }
  22720. }
  22721. addNodeClass( 'TempNode', TempNode );
  22722. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  22723. constructor( node, indexNode ) {
  22724. super();
  22725. this.node = node;
  22726. this.indexNode = indexNode;
  22727. this.isArrayElementNode = true;
  22728. }
  22729. getNodeType( builder ) {
  22730. return this.node.getElementType( builder );
  22731. }
  22732. generate( builder ) {
  22733. const nodeSnippet = this.node.build( builder );
  22734. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22735. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22736. }
  22737. }
  22738. addNodeClass( 'ArrayElementNode', ArrayElementNode );
  22739. class ConvertNode extends Node {
  22740. constructor( node, convertTo ) {
  22741. super();
  22742. this.node = node;
  22743. this.convertTo = convertTo;
  22744. }
  22745. getNodeType( builder ) {
  22746. const requestType = this.node.getNodeType( builder );
  22747. let convertTo = null;
  22748. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22749. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22750. convertTo = overloadingType;
  22751. }
  22752. }
  22753. return convertTo;
  22754. }
  22755. serialize( data ) {
  22756. super.serialize( data );
  22757. data.convertTo = this.convertTo;
  22758. }
  22759. deserialize( data ) {
  22760. super.deserialize( data );
  22761. this.convertTo = data.convertTo;
  22762. }
  22763. generate( builder, output ) {
  22764. const node = this.node;
  22765. const type = this.getNodeType( builder );
  22766. const snippet = node.build( builder, type );
  22767. return builder.format( snippet, type, output );
  22768. }
  22769. }
  22770. addNodeClass( 'ConvertNode', ConvertNode );
  22771. class JoinNode extends TempNode {
  22772. constructor( nodes = [], nodeType = null ) {
  22773. super( nodeType );
  22774. this.nodes = nodes;
  22775. }
  22776. getNodeType( builder ) {
  22777. if ( this.nodeType !== null ) {
  22778. return builder.getVectorType( this.nodeType );
  22779. }
  22780. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22781. }
  22782. generate( builder, output ) {
  22783. const type = this.getNodeType( builder );
  22784. const nodes = this.nodes;
  22785. const primitiveType = builder.getComponentType( type );
  22786. const snippetValues = [];
  22787. for ( const input of nodes ) {
  22788. let inputSnippet = input.build( builder );
  22789. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22790. if ( inputPrimitiveType !== primitiveType ) {
  22791. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22792. }
  22793. snippetValues.push( inputSnippet );
  22794. }
  22795. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22796. return builder.format( snippet, type, output );
  22797. }
  22798. }
  22799. addNodeClass( 'JoinNode', JoinNode );
  22800. const stringVectorComponents = vectorComponents.join( '' );
  22801. class SplitNode extends Node {
  22802. constructor( node, components = 'x' ) {
  22803. super();
  22804. this.node = node;
  22805. this.components = components;
  22806. this.isSplitNode = true;
  22807. }
  22808. getVectorLength() {
  22809. let vectorLength = this.components.length;
  22810. for ( const c of this.components ) {
  22811. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22812. }
  22813. return vectorLength;
  22814. }
  22815. getComponentType( builder ) {
  22816. return builder.getComponentType( this.node.getNodeType( builder ) );
  22817. }
  22818. getNodeType( builder ) {
  22819. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22820. }
  22821. generate( builder, output ) {
  22822. const node = this.node;
  22823. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22824. let snippet = null;
  22825. if ( nodeTypeLength > 1 ) {
  22826. let type = null;
  22827. const componentsLength = this.getVectorLength();
  22828. if ( componentsLength >= nodeTypeLength ) {
  22829. // needed expand the input node
  22830. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22831. }
  22832. const nodeSnippet = node.build( builder, type );
  22833. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22834. // unnecessary swizzle
  22835. snippet = builder.format( nodeSnippet, type, output );
  22836. } else {
  22837. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22838. }
  22839. } else {
  22840. // ignore .components if .node returns float/integer
  22841. snippet = node.build( builder, output );
  22842. }
  22843. return snippet;
  22844. }
  22845. serialize( data ) {
  22846. super.serialize( data );
  22847. data.components = this.components;
  22848. }
  22849. deserialize( data ) {
  22850. super.deserialize( data );
  22851. this.components = data.components;
  22852. }
  22853. }
  22854. addNodeClass( 'SplitNode', SplitNode );
  22855. class SetNode extends TempNode {
  22856. constructor( sourceNode, components, targetNode ) {
  22857. super();
  22858. this.sourceNode = sourceNode;
  22859. this.components = components;
  22860. this.targetNode = targetNode;
  22861. }
  22862. getNodeType( builder ) {
  22863. return this.sourceNode.getNodeType( builder );
  22864. }
  22865. generate( builder ) {
  22866. const { sourceNode, components, targetNode } = this;
  22867. const sourceType = this.getNodeType( builder );
  22868. const targetType = builder.getTypeFromLength( components.length );
  22869. const targetSnippet = targetNode.build( builder, targetType );
  22870. const sourceSnippet = sourceNode.build( builder, sourceType );
  22871. const length = builder.getTypeLength( sourceType );
  22872. const snippetValues = [];
  22873. for ( let i = 0; i < length; i ++ ) {
  22874. const component = vectorComponents[ i ];
  22875. if ( component === components[ 0 ] ) {
  22876. snippetValues.push( targetSnippet );
  22877. i += components.length - 1;
  22878. } else {
  22879. snippetValues.push( sourceSnippet + '.' + component );
  22880. }
  22881. }
  22882. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22883. }
  22884. }
  22885. addNodeClass( 'SetNode', SetNode );
  22886. class InputNode extends Node {
  22887. constructor( value, nodeType = null ) {
  22888. super( nodeType );
  22889. this.isInputNode = true;
  22890. this.value = value;
  22891. this.precision = null;
  22892. }
  22893. getNodeType( /*builder*/ ) {
  22894. if ( this.nodeType === null ) {
  22895. return getValueType( this.value );
  22896. }
  22897. return this.nodeType;
  22898. }
  22899. getInputType( builder ) {
  22900. return this.getNodeType( builder );
  22901. }
  22902. setPrecision( precision ) {
  22903. this.precision = precision;
  22904. return this;
  22905. }
  22906. serialize( data ) {
  22907. super.serialize( data );
  22908. data.value = this.value;
  22909. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22910. data.valueType = getValueType( this.value );
  22911. data.nodeType = this.nodeType;
  22912. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22913. data.precision = this.precision;
  22914. }
  22915. deserialize( data ) {
  22916. super.deserialize( data );
  22917. this.nodeType = data.nodeType;
  22918. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22919. this.precision = data.precision || null;
  22920. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22921. }
  22922. generate( /*builder, output*/ ) {
  22923. console.warn( 'Abstract function.' );
  22924. }
  22925. }
  22926. addNodeClass( 'InputNode', InputNode );
  22927. class ConstNode extends InputNode {
  22928. constructor( value, nodeType = null ) {
  22929. super( value, nodeType );
  22930. this.isConstNode = true;
  22931. }
  22932. generateConst( builder ) {
  22933. return builder.generateConst( this.getNodeType( builder ), this.value );
  22934. }
  22935. generate( builder, output ) {
  22936. const type = this.getNodeType( builder );
  22937. return builder.format( this.generateConst( builder ), type, output );
  22938. }
  22939. }
  22940. addNodeClass( 'ConstNode', ConstNode );
  22941. //
  22942. let currentStack = null;
  22943. const NodeElements = new Map(); // @TODO: Currently only a few nodes are added, probably also add others
  22944. function addNodeElement( name, nodeElement ) {
  22945. if ( NodeElements.has( name ) ) {
  22946. console.warn( `Redefinition of node element ${ name }` );
  22947. return;
  22948. }
  22949. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22950. NodeElements.set( name, nodeElement );
  22951. }
  22952. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22953. const shaderNodeHandler = {
  22954. setup( NodeClosure, params ) {
  22955. const inputs = params.shift();
  22956. return NodeClosure( nodeObjects( inputs ), ...params );
  22957. },
  22958. get( node, prop, nodeObj ) {
  22959. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22960. if ( node.isStackNode !== true && prop === 'assign' ) {
  22961. return ( ...params ) => {
  22962. currentStack.assign( nodeObj, ...params );
  22963. return nodeObj;
  22964. };
  22965. } else if ( NodeElements.has( prop ) ) {
  22966. const nodeElement = NodeElements.get( prop );
  22967. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22968. } else if ( prop === 'self' ) {
  22969. return node;
  22970. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22971. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22972. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22973. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22974. // accessing properties ( swizzle )
  22975. prop = parseSwizzle( prop );
  22976. return nodeObject( new SplitNode( nodeObj, prop ) );
  22977. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22978. // set properties ( swizzle )
  22979. prop = parseSwizzle( prop.slice( 3 ).toLowerCase() );
  22980. // sort to xyzw sequence
  22981. prop = prop.split( '' ).sort().join( '' );
  22982. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22983. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22984. // accessing property
  22985. if ( prop === 'width' ) prop = 'x';
  22986. else if ( prop === 'height' ) prop = 'y';
  22987. else if ( prop === 'depth' ) prop = 'z';
  22988. return nodeObject( new SplitNode( node, prop ) );
  22989. } else if ( /^\d+$/.test( prop ) === true ) {
  22990. // accessing array
  22991. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22992. }
  22993. }
  22994. return Reflect.get( node, prop, nodeObj );
  22995. },
  22996. set( node, prop, value, nodeObj ) {
  22997. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22998. // setting properties
  22999. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  23000. nodeObj[ prop ].assign( value );
  23001. return true;
  23002. }
  23003. }
  23004. return Reflect.set( node, prop, value, nodeObj );
  23005. }
  23006. };
  23007. const nodeObjectsCacheMap = new WeakMap();
  23008. const nodeBuilderFunctionsCacheMap = new WeakMap();
  23009. const ShaderNodeObject = function ( obj, altType = null ) {
  23010. const type = getValueType( obj );
  23011. if ( type === 'node' ) {
  23012. let nodeObject = nodeObjectsCacheMap.get( obj );
  23013. if ( nodeObject === undefined ) {
  23014. nodeObject = new Proxy( obj, shaderNodeHandler );
  23015. nodeObjectsCacheMap.set( obj, nodeObject );
  23016. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  23017. }
  23018. return nodeObject;
  23019. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  23020. return nodeObject( getConstNode( obj, altType ) );
  23021. } else if ( type === 'shader' ) {
  23022. return tslFn( obj );
  23023. }
  23024. return obj;
  23025. };
  23026. const ShaderNodeObjects = function ( objects, altType = null ) {
  23027. for ( const name in objects ) {
  23028. objects[ name ] = nodeObject( objects[ name ], altType );
  23029. }
  23030. return objects;
  23031. };
  23032. const ShaderNodeArray = function ( array, altType = null ) {
  23033. const len = array.length;
  23034. for ( let i = 0; i < len; i ++ ) {
  23035. array[ i ] = nodeObject( array[ i ], altType );
  23036. }
  23037. return array;
  23038. };
  23039. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  23040. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  23041. if ( scope === null ) {
  23042. return ( ...params ) => {
  23043. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  23044. };
  23045. } else if ( factor !== null ) {
  23046. factor = nodeObject( factor );
  23047. return ( ...params ) => {
  23048. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  23049. };
  23050. } else {
  23051. return ( ...params ) => {
  23052. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  23053. };
  23054. }
  23055. };
  23056. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  23057. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  23058. };
  23059. class ShaderCallNodeInternal extends Node {
  23060. constructor( shaderNode, inputNodes ) {
  23061. super();
  23062. this.shaderNode = shaderNode;
  23063. this.inputNodes = inputNodes;
  23064. }
  23065. getNodeType( builder ) {
  23066. const properties = builder.getNodeProperties( this );
  23067. if ( properties.outputNode === null ) {
  23068. properties.outputNode = this.setupOutput( builder );
  23069. }
  23070. return properties.outputNode.getNodeType( builder );
  23071. }
  23072. call( builder ) {
  23073. const { shaderNode, inputNodes } = this;
  23074. if ( shaderNode.layout ) {
  23075. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  23076. if ( functionNodesCacheMap === undefined ) {
  23077. functionNodesCacheMap = new WeakMap();
  23078. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  23079. }
  23080. let functionNode = functionNodesCacheMap.get( shaderNode );
  23081. if ( functionNode === undefined ) {
  23082. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  23083. functionNodesCacheMap.set( shaderNode, functionNode );
  23084. }
  23085. if ( builder.currentFunctionNode !== null ) {
  23086. builder.currentFunctionNode.includes.push( functionNode );
  23087. }
  23088. return nodeObject( functionNode.call( inputNodes ) );
  23089. }
  23090. const jsFunc = shaderNode.jsFunc;
  23091. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder.stack, builder ) : jsFunc( builder.stack, builder );
  23092. return nodeObject( outputNode );
  23093. }
  23094. setup( builder ) {
  23095. const { outputNode } = builder.getNodeProperties( this );
  23096. return outputNode || this.setupOutput( builder );
  23097. }
  23098. setupOutput( builder ) {
  23099. builder.addStack();
  23100. builder.stack.outputNode = this.call( builder );
  23101. return builder.removeStack();
  23102. }
  23103. generate( builder, output ) {
  23104. const { outputNode } = builder.getNodeProperties( this );
  23105. if ( outputNode === null ) {
  23106. // TSL: It's recommended to use `tslFn` in setup() pass.
  23107. return this.call( builder ).build( builder, output );
  23108. }
  23109. return super.generate( builder, output );
  23110. }
  23111. }
  23112. class ShaderNodeInternal extends Node {
  23113. constructor( jsFunc ) {
  23114. super();
  23115. this.jsFunc = jsFunc;
  23116. this.layout = null;
  23117. this.global = true;
  23118. }
  23119. get isArrayInput() {
  23120. return /^\((\s+)?\[/.test( this.jsFunc.toString() );
  23121. }
  23122. setLayout( layout ) {
  23123. this.layout = layout;
  23124. return this;
  23125. }
  23126. call( inputs = null ) {
  23127. nodeObjects( inputs );
  23128. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  23129. }
  23130. setup() {
  23131. return this.call();
  23132. }
  23133. }
  23134. const bools = [ false, true ];
  23135. const uints = [ 0, 1, 2, 3 ];
  23136. const ints = [ - 1, - 2 ];
  23137. 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 ];
  23138. const boolsCacheMap = new Map();
  23139. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  23140. const uintsCacheMap = new Map();
  23141. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  23142. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  23143. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  23144. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  23145. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  23146. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  23147. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  23148. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  23149. const getConstNode = ( value, type ) => {
  23150. if ( constNodesCacheMap.has( value ) ) {
  23151. return constNodesCacheMap.get( value );
  23152. } else if ( value.isNode === true ) {
  23153. return value;
  23154. } else {
  23155. return new ConstNode( value, type );
  23156. }
  23157. };
  23158. const safeGetNodeType = ( node ) => {
  23159. try {
  23160. return node.getNodeType();
  23161. } catch ( _ ) {
  23162. return undefined;
  23163. }
  23164. };
  23165. const ConvertType = function ( type, cacheMap = null ) {
  23166. return ( ...params ) => {
  23167. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  23168. params = [ getValueFromType( type, ...params ) ];
  23169. }
  23170. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  23171. return nodeObject( cacheMap.get( params[ 0 ] ) );
  23172. }
  23173. if ( params.length === 1 ) {
  23174. const node = getConstNode( params[ 0 ], type );
  23175. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  23176. return nodeObject( new ConvertNode( node, type ) );
  23177. }
  23178. const nodes = params.map( param => getConstNode( param ) );
  23179. return nodeObject( new JoinNode( nodes, type ) );
  23180. };
  23181. };
  23182. // exports
  23183. const defined = ( value ) => value && value.value;
  23184. // utils
  23185. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  23186. // shader node base
  23187. function ShaderNode( jsFunc ) {
  23188. return new Proxy( new ShaderNodeInternal( jsFunc ), shaderNodeHandler );
  23189. }
  23190. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  23191. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  23192. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  23193. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  23194. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  23195. const tslFn = ( jsFunc ) => {
  23196. const shaderNode = new ShaderNode( jsFunc );
  23197. const fn = ( ...params ) => {
  23198. let inputs;
  23199. nodeObjects( params );
  23200. if ( params[ 0 ] && params[ 0 ].isNode ) {
  23201. inputs = [ ...params ];
  23202. } else {
  23203. inputs = params[ 0 ];
  23204. }
  23205. return shaderNode.call( inputs );
  23206. };
  23207. fn.shaderNode = shaderNode;
  23208. fn.setLayout = ( layout ) => {
  23209. shaderNode.setLayout( layout );
  23210. return fn;
  23211. };
  23212. return fn;
  23213. };
  23214. addNodeClass( 'ShaderNode', ShaderNode );
  23215. //
  23216. addNodeElement( 'toGlobal', ( node ) => {
  23217. node.global = true;
  23218. return node;
  23219. } );
  23220. //
  23221. const setCurrentStack = ( stack ) => {
  23222. currentStack = stack;
  23223. };
  23224. const getCurrentStack = () => currentStack;
  23225. const If = ( ...params ) => currentStack.if( ...params );
  23226. function append( node ) {
  23227. if ( currentStack ) currentStack.add( node );
  23228. return node;
  23229. }
  23230. addNodeElement( 'append', append );
  23231. // types
  23232. // @TODO: Maybe export from ConstNode.js?
  23233. const color = new ConvertType( 'color' );
  23234. const float = new ConvertType( 'float', cacheMaps.float );
  23235. const int = new ConvertType( 'int', cacheMaps.ints );
  23236. const uint = new ConvertType( 'uint', cacheMaps.uint );
  23237. const bool = new ConvertType( 'bool', cacheMaps.bool );
  23238. const vec2 = new ConvertType( 'vec2' );
  23239. const ivec2 = new ConvertType( 'ivec2' );
  23240. const uvec2 = new ConvertType( 'uvec2' );
  23241. const bvec2 = new ConvertType( 'bvec2' );
  23242. const vec3 = new ConvertType( 'vec3' );
  23243. const ivec3 = new ConvertType( 'ivec3' );
  23244. const uvec3 = new ConvertType( 'uvec3' );
  23245. const bvec3 = new ConvertType( 'bvec3' );
  23246. const vec4 = new ConvertType( 'vec4' );
  23247. const ivec4 = new ConvertType( 'ivec4' );
  23248. const uvec4 = new ConvertType( 'uvec4' );
  23249. const bvec4 = new ConvertType( 'bvec4' );
  23250. const mat2 = new ConvertType( 'mat2' );
  23251. const imat2 = new ConvertType( 'imat2' );
  23252. const umat2 = new ConvertType( 'umat2' );
  23253. const bmat2 = new ConvertType( 'bmat2' );
  23254. const mat3 = new ConvertType( 'mat3' );
  23255. const imat3 = new ConvertType( 'imat3' );
  23256. const umat3 = new ConvertType( 'umat3' );
  23257. const bmat3 = new ConvertType( 'bmat3' );
  23258. const mat4 = new ConvertType( 'mat4' );
  23259. const imat4 = new ConvertType( 'imat4' );
  23260. const umat4 = new ConvertType( 'umat4' );
  23261. const bmat4 = new ConvertType( 'bmat4' );
  23262. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  23263. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  23264. addNodeElement( 'toColor', color );
  23265. addNodeElement( 'toFloat', float );
  23266. addNodeElement( 'toInt', int );
  23267. addNodeElement( 'toUint', uint );
  23268. addNodeElement( 'toBool', bool );
  23269. addNodeElement( 'toVec2', vec2 );
  23270. addNodeElement( 'toIvec2', ivec2 );
  23271. addNodeElement( 'toUvec2', uvec2 );
  23272. addNodeElement( 'toBvec2', bvec2 );
  23273. addNodeElement( 'toVec3', vec3 );
  23274. addNodeElement( 'toIvec3', ivec3 );
  23275. addNodeElement( 'toUvec3', uvec3 );
  23276. addNodeElement( 'toBvec3', bvec3 );
  23277. addNodeElement( 'toVec4', vec4 );
  23278. addNodeElement( 'toIvec4', ivec4 );
  23279. addNodeElement( 'toUvec4', uvec4 );
  23280. addNodeElement( 'toBvec4', bvec4 );
  23281. addNodeElement( 'toMat2', mat2 );
  23282. addNodeElement( 'toImat2', imat2 );
  23283. addNodeElement( 'toUmat2', umat2 );
  23284. addNodeElement( 'toBmat2', bmat2 );
  23285. addNodeElement( 'toMat3', mat3 );
  23286. addNodeElement( 'toImat3', imat3 );
  23287. addNodeElement( 'toUmat3', umat3 );
  23288. addNodeElement( 'toBmat3', bmat3 );
  23289. addNodeElement( 'toMat4', mat4 );
  23290. addNodeElement( 'toImat4', imat4 );
  23291. addNodeElement( 'toUmat4', umat4 );
  23292. addNodeElement( 'toBmat4', bmat4 );
  23293. // basic nodes
  23294. // HACK - we cannot export them from the corresponding files because of the cyclic dependency
  23295. const element = nodeProxy( ArrayElementNode );
  23296. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  23297. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  23298. addNodeElement( 'element', element );
  23299. addNodeElement( 'convert', convert );
  23300. class AssignNode extends TempNode {
  23301. constructor( targetNode, sourceNode ) {
  23302. super();
  23303. this.targetNode = targetNode;
  23304. this.sourceNode = sourceNode;
  23305. }
  23306. hasDependencies() {
  23307. return false;
  23308. }
  23309. getNodeType( builder, output ) {
  23310. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23311. }
  23312. needsSplitAssign( builder ) {
  23313. const { targetNode } = this;
  23314. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23315. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23316. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23317. return assignDiferentVector;
  23318. }
  23319. return false;
  23320. }
  23321. generate( builder, output ) {
  23322. const { targetNode, sourceNode } = this;
  23323. const needsSplitAssign = this.needsSplitAssign( builder );
  23324. const targetType = targetNode.getNodeType( builder );
  23325. const target = targetNode.context( { assign: true } ).build( builder );
  23326. const source = sourceNode.build( builder, targetType );
  23327. const sourceType = sourceNode.getNodeType( builder );
  23328. const nodeData = builder.getDataFromNode( this );
  23329. //
  23330. let snippet;
  23331. if ( nodeData.initialized === true ) {
  23332. if ( output !== 'void' ) {
  23333. snippet = target;
  23334. }
  23335. } else if ( needsSplitAssign ) {
  23336. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23337. const sourceProperty = builder.getPropertyName( sourceVar );
  23338. builder.addLineFlowCode( `${ sourceProperty } = ${ source }` );
  23339. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23340. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23341. const component = targetNode.components[ i ];
  23342. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` );
  23343. }
  23344. if ( output !== 'void' ) {
  23345. snippet = target;
  23346. }
  23347. } else {
  23348. snippet = `${ target } = ${ source }`;
  23349. if ( output === 'void' || sourceType === 'void' ) {
  23350. builder.addLineFlowCode( snippet );
  23351. if ( output !== 'void' ) {
  23352. snippet = target;
  23353. }
  23354. }
  23355. }
  23356. nodeData.initialized = true;
  23357. return builder.format( snippet, targetType, output );
  23358. }
  23359. }
  23360. const assign = nodeProxy( AssignNode );
  23361. addNodeClass( 'AssignNode', AssignNode );
  23362. addNodeElement( 'assign', assign );
  23363. class VaryingNode extends Node {
  23364. constructor( node, name = null ) {
  23365. super();
  23366. this.node = node;
  23367. this.name = name;
  23368. this.isVaryingNode = true;
  23369. }
  23370. isGlobal() {
  23371. return true;
  23372. }
  23373. getHash( builder ) {
  23374. return this.name || super.getHash( builder );
  23375. }
  23376. getNodeType( builder ) {
  23377. // VaryingNode is auto type
  23378. return this.node.getNodeType( builder );
  23379. }
  23380. setupVarying( builder ) {
  23381. const properties = builder.getNodeProperties( this );
  23382. let varying = properties.varying;
  23383. if ( varying === undefined ) {
  23384. const name = this.name;
  23385. const type = this.getNodeType( builder );
  23386. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23387. properties.node = this.node;
  23388. }
  23389. // this property can be used to check if the varying can be optimized for a variable
  23390. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23391. return varying;
  23392. }
  23393. setup( builder ) {
  23394. this.setupVarying( builder );
  23395. }
  23396. analyze( builder ) {
  23397. this.setupVarying( builder );
  23398. return this.node.analyze( builder );
  23399. }
  23400. generate( builder ) {
  23401. const properties = builder.getNodeProperties( this );
  23402. const varying = this.setupVarying( builder );
  23403. if ( properties.propertyName === undefined ) {
  23404. const type = this.getNodeType( builder );
  23405. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23406. // force node run in vertex stage
  23407. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23408. properties.propertyName = propertyName;
  23409. }
  23410. return builder.getPropertyName( varying );
  23411. }
  23412. }
  23413. const varying = nodeProxy( VaryingNode );
  23414. addNodeElement( 'varying', varying );
  23415. addNodeClass( 'VaryingNode', VaryingNode );
  23416. class AttributeNode extends Node {
  23417. constructor( attributeName, nodeType = null, defaultNode = null ) {
  23418. super( nodeType );
  23419. this.defaultNode = defaultNode;
  23420. this.global = true;
  23421. this._attributeName = attributeName;
  23422. }
  23423. getHash( builder ) {
  23424. return this.getAttributeName( builder );
  23425. }
  23426. getNodeType( builder ) {
  23427. let nodeType = super.getNodeType( builder );
  23428. if ( nodeType === null ) {
  23429. const attributeName = this.getAttributeName( builder );
  23430. if ( builder.hasGeometryAttribute( attributeName ) ) {
  23431. const attribute = builder.geometry.getAttribute( attributeName );
  23432. nodeType = builder.getTypeFromAttribute( attribute );
  23433. } else {
  23434. nodeType = 'float';
  23435. }
  23436. }
  23437. return nodeType;
  23438. }
  23439. setAttributeName( attributeName ) {
  23440. this._attributeName = attributeName;
  23441. return this;
  23442. }
  23443. getAttributeName( /*builder*/ ) {
  23444. return this._attributeName;
  23445. }
  23446. generate( builder ) {
  23447. const attributeName = this.getAttributeName( builder );
  23448. const nodeType = this.getNodeType( builder );
  23449. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  23450. if ( geometryAttribute === true ) {
  23451. const attribute = builder.geometry.getAttribute( attributeName );
  23452. const attributeType = builder.getTypeFromAttribute( attribute );
  23453. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  23454. if ( builder.shaderStage === 'vertex' ) {
  23455. return builder.format( nodeAttribute.name, attributeType, nodeType );
  23456. } else {
  23457. const nodeVarying = varying( this );
  23458. return nodeVarying.build( builder, nodeType );
  23459. }
  23460. } else {
  23461. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  23462. const { defaultNode } = this;
  23463. if ( defaultNode !== null ) {
  23464. return defaultNode.build( builder, nodeType );
  23465. } else {
  23466. return builder.generateConst( nodeType );
  23467. }
  23468. }
  23469. }
  23470. }
  23471. const attribute = ( name, nodeType, defaultNode ) => nodeObject( new AttributeNode( name, nodeType, nodeObject( defaultNode ) ) );
  23472. addNodeClass( 'AttributeNode', AttributeNode );
  23473. class BypassNode extends Node {
  23474. constructor( returnNode, callNode ) {
  23475. super();
  23476. this.isBypassNode = true;
  23477. this.outputNode = returnNode;
  23478. this.callNode = callNode;
  23479. }
  23480. getNodeType( builder ) {
  23481. return this.outputNode.getNodeType( builder );
  23482. }
  23483. generate( builder ) {
  23484. const snippet = this.callNode.build( builder, 'void' );
  23485. if ( snippet !== '' ) {
  23486. builder.addLineFlowCode( snippet );
  23487. }
  23488. return this.outputNode.build( builder );
  23489. }
  23490. }
  23491. const bypass = nodeProxy( BypassNode );
  23492. addNodeElement( 'bypass', bypass );
  23493. addNodeClass( 'BypassNode', BypassNode );
  23494. class CacheNode extends Node {
  23495. constructor( node, parent = true ) {
  23496. super();
  23497. this.node = node;
  23498. this.parent = parent;
  23499. this.isCacheNode = true;
  23500. }
  23501. getNodeType( builder ) {
  23502. return this.node.getNodeType( builder );
  23503. }
  23504. build( builder, ...params ) {
  23505. const previousCache = builder.getCache();
  23506. const cache = builder.getCacheFromNode( this, parent );
  23507. builder.setCache( cache );
  23508. const data = this.node.build( builder, ...params );
  23509. builder.setCache( previousCache );
  23510. return data;
  23511. }
  23512. }
  23513. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23514. addNodeElement( 'cache', cache );
  23515. addNodeClass( 'CacheNode', CacheNode );
  23516. class ContextNode extends Node {
  23517. constructor( node, context = {} ) {
  23518. super();
  23519. this.isContextNode = true;
  23520. this.node = node;
  23521. this.context = context;
  23522. }
  23523. getNodeType( builder ) {
  23524. return this.node.getNodeType( builder );
  23525. }
  23526. analyze( builder ) {
  23527. this.node.build( builder );
  23528. }
  23529. setup( builder ) {
  23530. const previousContext = builder.getContext();
  23531. builder.setContext( { ...builder.context, ...this.context } );
  23532. const node = this.node.build( builder );
  23533. builder.setContext( previousContext );
  23534. return node;
  23535. }
  23536. generate( builder, output ) {
  23537. const previousContext = builder.getContext();
  23538. builder.setContext( { ...builder.context, ...this.context } );
  23539. const snippet = this.node.build( builder, output );
  23540. builder.setContext( previousContext );
  23541. return snippet;
  23542. }
  23543. }
  23544. const context = nodeProxy( ContextNode );
  23545. const label = ( node, name ) => context( node, { label: name } );
  23546. addNodeElement( 'context', context );
  23547. addNodeElement( 'label', label );
  23548. addNodeClass( 'ContextNode', ContextNode );
  23549. class IndexNode extends Node {
  23550. constructor( scope ) {
  23551. super( 'uint' );
  23552. this.scope = scope;
  23553. this.isInstanceIndexNode = true;
  23554. }
  23555. generate( builder ) {
  23556. const nodeType = this.getNodeType( builder );
  23557. const scope = this.scope;
  23558. let propertyName;
  23559. if ( scope === IndexNode.VERTEX ) {
  23560. propertyName = builder.getVertexIndex();
  23561. } else if ( scope === IndexNode.INSTANCE ) {
  23562. propertyName = builder.getInstanceIndex();
  23563. } else if ( scope === IndexNode.DRAW ) {
  23564. propertyName = builder.getDrawIndex();
  23565. } else {
  23566. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  23567. }
  23568. let output;
  23569. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23570. output = propertyName;
  23571. } else {
  23572. const nodeVarying = varying( this );
  23573. output = nodeVarying.build( builder, nodeType );
  23574. }
  23575. return output;
  23576. }
  23577. }
  23578. IndexNode.VERTEX = 'vertex';
  23579. IndexNode.INSTANCE = 'instance';
  23580. IndexNode.DRAW = 'draw';
  23581. const vertexIndex = nodeImmutable( IndexNode, IndexNode.VERTEX );
  23582. const instanceIndex = nodeImmutable( IndexNode, IndexNode.INSTANCE );
  23583. const drawIndex = nodeImmutable( IndexNode, IndexNode.DRAW );
  23584. addNodeClass( 'IndexNode', IndexNode );
  23585. class LightingModel {
  23586. start( /*input, stack, builder*/ ) { }
  23587. finish( /*input, stack, builder*/ ) { }
  23588. direct( /*input, stack, builder*/ ) { }
  23589. directRectArea( /*input, stack, builder*/ ) {}
  23590. indirect( /*input, stack, builder*/ ) { }
  23591. ambientOcclusion( /*input, stack, builder*/ ) { }
  23592. }
  23593. class VarNode extends Node {
  23594. constructor( node, name = null ) {
  23595. super();
  23596. this.node = node;
  23597. this.name = name;
  23598. this.global = true;
  23599. this.isVarNode = true;
  23600. }
  23601. getHash( builder ) {
  23602. return this.name || super.getHash( builder );
  23603. }
  23604. getNodeType( builder ) {
  23605. return this.node.getNodeType( builder );
  23606. }
  23607. generate( builder ) {
  23608. const { node, name } = this;
  23609. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23610. const propertyName = builder.getPropertyName( nodeVar );
  23611. const snippet = node.build( builder, nodeVar.type );
  23612. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  23613. return propertyName;
  23614. }
  23615. }
  23616. const temp = nodeProxy( VarNode );
  23617. addNodeElement( 'temp', temp ); // @TODO: Will be removed in the future
  23618. addNodeElement( 'toVar', ( ...params ) => temp( ...params ).append() );
  23619. addNodeClass( 'VarNode', VarNode );
  23620. class NodeAttribute {
  23621. constructor( name, type, node = null ) {
  23622. this.isNodeAttribute = true;
  23623. this.name = name;
  23624. this.type = type;
  23625. this.node = node;
  23626. }
  23627. }
  23628. class NodeUniform {
  23629. constructor( name, type, node ) {
  23630. this.isNodeUniform = true;
  23631. this.name = name;
  23632. this.type = type;
  23633. this.node = node.getSelf();
  23634. }
  23635. get value() {
  23636. return this.node.value;
  23637. }
  23638. set value( val ) {
  23639. this.node.value = val;
  23640. }
  23641. get id() {
  23642. return this.node.id;
  23643. }
  23644. get groupNode() {
  23645. return this.node.groupNode;
  23646. }
  23647. }
  23648. class NodeVar {
  23649. constructor( name, type ) {
  23650. this.isNodeVar = true;
  23651. this.name = name;
  23652. this.type = type;
  23653. }
  23654. }
  23655. class NodeVarying extends NodeVar {
  23656. constructor( name, type ) {
  23657. super( name, type );
  23658. this.needsInterpolation = false;
  23659. this.isNodeVarying = true;
  23660. }
  23661. }
  23662. class NodeCode {
  23663. constructor( name, type, code = '' ) {
  23664. this.name = name;
  23665. this.type = type;
  23666. this.code = code;
  23667. Object.defineProperty( this, 'isNodeCode', { value: true } );
  23668. }
  23669. }
  23670. class NodeKeywords {
  23671. constructor() {
  23672. this.keywords = [];
  23673. this.nodes = {};
  23674. this.keywordsCallback = {};
  23675. }
  23676. getNode( name ) {
  23677. let node = this.nodes[ name ];
  23678. if ( node === undefined && this.keywordsCallback[ name ] !== undefined ) {
  23679. node = this.keywordsCallback[ name ]( name );
  23680. this.nodes[ name ] = node;
  23681. }
  23682. return node;
  23683. }
  23684. addKeyword( name, callback ) {
  23685. this.keywords.push( name );
  23686. this.keywordsCallback[ name ] = callback;
  23687. return this;
  23688. }
  23689. parse( code ) {
  23690. const keywordNames = this.keywords;
  23691. const regExp = new RegExp( `\\b${keywordNames.join( '\\b|\\b' )}\\b`, 'g' );
  23692. const codeKeywords = code.match( regExp );
  23693. const keywordNodes = [];
  23694. if ( codeKeywords !== null ) {
  23695. for ( const keyword of codeKeywords ) {
  23696. const node = this.getNode( keyword );
  23697. if ( node !== undefined && keywordNodes.indexOf( node ) === - 1 ) {
  23698. keywordNodes.push( node );
  23699. }
  23700. }
  23701. }
  23702. return keywordNodes;
  23703. }
  23704. include( builder, code ) {
  23705. const keywordNodes = this.parse( code );
  23706. for ( const keywordNode of keywordNodes ) {
  23707. keywordNode.build( builder );
  23708. }
  23709. }
  23710. }
  23711. let id$3 = 0;
  23712. class NodeCache {
  23713. constructor( parent = null ) {
  23714. this.id = id$3 ++;
  23715. this.nodesData = new WeakMap();
  23716. this.parent = parent;
  23717. }
  23718. getData( node ) {
  23719. let data = this.nodesData.get( node );
  23720. if ( data === undefined && this.parent !== null ) {
  23721. data = this.parent.getData( node );
  23722. }
  23723. return data;
  23724. }
  23725. setData( node, data ) {
  23726. this.nodesData.set( node, data );
  23727. }
  23728. }
  23729. class PropertyNode extends Node {
  23730. constructor( nodeType, name = null, varying = false ) {
  23731. super( nodeType );
  23732. this.name = name;
  23733. this.varying = varying;
  23734. this.isPropertyNode = true;
  23735. }
  23736. getHash( builder ) {
  23737. return this.name || super.getHash( builder );
  23738. }
  23739. isGlobal( /*builder*/ ) {
  23740. return true;
  23741. }
  23742. generate( builder ) {
  23743. let nodeVar;
  23744. if ( this.varying === true ) {
  23745. nodeVar = builder.getVaryingFromNode( this, this.name );
  23746. nodeVar.needsInterpolation = true;
  23747. } else {
  23748. nodeVar = builder.getVarFromNode( this, this.name );
  23749. }
  23750. return builder.getPropertyName( nodeVar );
  23751. }
  23752. }
  23753. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23754. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23755. const diffuseColor = nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23756. const emissive = nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  23757. const roughness = nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23758. const metalness = nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23759. const clearcoat = nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23760. const clearcoatRoughness = nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23761. const sheen = nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23762. const sheenRoughness = nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23763. const iridescence = nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23764. const iridescenceIOR = nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23765. const iridescenceThickness = nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23766. const alphaT = nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23767. const anisotropy = nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23768. const anisotropyT = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23769. const anisotropyB = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23770. const specularColor = nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23771. const specularF90 = nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23772. const shininess = nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23773. const output = nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23774. const dashSize = nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23775. const gapSize = nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23776. const pointWidth = nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23777. const ior = nodeImmutable( PropertyNode, 'float', 'IOR' );
  23778. const transmission = nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23779. const thickness = nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23780. const attenuationDistance = nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23781. const attenuationColor = nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23782. const dispersion = nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23783. addNodeClass( 'PropertyNode', PropertyNode );
  23784. class ParameterNode extends PropertyNode {
  23785. constructor( nodeType, name = null ) {
  23786. super( nodeType, name );
  23787. this.isParameterNode = true;
  23788. }
  23789. getHash() {
  23790. return this.uuid;
  23791. }
  23792. generate() {
  23793. return this.name;
  23794. }
  23795. }
  23796. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23797. addNodeClass( 'ParameterNode', ParameterNode );
  23798. class CodeNode extends Node {
  23799. constructor( code = '', includes = [], language = '' ) {
  23800. super( 'code' );
  23801. this.isCodeNode = true;
  23802. this.code = code;
  23803. this.language = language;
  23804. this.includes = includes;
  23805. }
  23806. isGlobal() {
  23807. return true;
  23808. }
  23809. setIncludes( includes ) {
  23810. this.includes = includes;
  23811. return this;
  23812. }
  23813. getIncludes( /*builder*/ ) {
  23814. return this.includes;
  23815. }
  23816. generate( builder ) {
  23817. const includes = this.getIncludes( builder );
  23818. for ( const include of includes ) {
  23819. include.build( builder );
  23820. }
  23821. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23822. nodeCode.code = this.code;
  23823. return nodeCode.code;
  23824. }
  23825. serialize( data ) {
  23826. super.serialize( data );
  23827. data.code = this.code;
  23828. data.language = this.language;
  23829. }
  23830. deserialize( data ) {
  23831. super.deserialize( data );
  23832. this.code = data.code;
  23833. this.language = data.language;
  23834. }
  23835. }
  23836. const code = nodeProxy( CodeNode );
  23837. const js = ( src, includes ) => code( src, includes, 'js' );
  23838. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23839. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23840. addNodeClass( 'CodeNode', CodeNode );
  23841. class FunctionNode extends CodeNode {
  23842. constructor( code = '', includes = [], language = '' ) {
  23843. super( code, includes, language );
  23844. this.keywords = {};
  23845. }
  23846. getNodeType( builder ) {
  23847. return this.getNodeFunction( builder ).type;
  23848. }
  23849. getInputs( builder ) {
  23850. return this.getNodeFunction( builder ).inputs;
  23851. }
  23852. getNodeFunction( builder ) {
  23853. const nodeData = builder.getDataFromNode( this );
  23854. let nodeFunction = nodeData.nodeFunction;
  23855. if ( nodeFunction === undefined ) {
  23856. nodeFunction = builder.parser.parseFunction( this.code );
  23857. nodeData.nodeFunction = nodeFunction;
  23858. }
  23859. return nodeFunction;
  23860. }
  23861. generate( builder, output ) {
  23862. super.generate( builder );
  23863. const nodeFunction = this.getNodeFunction( builder );
  23864. const name = nodeFunction.name;
  23865. const type = nodeFunction.type;
  23866. const nodeCode = builder.getCodeFromNode( this, type );
  23867. if ( name !== '' ) {
  23868. // use a custom property name
  23869. nodeCode.name = name;
  23870. }
  23871. const propertyName = builder.getPropertyName( nodeCode );
  23872. let code = this.getNodeFunction( builder ).getCode( propertyName );
  23873. const keywords = this.keywords;
  23874. const keywordsProperties = Object.keys( keywords );
  23875. if ( keywordsProperties.length > 0 ) {
  23876. for ( const property of keywordsProperties ) {
  23877. const propertyRegExp = new RegExp( `\\b${property}\\b`, 'g' );
  23878. const nodeProperty = keywords[ property ].build( builder, 'property' );
  23879. code = code.replace( propertyRegExp, nodeProperty );
  23880. }
  23881. }
  23882. nodeCode.code = code + '\n';
  23883. if ( output === 'property' ) {
  23884. return propertyName;
  23885. } else {
  23886. return builder.format( `${ propertyName }()`, type, output );
  23887. }
  23888. }
  23889. }
  23890. const nativeFn = ( code, includes = [], language = '' ) => {
  23891. for ( let i = 0; i < includes.length; i ++ ) {
  23892. const include = includes[ i ];
  23893. // TSL Function: glslFn, wgslFn
  23894. if ( typeof include === 'function' ) {
  23895. includes[ i ] = include.functionNode;
  23896. }
  23897. }
  23898. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23899. const fn = ( ...params ) => functionNode.call( ...params );
  23900. fn.functionNode = functionNode;
  23901. return fn;
  23902. };
  23903. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23904. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23905. addNodeClass( 'FunctionNode', FunctionNode );
  23906. class UniformGroupNode extends Node {
  23907. constructor( name, shared = false ) {
  23908. super( 'string' );
  23909. this.name = name;
  23910. this.version = 0;
  23911. this.shared = shared;
  23912. this.isUniformGroup = true;
  23913. }
  23914. set needsUpdate( value ) {
  23915. if ( value === true ) this.version ++;
  23916. }
  23917. }
  23918. const uniformGroup = ( name ) => new UniformGroupNode( name );
  23919. const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true );
  23920. const frameGroup = sharedUniformGroup( 'frame' );
  23921. const renderGroup = sharedUniformGroup( 'render' );
  23922. const objectGroup = uniformGroup( 'object' );
  23923. addNodeClass( 'UniformGroupNode', UniformGroupNode );
  23924. class UniformNode extends InputNode {
  23925. constructor( value, nodeType = null ) {
  23926. super( value, nodeType );
  23927. this.isUniformNode = true;
  23928. this.name = '';
  23929. this.groupNode = objectGroup;
  23930. }
  23931. label( name ) {
  23932. this.name = name;
  23933. return this;
  23934. }
  23935. setGroup( group ) {
  23936. this.groupNode = group;
  23937. return this;
  23938. }
  23939. getGroup() {
  23940. return this.groupNode;
  23941. }
  23942. getUniformHash( builder ) {
  23943. return this.getHash( builder );
  23944. }
  23945. onUpdate( callback, updateType ) {
  23946. const self = this.getSelf();
  23947. callback = callback.bind( self );
  23948. return super.onUpdate( ( frame ) => {
  23949. const value = callback( frame, self );
  23950. if ( value !== undefined ) {
  23951. this.value = value;
  23952. }
  23953. }, updateType );
  23954. }
  23955. generate( builder, output ) {
  23956. const type = this.getNodeType( builder );
  23957. const hash = this.getUniformHash( builder );
  23958. let sharedNode = builder.getNodeFromHash( hash );
  23959. if ( sharedNode === undefined ) {
  23960. builder.setHashNode( this, hash );
  23961. sharedNode = this;
  23962. }
  23963. const sharedNodeType = sharedNode.getInputType( builder );
  23964. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  23965. const propertyName = builder.getPropertyName( nodeUniform );
  23966. if ( builder.context.label !== undefined ) delete builder.context.label;
  23967. return builder.format( propertyName, type, output );
  23968. }
  23969. }
  23970. const uniform = ( arg1, arg2 ) => {
  23971. const nodeType = getConstNodeType( arg2 || arg1 );
  23972. // @TODO: get ConstNode from .traverse() in the future
  23973. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  23974. return nodeObject( new UniformNode( value, nodeType ) );
  23975. };
  23976. addNodeClass( 'UniformNode', UniformNode );
  23977. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  23978. class TextureSizeNode extends Node {
  23979. constructor( textureNode, levelNode = null ) {
  23980. super( 'uvec2' );
  23981. this.isTextureSizeNode = true;
  23982. this.textureNode = textureNode;
  23983. this.levelNode = levelNode;
  23984. }
  23985. generate( builder, output ) {
  23986. const textureProperty = this.textureNode.build( builder, 'property' );
  23987. const levelNode = this.levelNode.build( builder, 'int' );
  23988. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ levelNode } )`, this.getNodeType( builder ), output );
  23989. }
  23990. }
  23991. const textureSize = nodeProxy( TextureSizeNode );
  23992. addNodeElement( 'textureSize', textureSize );
  23993. addNodeClass( 'TextureSizeNode', TextureSizeNode );
  23994. class OperatorNode extends TempNode {
  23995. constructor( op, aNode, bNode, ...params ) {
  23996. super();
  23997. if ( params.length > 0 ) {
  23998. let finalOp = new OperatorNode( op, aNode, bNode );
  23999. for ( let i = 0; i < params.length - 1; i ++ ) {
  24000. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  24001. }
  24002. aNode = finalOp;
  24003. bNode = params[ params.length - 1 ];
  24004. }
  24005. this.op = op;
  24006. this.aNode = aNode;
  24007. this.bNode = bNode;
  24008. }
  24009. getNodeType( builder, output ) {
  24010. const op = this.op;
  24011. const aNode = this.aNode;
  24012. const bNode = this.bNode;
  24013. const typeA = aNode.getNodeType( builder );
  24014. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24015. if ( typeA === 'void' || typeB === 'void' ) {
  24016. return 'void';
  24017. } else if ( op === '%' ) {
  24018. return typeA;
  24019. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  24020. return builder.getIntegerType( typeA );
  24021. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  24022. return 'bool';
  24023. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  24024. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  24025. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  24026. } else {
  24027. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  24028. return typeB;
  24029. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24030. // matrix x vector
  24031. return builder.getVectorFromMatrix( typeA );
  24032. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24033. // vector x matrix
  24034. return builder.getVectorFromMatrix( typeB );
  24035. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  24036. // anytype x anytype: use the greater length vector
  24037. return typeB;
  24038. }
  24039. return typeA;
  24040. }
  24041. }
  24042. generate( builder, output ) {
  24043. const op = this.op;
  24044. const aNode = this.aNode;
  24045. const bNode = this.bNode;
  24046. const type = this.getNodeType( builder, output );
  24047. let typeA = null;
  24048. let typeB = null;
  24049. if ( type !== 'void' ) {
  24050. typeA = aNode.getNodeType( builder );
  24051. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24052. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  24053. if ( builder.isVector( typeA ) ) {
  24054. typeB = typeA;
  24055. } else {
  24056. typeA = typeB = 'float';
  24057. }
  24058. } else if ( op === '>>' || op === '<<' ) {
  24059. typeA = type;
  24060. typeB = builder.changeComponentType( typeB, 'uint' );
  24061. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24062. // matrix x vector
  24063. typeB = builder.getVectorFromMatrix( typeA );
  24064. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24065. // vector x matrix
  24066. typeA = builder.getVectorFromMatrix( typeB );
  24067. } else {
  24068. // anytype x anytype
  24069. typeA = typeB = type;
  24070. }
  24071. } else {
  24072. typeA = typeB = type;
  24073. }
  24074. const a = aNode.build( builder, typeA );
  24075. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  24076. const outputLength = builder.getTypeLength( output );
  24077. const fnOpSnippet = builder.getFunctionOperator( op );
  24078. if ( output !== 'void' ) {
  24079. if ( op === '<' && outputLength > 1 ) {
  24080. return builder.format( `${ builder.getMethod( 'lessThan' ) }( ${ a }, ${ b } )`, type, output );
  24081. } else if ( op === '<=' && outputLength > 1 ) {
  24082. return builder.format( `${ builder.getMethod( 'lessThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24083. } else if ( op === '>' && outputLength > 1 ) {
  24084. return builder.format( `${ builder.getMethod( 'greaterThan' ) }( ${ a }, ${ b } )`, type, output );
  24085. } else if ( op === '>=' && outputLength > 1 ) {
  24086. return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24087. } else if ( op === '!' || op === '~' ) {
  24088. return builder.format( `(${op}${a})`, typeA, output );
  24089. } else if ( fnOpSnippet ) {
  24090. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24091. } else {
  24092. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  24093. }
  24094. } else if ( typeA !== 'void' ) {
  24095. if ( fnOpSnippet ) {
  24096. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24097. } else {
  24098. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  24099. }
  24100. }
  24101. }
  24102. serialize( data ) {
  24103. super.serialize( data );
  24104. data.op = this.op;
  24105. }
  24106. deserialize( data ) {
  24107. super.deserialize( data );
  24108. this.op = data.op;
  24109. }
  24110. }
  24111. const add = nodeProxy( OperatorNode, '+' );
  24112. const sub = nodeProxy( OperatorNode, '-' );
  24113. const mul = nodeProxy( OperatorNode, '*' );
  24114. const div = nodeProxy( OperatorNode, '/' );
  24115. const remainder = nodeProxy( OperatorNode, '%' );
  24116. const equal = nodeProxy( OperatorNode, '==' );
  24117. const notEqual = nodeProxy( OperatorNode, '!=' );
  24118. const lessThan = nodeProxy( OperatorNode, '<' );
  24119. const greaterThan = nodeProxy( OperatorNode, '>' );
  24120. const lessThanEqual = nodeProxy( OperatorNode, '<=' );
  24121. const greaterThanEqual = nodeProxy( OperatorNode, '>=' );
  24122. const and = nodeProxy( OperatorNode, '&&' );
  24123. const or = nodeProxy( OperatorNode, '||' );
  24124. const not = nodeProxy( OperatorNode, '!' );
  24125. const xor = nodeProxy( OperatorNode, '^^' );
  24126. const bitAnd = nodeProxy( OperatorNode, '&' );
  24127. const bitNot = nodeProxy( OperatorNode, '~' );
  24128. const bitOr = nodeProxy( OperatorNode, '|' );
  24129. const bitXor = nodeProxy( OperatorNode, '^' );
  24130. const shiftLeft = nodeProxy( OperatorNode, '<<' );
  24131. const shiftRight = nodeProxy( OperatorNode, '>>' );
  24132. addNodeElement( 'add', add );
  24133. addNodeElement( 'sub', sub );
  24134. addNodeElement( 'mul', mul );
  24135. addNodeElement( 'div', div );
  24136. addNodeElement( 'remainder', remainder );
  24137. addNodeElement( 'equal', equal );
  24138. addNodeElement( 'notEqual', notEqual );
  24139. addNodeElement( 'lessThan', lessThan );
  24140. addNodeElement( 'greaterThan', greaterThan );
  24141. addNodeElement( 'lessThanEqual', lessThanEqual );
  24142. addNodeElement( 'greaterThanEqual', greaterThanEqual );
  24143. addNodeElement( 'and', and );
  24144. addNodeElement( 'or', or );
  24145. addNodeElement( 'not', not );
  24146. addNodeElement( 'xor', xor );
  24147. addNodeElement( 'bitAnd', bitAnd );
  24148. addNodeElement( 'bitNot', bitNot );
  24149. addNodeElement( 'bitOr', bitOr );
  24150. addNodeElement( 'bitXor', bitXor );
  24151. addNodeElement( 'shiftLeft', shiftLeft );
  24152. addNodeElement( 'shiftRight', shiftRight );
  24153. addNodeClass( 'OperatorNode', OperatorNode );
  24154. class MathNode extends TempNode {
  24155. constructor( method, aNode, bNode = null, cNode = null ) {
  24156. super();
  24157. this.method = method;
  24158. this.aNode = aNode;
  24159. this.bNode = bNode;
  24160. this.cNode = cNode;
  24161. }
  24162. getInputType( builder ) {
  24163. const aType = this.aNode.getNodeType( builder );
  24164. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  24165. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  24166. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  24167. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  24168. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  24169. if ( aLen > bLen && aLen > cLen ) {
  24170. return aType;
  24171. } else if ( bLen > cLen ) {
  24172. return bType;
  24173. } else if ( cLen > aLen ) {
  24174. return cType;
  24175. }
  24176. return aType;
  24177. }
  24178. getNodeType( builder ) {
  24179. const method = this.method;
  24180. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  24181. return 'float';
  24182. } else if ( method === MathNode.CROSS ) {
  24183. return 'vec3';
  24184. } else if ( method === MathNode.ALL ) {
  24185. return 'bool';
  24186. } else if ( method === MathNode.EQUALS ) {
  24187. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  24188. } else if ( method === MathNode.MOD ) {
  24189. return this.aNode.getNodeType( builder );
  24190. } else {
  24191. return this.getInputType( builder );
  24192. }
  24193. }
  24194. generate( builder, output ) {
  24195. const method = this.method;
  24196. const type = this.getNodeType( builder );
  24197. const inputType = this.getInputType( builder );
  24198. const a = this.aNode;
  24199. const b = this.bNode;
  24200. const c = this.cNode;
  24201. const isWebGL = builder.renderer.isWebGLRenderer === true;
  24202. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  24203. // dir can be either a direction vector or a normal vector
  24204. // upper-left 3x3 of matrix is assumed to be orthogonal
  24205. let tA = a;
  24206. let tB = b;
  24207. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  24208. tB = vec4( vec3( tB ), 0.0 );
  24209. } else {
  24210. tA = vec4( vec3( tA ), 0.0 );
  24211. }
  24212. const mulNode = mul( tA, tB ).xyz;
  24213. return normalize( mulNode ).build( builder, output );
  24214. } else if ( method === MathNode.NEGATE ) {
  24215. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  24216. } else if ( method === MathNode.ONE_MINUS ) {
  24217. return sub( 1.0, a ).build( builder, output );
  24218. } else if ( method === MathNode.RECIPROCAL ) {
  24219. return div( 1.0, a ).build( builder, output );
  24220. } else if ( method === MathNode.DIFFERENCE ) {
  24221. return abs( sub( a, b ) ).build( builder, output );
  24222. } else {
  24223. const params = [];
  24224. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  24225. params.push(
  24226. a.build( builder, type ),
  24227. b.build( builder, type )
  24228. );
  24229. } else if ( method === MathNode.STEP ) {
  24230. params.push(
  24231. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  24232. b.build( builder, inputType )
  24233. );
  24234. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  24235. params.push(
  24236. a.build( builder, inputType ),
  24237. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24238. );
  24239. } else if ( method === MathNode.REFRACT ) {
  24240. params.push(
  24241. a.build( builder, inputType ),
  24242. b.build( builder, inputType ),
  24243. c.build( builder, 'float' )
  24244. );
  24245. } else if ( method === MathNode.MIX ) {
  24246. params.push(
  24247. a.build( builder, inputType ),
  24248. b.build( builder, inputType ),
  24249. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24250. );
  24251. } else {
  24252. params.push( a.build( builder, inputType ) );
  24253. if ( b !== null ) params.push( b.build( builder, inputType ) );
  24254. if ( c !== null ) params.push( c.build( builder, inputType ) );
  24255. }
  24256. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  24257. }
  24258. }
  24259. serialize( data ) {
  24260. super.serialize( data );
  24261. data.method = this.method;
  24262. }
  24263. deserialize( data ) {
  24264. super.deserialize( data );
  24265. this.method = data.method;
  24266. }
  24267. }
  24268. // 1 input
  24269. MathNode.ALL = 'all';
  24270. MathNode.ANY = 'any';
  24271. MathNode.EQUALS = 'equals';
  24272. MathNode.RADIANS = 'radians';
  24273. MathNode.DEGREES = 'degrees';
  24274. MathNode.EXP = 'exp';
  24275. MathNode.EXP2 = 'exp2';
  24276. MathNode.LOG = 'log';
  24277. MathNode.LOG2 = 'log2';
  24278. MathNode.SQRT = 'sqrt';
  24279. MathNode.INVERSE_SQRT = 'inversesqrt';
  24280. MathNode.FLOOR = 'floor';
  24281. MathNode.CEIL = 'ceil';
  24282. MathNode.NORMALIZE = 'normalize';
  24283. MathNode.FRACT = 'fract';
  24284. MathNode.SIN = 'sin';
  24285. MathNode.COS = 'cos';
  24286. MathNode.TAN = 'tan';
  24287. MathNode.ASIN = 'asin';
  24288. MathNode.ACOS = 'acos';
  24289. MathNode.ATAN = 'atan';
  24290. MathNode.ABS = 'abs';
  24291. MathNode.SIGN = 'sign';
  24292. MathNode.LENGTH = 'length';
  24293. MathNode.NEGATE = 'negate';
  24294. MathNode.ONE_MINUS = 'oneMinus';
  24295. MathNode.DFDX = 'dFdx';
  24296. MathNode.DFDY = 'dFdy';
  24297. MathNode.ROUND = 'round';
  24298. MathNode.RECIPROCAL = 'reciprocal';
  24299. MathNode.TRUNC = 'trunc';
  24300. MathNode.FWIDTH = 'fwidth';
  24301. MathNode.BITCAST = 'bitcast';
  24302. MathNode.TRANSPOSE = 'transpose';
  24303. // 2 inputs
  24304. MathNode.ATAN2 = 'atan2';
  24305. MathNode.MIN = 'min';
  24306. MathNode.MAX = 'max';
  24307. MathNode.MOD = 'mod';
  24308. MathNode.STEP = 'step';
  24309. MathNode.REFLECT = 'reflect';
  24310. MathNode.DISTANCE = 'distance';
  24311. MathNode.DIFFERENCE = 'difference';
  24312. MathNode.DOT = 'dot';
  24313. MathNode.CROSS = 'cross';
  24314. MathNode.POW = 'pow';
  24315. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  24316. // 3 inputs
  24317. MathNode.MIX = 'mix';
  24318. MathNode.CLAMP = 'clamp';
  24319. MathNode.REFRACT = 'refract';
  24320. MathNode.SMOOTHSTEP = 'smoothstep';
  24321. MathNode.FACEFORWARD = 'faceforward';
  24322. const EPSILON = float( 1e-6 );
  24323. const INFINITY = float( 1e6 );
  24324. const PI = float( Math.PI );
  24325. const PI2 = float( Math.PI * 2 );
  24326. const all = nodeProxy( MathNode, MathNode.ALL );
  24327. const any = nodeProxy( MathNode, MathNode.ANY );
  24328. const equals = nodeProxy( MathNode, MathNode.EQUALS );
  24329. const radians = nodeProxy( MathNode, MathNode.RADIANS );
  24330. const degrees = nodeProxy( MathNode, MathNode.DEGREES );
  24331. const exp = nodeProxy( MathNode, MathNode.EXP );
  24332. const exp2 = nodeProxy( MathNode, MathNode.EXP2 );
  24333. const log = nodeProxy( MathNode, MathNode.LOG );
  24334. const log2 = nodeProxy( MathNode, MathNode.LOG2 );
  24335. const sqrt = nodeProxy( MathNode, MathNode.SQRT );
  24336. const inverseSqrt = nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  24337. const floor = nodeProxy( MathNode, MathNode.FLOOR );
  24338. const ceil = nodeProxy( MathNode, MathNode.CEIL );
  24339. const normalize = nodeProxy( MathNode, MathNode.NORMALIZE );
  24340. const fract = nodeProxy( MathNode, MathNode.FRACT );
  24341. const sin = nodeProxy( MathNode, MathNode.SIN );
  24342. const cos = nodeProxy( MathNode, MathNode.COS );
  24343. const tan = nodeProxy( MathNode, MathNode.TAN );
  24344. const asin = nodeProxy( MathNode, MathNode.ASIN );
  24345. const acos = nodeProxy( MathNode, MathNode.ACOS );
  24346. const atan = nodeProxy( MathNode, MathNode.ATAN );
  24347. const abs = nodeProxy( MathNode, MathNode.ABS );
  24348. const sign = nodeProxy( MathNode, MathNode.SIGN );
  24349. const length = nodeProxy( MathNode, MathNode.LENGTH );
  24350. const negate = nodeProxy( MathNode, MathNode.NEGATE );
  24351. const oneMinus = nodeProxy( MathNode, MathNode.ONE_MINUS );
  24352. const dFdx = nodeProxy( MathNode, MathNode.DFDX );
  24353. const dFdy = nodeProxy( MathNode, MathNode.DFDY );
  24354. const round = nodeProxy( MathNode, MathNode.ROUND );
  24355. const reciprocal = nodeProxy( MathNode, MathNode.RECIPROCAL );
  24356. const trunc = nodeProxy( MathNode, MathNode.TRUNC );
  24357. const fwidth = nodeProxy( MathNode, MathNode.FWIDTH );
  24358. const bitcast = nodeProxy( MathNode, MathNode.BITCAST );
  24359. const transpose = nodeProxy( MathNode, MathNode.TRANSPOSE );
  24360. const atan2 = nodeProxy( MathNode, MathNode.ATAN2 );
  24361. const min$1 = nodeProxy( MathNode, MathNode.MIN );
  24362. const max$1 = nodeProxy( MathNode, MathNode.MAX );
  24363. const mod = nodeProxy( MathNode, MathNode.MOD );
  24364. const step = nodeProxy( MathNode, MathNode.STEP );
  24365. const reflect = nodeProxy( MathNode, MathNode.REFLECT );
  24366. const distance = nodeProxy( MathNode, MathNode.DISTANCE );
  24367. const difference = nodeProxy( MathNode, MathNode.DIFFERENCE );
  24368. const dot = nodeProxy( MathNode, MathNode.DOT );
  24369. const cross = nodeProxy( MathNode, MathNode.CROSS );
  24370. const pow = nodeProxy( MathNode, MathNode.POW );
  24371. const pow2 = nodeProxy( MathNode, MathNode.POW, 2 );
  24372. const pow3 = nodeProxy( MathNode, MathNode.POW, 3 );
  24373. const pow4 = nodeProxy( MathNode, MathNode.POW, 4 );
  24374. const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  24375. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  24376. const lengthSq = ( a ) => dot( a, a );
  24377. const mix = nodeProxy( MathNode, MathNode.MIX );
  24378. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  24379. const saturate = ( value ) => clamp( value );
  24380. const refract = nodeProxy( MathNode, MathNode.REFRACT );
  24381. const smoothstep = nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  24382. const faceForward = nodeProxy( MathNode, MathNode.FACEFORWARD );
  24383. const rand = tslFn( ( [ uv ] ) => {
  24384. const a = 12.9898, b = 78.233, c = 43758.5453;
  24385. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  24386. return fract( sin( sn ).mul( c ) );
  24387. } );
  24388. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  24389. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  24390. addNodeElement( 'all', all );
  24391. addNodeElement( 'any', any );
  24392. addNodeElement( 'equals', equals );
  24393. addNodeElement( 'radians', radians );
  24394. addNodeElement( 'degrees', degrees );
  24395. addNodeElement( 'exp', exp );
  24396. addNodeElement( 'exp2', exp2 );
  24397. addNodeElement( 'log', log );
  24398. addNodeElement( 'log2', log2 );
  24399. addNodeElement( 'sqrt', sqrt );
  24400. addNodeElement( 'inverseSqrt', inverseSqrt );
  24401. addNodeElement( 'floor', floor );
  24402. addNodeElement( 'ceil', ceil );
  24403. addNodeElement( 'normalize', normalize );
  24404. addNodeElement( 'fract', fract );
  24405. addNodeElement( 'sin', sin );
  24406. addNodeElement( 'cos', cos );
  24407. addNodeElement( 'tan', tan );
  24408. addNodeElement( 'asin', asin );
  24409. addNodeElement( 'acos', acos );
  24410. addNodeElement( 'atan', atan );
  24411. addNodeElement( 'abs', abs );
  24412. addNodeElement( 'sign', sign );
  24413. addNodeElement( 'length', length );
  24414. addNodeElement( 'lengthSq', lengthSq );
  24415. addNodeElement( 'negate', negate );
  24416. addNodeElement( 'oneMinus', oneMinus );
  24417. addNodeElement( 'dFdx', dFdx );
  24418. addNodeElement( 'dFdy', dFdy );
  24419. addNodeElement( 'round', round );
  24420. addNodeElement( 'reciprocal', reciprocal );
  24421. addNodeElement( 'trunc', trunc );
  24422. addNodeElement( 'fwidth', fwidth );
  24423. addNodeElement( 'atan2', atan2 );
  24424. addNodeElement( 'min', min$1 );
  24425. addNodeElement( 'max', max$1 );
  24426. addNodeElement( 'mod', mod );
  24427. addNodeElement( 'step', step );
  24428. addNodeElement( 'reflect', reflect );
  24429. addNodeElement( 'distance', distance );
  24430. addNodeElement( 'dot', dot );
  24431. addNodeElement( 'cross', cross );
  24432. addNodeElement( 'pow', pow );
  24433. addNodeElement( 'pow2', pow2 );
  24434. addNodeElement( 'pow3', pow3 );
  24435. addNodeElement( 'pow4', pow4 );
  24436. addNodeElement( 'transformDirection', transformDirection );
  24437. addNodeElement( 'mix', mixElement );
  24438. addNodeElement( 'clamp', clamp );
  24439. addNodeElement( 'refract', refract );
  24440. addNodeElement( 'smoothstep', smoothstepElement );
  24441. addNodeElement( 'faceForward', faceForward );
  24442. addNodeElement( 'difference', difference );
  24443. addNodeElement( 'saturate', saturate );
  24444. addNodeElement( 'cbrt', cbrt );
  24445. addNodeElement( 'transpose', transpose );
  24446. addNodeElement( 'rand', rand );
  24447. addNodeClass( 'MathNode', MathNode );
  24448. const sRGBToLinearShader = tslFn( ( inputs ) => {
  24449. const { value } = inputs;
  24450. const { rgb } = value;
  24451. const a = rgb.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  24452. const b = rgb.mul( 0.0773993808 );
  24453. const factor = rgb.lessThanEqual( 0.04045 );
  24454. const rgbResult = mix( a, b, factor );
  24455. return vec4( rgbResult, value.a );
  24456. } );
  24457. const LinearTosRGBShader = tslFn( ( inputs ) => {
  24458. const { value } = inputs;
  24459. const { rgb } = value;
  24460. const a = rgb.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  24461. const b = rgb.mul( 12.92 );
  24462. const factor = rgb.lessThanEqual( 0.0031308 );
  24463. const rgbResult = mix( a, b, factor );
  24464. return vec4( rgbResult, value.a );
  24465. } );
  24466. const getColorSpaceMethod = ( colorSpace ) => {
  24467. let method = null;
  24468. if ( colorSpace === LinearSRGBColorSpace ) {
  24469. method = 'Linear';
  24470. } else if ( colorSpace === SRGBColorSpace ) {
  24471. method = 'sRGB';
  24472. }
  24473. return method;
  24474. };
  24475. const getMethod = ( source, target ) => {
  24476. return getColorSpaceMethod( source ) + 'To' + getColorSpaceMethod( target );
  24477. };
  24478. class ColorSpaceNode extends TempNode {
  24479. constructor( method, node ) {
  24480. super( 'vec4' );
  24481. this.method = method;
  24482. this.node = node;
  24483. }
  24484. setup() {
  24485. const { method, node } = this;
  24486. if ( method === ColorSpaceNode.LINEAR_TO_LINEAR )
  24487. return node;
  24488. return Methods[ method ]( { value: node } );
  24489. }
  24490. }
  24491. ColorSpaceNode.LINEAR_TO_LINEAR = 'LinearToLinear';
  24492. ColorSpaceNode.LINEAR_TO_sRGB = 'LinearTosRGB';
  24493. ColorSpaceNode.sRGB_TO_LINEAR = 'sRGBToLinear';
  24494. const Methods = {
  24495. [ ColorSpaceNode.LINEAR_TO_sRGB ]: LinearTosRGBShader,
  24496. [ ColorSpaceNode.sRGB_TO_LINEAR ]: sRGBToLinearShader
  24497. };
  24498. const linearToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( LinearSRGBColorSpace, colorSpace ), nodeObject( node ) ) );
  24499. const colorSpaceToLinear = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( colorSpace, LinearSRGBColorSpace ), nodeObject( node ) ) );
  24500. const linearTosRGB = nodeProxy( ColorSpaceNode, ColorSpaceNode.LINEAR_TO_sRGB );
  24501. const sRGBToLinear = nodeProxy( ColorSpaceNode, ColorSpaceNode.sRGB_TO_LINEAR );
  24502. addNodeElement( 'linearTosRGB', linearTosRGB );
  24503. addNodeElement( 'sRGBToLinear', sRGBToLinear );
  24504. addNodeElement( 'linearToColorSpace', linearToColorSpace );
  24505. addNodeElement( 'colorSpaceToLinear', colorSpaceToLinear );
  24506. addNodeClass( 'ColorSpaceNode', ColorSpaceNode );
  24507. class ExpressionNode extends Node {
  24508. constructor( snippet = '', nodeType = 'void' ) {
  24509. super( nodeType );
  24510. this.snippet = snippet;
  24511. }
  24512. generate( builder, output ) {
  24513. const type = this.getNodeType( builder );
  24514. const snippet = this.snippet;
  24515. if ( type === 'void' ) {
  24516. builder.addLineFlowCode( snippet );
  24517. } else {
  24518. return builder.format( `( ${ snippet } )`, type, output );
  24519. }
  24520. }
  24521. }
  24522. const expression = nodeProxy( ExpressionNode );
  24523. addNodeClass( 'ExpressionNode', ExpressionNode );
  24524. class MaxMipLevelNode extends UniformNode {
  24525. constructor( textureNode ) {
  24526. super( 0 );
  24527. this._textureNode = textureNode;
  24528. this.updateType = NodeUpdateType.FRAME;
  24529. }
  24530. get textureNode() {
  24531. return this._textureNode;
  24532. }
  24533. get texture() {
  24534. return this._textureNode.value;
  24535. }
  24536. update() {
  24537. const texture = this.texture;
  24538. const images = texture.images;
  24539. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24540. if ( image && image.width !== undefined ) {
  24541. const { width, height } = image;
  24542. this.value = Math.log2( Math.max( width, height ) );
  24543. }
  24544. }
  24545. }
  24546. const maxMipLevel = nodeProxy( MaxMipLevelNode );
  24547. addNodeClass( 'MaxMipLevelNode', MaxMipLevelNode );
  24548. class TextureNode extends UniformNode {
  24549. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24550. super( value );
  24551. this.isTextureNode = true;
  24552. this.uvNode = uvNode;
  24553. this.levelNode = levelNode;
  24554. this.biasNode = biasNode;
  24555. this.compareNode = null;
  24556. this.depthNode = null;
  24557. this.gradNode = null;
  24558. this.sampler = true;
  24559. this.updateMatrix = false;
  24560. this.updateType = NodeUpdateType.NONE;
  24561. this.referenceNode = null;
  24562. this._value = value;
  24563. this._matrixUniform = null;
  24564. this.setUpdateMatrix( uvNode === null );
  24565. }
  24566. set value( value ) {
  24567. if ( this.referenceNode ) {
  24568. this.referenceNode.value = value;
  24569. } else {
  24570. this._value = value;
  24571. }
  24572. }
  24573. get value() {
  24574. return this.referenceNode ? this.referenceNode.value : this._value;
  24575. }
  24576. getUniformHash( /*builder*/ ) {
  24577. return this.value.uuid;
  24578. }
  24579. getNodeType( /*builder*/ ) {
  24580. if ( this.value.isDepthTexture === true ) return 'float';
  24581. if ( this.value.type === UnsignedIntType ) {
  24582. return 'uvec4';
  24583. } else if ( this.value.type === IntType ) {
  24584. return 'ivec4';
  24585. }
  24586. return 'vec4';
  24587. }
  24588. getInputType( /*builder*/ ) {
  24589. return 'texture';
  24590. }
  24591. getDefaultUV() {
  24592. return uv( this.value.channel );
  24593. }
  24594. updateReference( /*state*/ ) {
  24595. return this.value;
  24596. }
  24597. getTransformedUV( uvNode ) {
  24598. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24599. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24600. }
  24601. setUpdateMatrix( value ) {
  24602. this.updateMatrix = value;
  24603. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24604. return this;
  24605. }
  24606. setupUV( builder, uvNode ) {
  24607. const texture = this.value;
  24608. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24609. uvNode = uvNode.setY( uvNode.y.oneMinus() );
  24610. }
  24611. return uvNode;
  24612. }
  24613. setup( builder ) {
  24614. const properties = builder.getNodeProperties( this );
  24615. properties.referenceNode = this.referenceNode;
  24616. //
  24617. let uvNode = this.uvNode;
  24618. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24619. uvNode = builder.context.getUV( this );
  24620. }
  24621. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24622. if ( this.updateMatrix === true ) {
  24623. uvNode = this.getTransformedUV( uvNode );
  24624. }
  24625. uvNode = this.setupUV( builder, uvNode );
  24626. //
  24627. let levelNode = this.levelNode;
  24628. if ( levelNode === null && builder.context.getTextureLevel ) {
  24629. levelNode = builder.context.getTextureLevel( this );
  24630. }
  24631. //
  24632. properties.uvNode = uvNode;
  24633. properties.levelNode = levelNode;
  24634. properties.biasNode = this.biasNode;
  24635. properties.compareNode = this.compareNode;
  24636. properties.gradNode = this.gradNode;
  24637. properties.depthNode = this.depthNode;
  24638. }
  24639. generateUV( builder, uvNode ) {
  24640. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24641. }
  24642. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24643. const texture = this.value;
  24644. let snippet;
  24645. if ( levelSnippet ) {
  24646. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24647. } else if ( biasSnippet ) {
  24648. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24649. } else if ( gradSnippet ) {
  24650. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24651. } else if ( compareSnippet ) {
  24652. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24653. } else if ( this.sampler === false ) {
  24654. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24655. } else {
  24656. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24657. }
  24658. return snippet;
  24659. }
  24660. generate( builder, output ) {
  24661. const properties = builder.getNodeProperties( this );
  24662. const texture = this.value;
  24663. if ( ! texture || texture.isTexture !== true ) {
  24664. throw new Error( 'TextureNode: Need a three.js texture.' );
  24665. }
  24666. const textureProperty = super.generate( builder, 'property' );
  24667. if ( output === 'sampler' ) {
  24668. return textureProperty + '_sampler';
  24669. } else if ( builder.isReference( output ) ) {
  24670. return textureProperty;
  24671. } else {
  24672. const nodeData = builder.getDataFromNode( this );
  24673. let propertyName = nodeData.propertyName;
  24674. if ( propertyName === undefined ) {
  24675. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24676. const uvSnippet = this.generateUV( builder, uvNode );
  24677. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24678. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24679. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24680. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24681. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24682. const nodeVar = builder.getVarFromNode( this );
  24683. propertyName = builder.getPropertyName( nodeVar );
  24684. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24685. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  24686. nodeData.snippet = snippet;
  24687. nodeData.propertyName = propertyName;
  24688. }
  24689. let snippet = propertyName;
  24690. const nodeType = this.getNodeType( builder );
  24691. if ( builder.needsColorSpaceToLinear( texture ) ) {
  24692. snippet = colorSpaceToLinear( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24693. }
  24694. return builder.format( snippet, nodeType, output );
  24695. }
  24696. }
  24697. setSampler( value ) {
  24698. this.sampler = value;
  24699. return this;
  24700. }
  24701. getSampler() {
  24702. return this.sampler;
  24703. }
  24704. // @TODO: Move to TSL
  24705. uv( uvNode ) {
  24706. const textureNode = this.clone();
  24707. textureNode.uvNode = nodeObject( uvNode );
  24708. textureNode.referenceNode = this;
  24709. return nodeObject( textureNode );
  24710. }
  24711. blur( amountNode ) {
  24712. const textureNode = this.clone();
  24713. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24714. textureNode.referenceNode = this;
  24715. return nodeObject( textureNode );
  24716. }
  24717. level( levelNode ) {
  24718. const textureNode = this.clone();
  24719. textureNode.levelNode = nodeObject( levelNode );
  24720. textureNode.referenceNode = this;
  24721. return nodeObject( textureNode );
  24722. }
  24723. size( levelNode ) {
  24724. return textureSize( this, levelNode );
  24725. }
  24726. bias( biasNode ) {
  24727. const textureNode = this.clone();
  24728. textureNode.biasNode = nodeObject( biasNode );
  24729. textureNode.referenceNode = this;
  24730. return nodeObject( textureNode );
  24731. }
  24732. compare( compareNode ) {
  24733. const textureNode = this.clone();
  24734. textureNode.compareNode = nodeObject( compareNode );
  24735. textureNode.referenceNode = this;
  24736. return nodeObject( textureNode );
  24737. }
  24738. grad( gradNodeX, gradNodeY ) {
  24739. const textureNode = this.clone();
  24740. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24741. textureNode.referenceNode = this;
  24742. return nodeObject( textureNode );
  24743. }
  24744. depth( depthNode ) {
  24745. const textureNode = this.clone();
  24746. textureNode.depthNode = nodeObject( depthNode );
  24747. textureNode.referenceNode = this;
  24748. return nodeObject( textureNode );
  24749. }
  24750. // --
  24751. serialize( data ) {
  24752. super.serialize( data );
  24753. data.value = this.value.toJSON( data.meta ).uuid;
  24754. }
  24755. deserialize( data ) {
  24756. super.deserialize( data );
  24757. this.value = data.meta.textures[ data.value ];
  24758. }
  24759. update() {
  24760. const texture = this.value;
  24761. const matrixUniform = this._matrixUniform;
  24762. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24763. if ( texture.matrixAutoUpdate === true ) {
  24764. texture.updateMatrix();
  24765. }
  24766. }
  24767. clone() {
  24768. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24769. newNode.sampler = this.sampler;
  24770. return newNode;
  24771. }
  24772. }
  24773. const texture = nodeProxy( TextureNode );
  24774. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24775. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24776. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24777. addNodeElement( 'texture', texture );
  24778. //addNodeElement( 'textureLevel', textureLevel );
  24779. addNodeClass( 'TextureNode', TextureNode );
  24780. class BufferNode extends UniformNode {
  24781. constructor( value, bufferType, bufferCount = 0 ) {
  24782. super( value, bufferType );
  24783. this.isBufferNode = true;
  24784. this.bufferType = bufferType;
  24785. this.bufferCount = bufferCount;
  24786. }
  24787. getElementType( builder ) {
  24788. return this.getNodeType( builder );
  24789. }
  24790. getInputType( /*builder*/ ) {
  24791. return 'buffer';
  24792. }
  24793. }
  24794. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24795. addNodeClass( 'BufferNode', BufferNode );
  24796. class UniformsElementNode extends ArrayElementNode {
  24797. constructor( arrayBuffer, indexNode ) {
  24798. super( arrayBuffer, indexNode );
  24799. this.isArrayBufferElementNode = true;
  24800. }
  24801. getNodeType( builder ) {
  24802. return this.node.getElementType( builder );
  24803. }
  24804. generate( builder ) {
  24805. const snippet = super.generate( builder );
  24806. const type = this.getNodeType();
  24807. return builder.format( snippet, 'vec4', type );
  24808. }
  24809. }
  24810. class UniformsNode extends BufferNode {
  24811. constructor( value, elementType = null ) {
  24812. super( null, 'vec4' );
  24813. this.array = value;
  24814. this.elementType = elementType;
  24815. this._elementType = null;
  24816. this._elementLength = 0;
  24817. this.updateType = NodeUpdateType.RENDER;
  24818. this.isArrayBufferNode = true;
  24819. }
  24820. getElementType() {
  24821. return this.elementType || this._elementType;
  24822. }
  24823. getElementLength() {
  24824. return this._elementLength;
  24825. }
  24826. update( /*frame*/ ) {
  24827. const { array, value } = this;
  24828. const elementLength = this.getElementLength();
  24829. const elementType = this.getElementType();
  24830. if ( elementLength === 1 ) {
  24831. for ( let i = 0; i < array.length; i ++ ) {
  24832. const index = i * 4;
  24833. value[ index ] = array[ i ];
  24834. }
  24835. } else if ( elementType === 'color' ) {
  24836. for ( let i = 0; i < array.length; i ++ ) {
  24837. const index = i * 4;
  24838. const vector = array[ i ];
  24839. value[ index ] = vector.r;
  24840. value[ index + 1 ] = vector.g;
  24841. value[ index + 2 ] = vector.b || 0;
  24842. //value[ index + 3 ] = vector.a || 0;
  24843. }
  24844. } else {
  24845. for ( let i = 0; i < array.length; i ++ ) {
  24846. const index = i * 4;
  24847. const vector = array[ i ];
  24848. value[ index ] = vector.x;
  24849. value[ index + 1 ] = vector.y;
  24850. value[ index + 2 ] = vector.z || 0;
  24851. value[ index + 3 ] = vector.w || 0;
  24852. }
  24853. }
  24854. }
  24855. setup( builder ) {
  24856. const length = this.array.length;
  24857. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24858. this._elementLength = builder.getTypeLength( this._elementType );
  24859. let arrayType = Float32Array;
  24860. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24861. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24862. this.value = new arrayType( length * 4 );
  24863. this.bufferCount = length;
  24864. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24865. return super.setup( builder );
  24866. }
  24867. element( indexNode ) {
  24868. return nodeObject( new UniformsElementNode( this, nodeObject( indexNode ) ) );
  24869. }
  24870. }
  24871. const uniforms = ( values, nodeType ) => nodeObject( new UniformsNode( values, nodeType ) );
  24872. addNodeClass( 'UniformsNode', UniformsNode );
  24873. class ReferenceElementNode extends ArrayElementNode {
  24874. constructor( referenceNode, indexNode ) {
  24875. super( referenceNode, indexNode );
  24876. this.referenceNode = referenceNode;
  24877. this.isReferenceElementNode = true;
  24878. }
  24879. getNodeType() {
  24880. return this.referenceNode.uniformType;
  24881. }
  24882. generate( builder ) {
  24883. const snippet = super.generate( builder );
  24884. const arrayType = this.referenceNode.getNodeType();
  24885. const elementType = this.getNodeType();
  24886. return builder.format( snippet, arrayType, elementType );
  24887. }
  24888. }
  24889. class ReferenceNode extends Node {
  24890. constructor( property, uniformType, object = null, count = null ) {
  24891. super();
  24892. this.property = property;
  24893. this.uniformType = uniformType;
  24894. this.object = object;
  24895. this.count = count;
  24896. this.properties = property.split( '.' );
  24897. this.reference = null;
  24898. this.node = null;
  24899. this.updateType = NodeUpdateType.OBJECT;
  24900. }
  24901. element( indexNode ) {
  24902. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24903. }
  24904. setNodeType( uniformType ) {
  24905. let node = null;
  24906. if ( this.count !== null ) {
  24907. node = buffer( null, uniformType, this.count );
  24908. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24909. node = uniforms( null, uniformType );
  24910. } else if ( uniformType === 'texture' ) {
  24911. node = texture( null );
  24912. } else {
  24913. node = uniform( null, uniformType );
  24914. }
  24915. this.node = node;
  24916. }
  24917. getNodeType( builder ) {
  24918. if ( this.node === null ) {
  24919. this.updateValue();
  24920. }
  24921. return this.node.getNodeType( builder );
  24922. }
  24923. getValueFromReference( object = this.reference ) {
  24924. const { properties } = this;
  24925. let value = object[ properties[ 0 ] ];
  24926. for ( let i = 1; i < properties.length; i ++ ) {
  24927. value = value[ properties[ i ] ];
  24928. }
  24929. return value;
  24930. }
  24931. updateReference( state ) {
  24932. this.reference = this.object !== null ? this.object : state.object;
  24933. return this.reference;
  24934. }
  24935. setup() {
  24936. this.updateValue();
  24937. return this.node;
  24938. }
  24939. update( /*frame*/ ) {
  24940. this.updateValue();
  24941. }
  24942. updateValue() {
  24943. if ( this.node === null ) this.setNodeType( this.uniformType );
  24944. const value = this.getValueFromReference();
  24945. if ( Array.isArray( value ) ) {
  24946. this.node.array = value;
  24947. } else {
  24948. this.node.value = value;
  24949. }
  24950. }
  24951. }
  24952. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  24953. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  24954. addNodeClass( 'ReferenceNode', ReferenceNode );
  24955. class MaterialReferenceNode extends ReferenceNode {
  24956. constructor( property, inputType, material = null ) {
  24957. super( property, inputType, material );
  24958. this.material = material;
  24959. //this.updateType = NodeUpdateType.RENDER;
  24960. }
  24961. /*setNodeType( node ) {
  24962. super.setNodeType( node );
  24963. this.node.groupNode = renderGroup;
  24964. }*/
  24965. updateReference( state ) {
  24966. this.reference = this.material !== null ? this.material : state.material;
  24967. return this.reference;
  24968. }
  24969. }
  24970. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  24971. addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode );
  24972. const cameraGroup = /*#__PURE__*/ sharedUniformGroup( 'camera' ).onRenderUpdate( () => {
  24973. cameraGroup.needsUpdate = true;
  24974. } );
  24975. const cameraNear = /*#__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24976. const cameraFar = /*#__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24977. const cameraLogDepth = /*#__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  24978. const cameraProjectionMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24979. const cameraProjectionMatrixInverse = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24980. const cameraViewMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24981. const cameraWorldMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24982. const cameraNormalMatrix = /*#__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24983. const cameraPosition = /*#__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24984. class Object3DNode extends Node {
  24985. constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) {
  24986. super();
  24987. this.scope = scope;
  24988. this.object3d = object3d;
  24989. this.updateType = NodeUpdateType.OBJECT;
  24990. this._uniformNode = new UniformNode( null );
  24991. }
  24992. getNodeType() {
  24993. const scope = this.scope;
  24994. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  24995. return 'mat4';
  24996. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  24997. return 'mat3';
  24998. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24999. return 'vec3';
  25000. }
  25001. }
  25002. update( frame ) {
  25003. const object = this.object3d;
  25004. const uniformNode = this._uniformNode;
  25005. const scope = this.scope;
  25006. if ( scope === Object3DNode.VIEW_MATRIX ) {
  25007. uniformNode.value = object.modelViewMatrix;
  25008. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25009. uniformNode.value = object.normalMatrix;
  25010. } else if ( scope === Object3DNode.WORLD_MATRIX ) {
  25011. uniformNode.value = object.matrixWorld;
  25012. } else if ( scope === Object3DNode.POSITION ) {
  25013. uniformNode.value = uniformNode.value || new Vector3();
  25014. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25015. } else if ( scope === Object3DNode.SCALE ) {
  25016. uniformNode.value = uniformNode.value || new Vector3();
  25017. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  25018. } else if ( scope === Object3DNode.DIRECTION ) {
  25019. uniformNode.value = uniformNode.value || new Vector3();
  25020. object.getWorldDirection( uniformNode.value );
  25021. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  25022. const camera = frame.camera;
  25023. uniformNode.value = uniformNode.value || new Vector3();
  25024. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25025. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  25026. }
  25027. }
  25028. generate( builder ) {
  25029. const scope = this.scope;
  25030. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  25031. this._uniformNode.nodeType = 'mat4';
  25032. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25033. this._uniformNode.nodeType = 'mat3';
  25034. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  25035. this._uniformNode.nodeType = 'vec3';
  25036. }
  25037. return this._uniformNode.build( builder );
  25038. }
  25039. serialize( data ) {
  25040. super.serialize( data );
  25041. data.scope = this.scope;
  25042. }
  25043. deserialize( data ) {
  25044. super.deserialize( data );
  25045. this.scope = data.scope;
  25046. }
  25047. }
  25048. Object3DNode.VIEW_MATRIX = 'viewMatrix';
  25049. Object3DNode.NORMAL_MATRIX = 'normalMatrix';
  25050. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  25051. Object3DNode.POSITION = 'position';
  25052. Object3DNode.SCALE = 'scale';
  25053. Object3DNode.VIEW_POSITION = 'viewPosition';
  25054. Object3DNode.DIRECTION = 'direction';
  25055. const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  25056. const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX );
  25057. const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX );
  25058. const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  25059. const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION );
  25060. const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE );
  25061. const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  25062. addNodeClass( 'Object3DNode', Object3DNode );
  25063. class ModelNode extends Object3DNode {
  25064. constructor( scope = ModelNode.VIEW_MATRIX ) {
  25065. super( scope );
  25066. }
  25067. update( frame ) {
  25068. this.object3d = frame.object;
  25069. super.update( frame );
  25070. }
  25071. }
  25072. const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION );
  25073. const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' );
  25074. const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX );
  25075. const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  25076. const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION );
  25077. const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE );
  25078. const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  25079. const modelWorldMatrixInverse = uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  25080. addNodeClass( 'ModelNode', ModelNode );
  25081. const normalGeometry = /*#__PURE__*/ attribute( 'normal', 'vec3', vec3( 0, 1, 0 ) );
  25082. const normalLocal = /*#__PURE__*/ normalGeometry.toVar( 'normalLocal' );
  25083. const normalView = /*#__PURE__*/ varying( modelNormalMatrix.mul( normalLocal ), 'v_normalView' ).normalize().toVar( 'normalView' );
  25084. const normalWorld = /*#__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  25085. const transformedNormalView = /*#__PURE__*/ property( 'vec3', 'transformedNormalView' );
  25086. const transformedNormalWorld = /*#__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedNormalWorld' );
  25087. const transformedClearcoatNormalView = /*#__PURE__*/ property( 'vec3', 'transformedClearcoatNormalView' );
  25088. const _propertyCache = new Map();
  25089. class MaterialNode extends Node {
  25090. constructor( scope ) {
  25091. super();
  25092. this.scope = scope;
  25093. }
  25094. getCache( property, type ) {
  25095. let node = _propertyCache.get( property );
  25096. if ( node === undefined ) {
  25097. node = materialReference( property, type );
  25098. _propertyCache.set( property, node );
  25099. }
  25100. return node;
  25101. }
  25102. getFloat( property ) {
  25103. return this.getCache( property, 'float' );
  25104. }
  25105. getColor( property ) {
  25106. return this.getCache( property, 'color' );
  25107. }
  25108. getTexture( property ) {
  25109. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25110. }
  25111. setup( builder ) {
  25112. const material = builder.context.material;
  25113. const scope = this.scope;
  25114. let node = null;
  25115. if ( scope === MaterialNode.COLOR ) {
  25116. const colorNode = this.getColor( scope );
  25117. if ( material.map && material.map.isTexture === true ) {
  25118. node = colorNode.mul( this.getTexture( 'map' ) );
  25119. } else {
  25120. node = colorNode;
  25121. }
  25122. } else if ( scope === MaterialNode.OPACITY ) {
  25123. const opacityNode = this.getFloat( scope );
  25124. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25125. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25126. } else {
  25127. node = opacityNode;
  25128. }
  25129. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25130. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25131. node = this.getTexture( 'specular' ).r;
  25132. } else {
  25133. node = float( 1 );
  25134. }
  25135. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25136. const specularIntensity = this.getFloat( scope );
  25137. if ( material.specularMap ) {
  25138. node = specularIntensity.mul( this.getTexture( scope ).a );
  25139. } else {
  25140. node = specularIntensity;
  25141. }
  25142. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25143. const specularColorNode = this.getColor( scope );
  25144. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25145. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25146. } else {
  25147. node = specularColorNode;
  25148. }
  25149. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25150. const roughnessNode = this.getFloat( scope );
  25151. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25152. node = roughnessNode.mul( this.getTexture( scope ).g );
  25153. } else {
  25154. node = roughnessNode;
  25155. }
  25156. } else if ( scope === MaterialNode.METALNESS ) {
  25157. const metalnessNode = this.getFloat( scope );
  25158. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25159. node = metalnessNode.mul( this.getTexture( scope ).b );
  25160. } else {
  25161. node = metalnessNode;
  25162. }
  25163. } else if ( scope === MaterialNode.EMISSIVE ) {
  25164. const emissiveNode = this.getColor( scope );
  25165. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25166. node = emissiveNode.mul( this.getTexture( scope ) );
  25167. } else {
  25168. node = emissiveNode;
  25169. }
  25170. } else if ( scope === MaterialNode.NORMAL ) {
  25171. if ( material.normalMap ) {
  25172. node = this.getTexture( 'normal' ).normalMap( this.getCache( 'normalScale', 'vec2' ) );
  25173. } else if ( material.bumpMap ) {
  25174. node = this.getTexture( 'bump' ).r.bumpMap( this.getFloat( 'bumpScale' ) );
  25175. } else {
  25176. node = normalView;
  25177. }
  25178. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25179. const clearcoatNode = this.getFloat( scope );
  25180. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25181. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25182. } else {
  25183. node = clearcoatNode;
  25184. }
  25185. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25186. const clearcoatRoughnessNode = this.getFloat( scope );
  25187. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25188. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25189. } else {
  25190. node = clearcoatRoughnessNode;
  25191. }
  25192. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25193. if ( material.clearcoatNormalMap ) {
  25194. node = this.getTexture( scope ).normalMap( this.getCache( scope + 'Scale', 'vec2' ) );
  25195. } else {
  25196. node = normalView;
  25197. }
  25198. } else if ( scope === MaterialNode.SHEEN ) {
  25199. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25200. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25201. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25202. } else {
  25203. node = sheenNode;
  25204. }
  25205. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25206. const sheenRoughnessNode = this.getFloat( scope );
  25207. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25208. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25209. } else {
  25210. node = sheenRoughnessNode;
  25211. }
  25212. node = node.clamp( 0.07, 1.0 );
  25213. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25214. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25215. const anisotropyPolar = this.getTexture( scope );
  25216. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25217. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25218. } else {
  25219. node = materialAnisotropyVector;
  25220. }
  25221. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25222. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25223. if ( material.iridescenceThicknessMap ) {
  25224. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25225. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25226. } else {
  25227. node = iridescenceThicknessMaximum;
  25228. }
  25229. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25230. const transmissionNode = this.getFloat( scope );
  25231. if ( material.transmissionMap ) {
  25232. node = transmissionNode.mul( this.getTexture( scope ).r );
  25233. } else {
  25234. node = transmissionNode;
  25235. }
  25236. } else if ( scope === MaterialNode.THICKNESS ) {
  25237. const thicknessNode = this.getFloat( scope );
  25238. if ( material.thicknessMap ) {
  25239. node = thicknessNode.mul( this.getTexture( scope ).g );
  25240. } else {
  25241. node = thicknessNode;
  25242. }
  25243. } else if ( scope === MaterialNode.IOR ) {
  25244. node = this.getFloat( scope );
  25245. } else if ( scope === MaterialNode.REFRACTION_RATIO ) {
  25246. node = this.getFloat( scope );
  25247. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25248. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25249. } else if ( scope === MaterialNode.AO_MAP ) {
  25250. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25251. } else {
  25252. const outputType = this.getNodeType( builder );
  25253. node = this.getCache( scope, outputType );
  25254. }
  25255. return node;
  25256. }
  25257. }
  25258. MaterialNode.ALPHA_TEST = 'alphaTest';
  25259. MaterialNode.COLOR = 'color';
  25260. MaterialNode.OPACITY = 'opacity';
  25261. MaterialNode.SHININESS = 'shininess';
  25262. MaterialNode.SPECULAR = 'specular';
  25263. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25264. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25265. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25266. MaterialNode.REFLECTIVITY = 'reflectivity';
  25267. MaterialNode.ROUGHNESS = 'roughness';
  25268. MaterialNode.METALNESS = 'metalness';
  25269. MaterialNode.NORMAL = 'normal';
  25270. MaterialNode.CLEARCOAT = 'clearcoat';
  25271. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25272. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25273. MaterialNode.EMISSIVE = 'emissive';
  25274. MaterialNode.ROTATION = 'rotation';
  25275. MaterialNode.SHEEN = 'sheen';
  25276. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25277. MaterialNode.ANISOTROPY = 'anisotropy';
  25278. MaterialNode.IRIDESCENCE = 'iridescence';
  25279. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25280. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25281. MaterialNode.IOR = 'ior';
  25282. MaterialNode.TRANSMISSION = 'transmission';
  25283. MaterialNode.THICKNESS = 'thickness';
  25284. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25285. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25286. MaterialNode.LINE_SCALE = 'scale';
  25287. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25288. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25289. MaterialNode.LINE_WIDTH = 'linewidth';
  25290. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25291. MaterialNode.POINT_WIDTH = 'pointWidth';
  25292. MaterialNode.DISPERSION = 'dispersion';
  25293. MaterialNode.LIGHT_MAP = 'light';
  25294. MaterialNode.AO_MAP = 'ao';
  25295. MaterialNode.REFRACTION_RATIO = 'refractionRatio';
  25296. const materialAlphaTest = nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25297. const materialColor = nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25298. const materialShininess = nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25299. const materialEmissive = nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25300. const materialOpacity = nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25301. const materialSpecular = nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25302. const materialSpecularIntensity = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25303. const materialSpecularColor = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25304. const materialSpecularStrength = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25305. const materialReflectivity = nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25306. const materialRoughness = nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25307. const materialMetalness = nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25308. const materialNormal = nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  25309. const materialClearcoat = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25310. const materialClearcoatRoughness = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25311. const materialClearcoatNormal = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  25312. const materialRotation = nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25313. const materialSheen = nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25314. const materialSheenRoughness = nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25315. const materialAnisotropy = nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25316. const materialIridescence = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25317. const materialIridescenceIOR = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25318. const materialIridescenceThickness = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25319. const materialTransmission = nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25320. const materialThickness = nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25321. const materialIOR = nodeImmutable( MaterialNode, MaterialNode.IOR );
  25322. const materialAttenuationDistance = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25323. const materialAttenuationColor = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25324. const materialLineScale = nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25325. const materialLineDashSize = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25326. const materialLineGapSize = nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25327. const materialLineWidth = nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25328. const materialLineDashOffset = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25329. const materialPointWidth = nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25330. const materialDispersion = nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25331. const materialLightMap = nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25332. const materialAOMap = nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25333. const materialRefractionRatio = nodeImmutable( MaterialNode, MaterialNode.REFRACTION_RATIO );
  25334. const materialAnisotropyVector = uniform( new Vector2() ).onReference( function ( frame ) {
  25335. return frame.material;
  25336. } ).onRenderUpdate( function ( { material } ) {
  25337. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25338. } );
  25339. addNodeClass( 'MaterialNode', MaterialNode );
  25340. const positionGeometry = /*#__PURE__*/ attribute( 'position', 'vec3' );
  25341. const positionLocal = /*#__PURE__*/ positionGeometry.toVar( 'positionLocal' );
  25342. const positionWorld = /*#__PURE__*/ varying( modelWorldMatrix.mul( positionLocal ).xyz, 'v_positionWorld' );
  25343. const positionWorldDirection = /*#__PURE__*/ varying( positionLocal.transformDirection( modelWorldMatrix ), 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  25344. const positionView = /*#__PURE__*/ varying( modelViewMatrix.mul( positionLocal ).xyz, 'v_positionView' );
  25345. const positionViewDirection = /*#__PURE__*/ varying( positionView.negate(), 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  25346. class ModelViewProjectionNode extends TempNode {
  25347. constructor( positionNode = null ) {
  25348. super( 'vec4' );
  25349. this.positionNode = positionNode;
  25350. }
  25351. setup( builder ) {
  25352. if ( builder.shaderStage === 'fragment' ) {
  25353. return varying( builder.context.mvp );
  25354. }
  25355. const position = this.positionNode || positionLocal;
  25356. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( position );
  25357. }
  25358. }
  25359. const modelViewProjection = nodeProxy( ModelViewProjectionNode );
  25360. addNodeClass( 'ModelViewProjectionNode', ModelViewProjectionNode );
  25361. class BufferAttributeNode extends InputNode {
  25362. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  25363. super( value, bufferType );
  25364. this.isBufferNode = true;
  25365. this.bufferType = bufferType;
  25366. this.bufferStride = bufferStride;
  25367. this.bufferOffset = bufferOffset;
  25368. this.usage = StaticDrawUsage;
  25369. this.instanced = false;
  25370. this.attribute = null;
  25371. this.global = true;
  25372. if ( value && value.isBufferAttribute === true ) {
  25373. this.attribute = value;
  25374. this.usage = value.usage;
  25375. this.instanced = value.isInstancedBufferAttribute;
  25376. }
  25377. }
  25378. getHash( builder ) {
  25379. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  25380. let bufferData = builder.globalCache.getData( this.value );
  25381. if ( bufferData === undefined ) {
  25382. bufferData = {
  25383. node: this
  25384. };
  25385. builder.globalCache.setData( this.value, bufferData );
  25386. }
  25387. return bufferData.node.uuid;
  25388. }
  25389. return this.uuid;
  25390. }
  25391. getNodeType( builder ) {
  25392. if ( this.bufferType === null ) {
  25393. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  25394. }
  25395. return this.bufferType;
  25396. }
  25397. setup( builder ) {
  25398. if ( this.attribute !== null ) return;
  25399. const type = this.getNodeType( builder );
  25400. const array = this.value;
  25401. const itemSize = builder.getTypeLength( type );
  25402. const stride = this.bufferStride || itemSize;
  25403. const offset = this.bufferOffset;
  25404. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  25405. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  25406. buffer.setUsage( this.usage );
  25407. this.attribute = bufferAttribute;
  25408. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  25409. }
  25410. generate( builder ) {
  25411. const nodeType = this.getNodeType( builder );
  25412. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  25413. const propertyName = builder.getPropertyName( nodeAttribute );
  25414. let output = null;
  25415. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25416. this.name = propertyName;
  25417. output = propertyName;
  25418. } else {
  25419. const nodeVarying = varying( this );
  25420. output = nodeVarying.build( builder, nodeType );
  25421. }
  25422. return output;
  25423. }
  25424. getInputType( /*builder*/ ) {
  25425. return 'bufferAttribute';
  25426. }
  25427. setUsage( value ) {
  25428. this.usage = value;
  25429. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  25430. this.attribute.usage = value;
  25431. }
  25432. return this;
  25433. }
  25434. setInstanced( value ) {
  25435. this.instanced = value;
  25436. return this;
  25437. }
  25438. }
  25439. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  25440. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  25441. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  25442. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  25443. addNodeElement( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  25444. addNodeClass( 'BufferAttributeNode', BufferAttributeNode );
  25445. class InstanceNode extends Node {
  25446. constructor( instanceMesh ) {
  25447. super( 'void' );
  25448. this.instanceMesh = instanceMesh;
  25449. this.instanceMatrixNode = null;
  25450. this.instanceColorNode = null;
  25451. this.updateType = NodeUpdateType.FRAME;
  25452. this.buffer = null;
  25453. this.bufferColor = null;
  25454. }
  25455. setup( /*builder*/ ) {
  25456. let instanceMatrixNode = this.instanceMatrixNode;
  25457. const instanceMesh = this.instanceMesh;
  25458. if ( instanceMatrixNode === null ) {
  25459. const instanceAttribute = instanceMesh.instanceMatrix;
  25460. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25461. this.buffer = buffer;
  25462. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25463. const instanceBuffers = [
  25464. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25465. bufferFn( buffer, 'vec4', 16, 0 ),
  25466. bufferFn( buffer, 'vec4', 16, 4 ),
  25467. bufferFn( buffer, 'vec4', 16, 8 ),
  25468. bufferFn( buffer, 'vec4', 16, 12 )
  25469. ];
  25470. instanceMatrixNode = mat4( ...instanceBuffers );
  25471. this.instanceMatrixNode = instanceMatrixNode;
  25472. }
  25473. const instanceColorAttribute = instanceMesh.instanceColor;
  25474. if ( instanceColorAttribute && this.instanceColorNode === null ) {
  25475. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25476. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25477. this.bufferColor = buffer;
  25478. this.instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25479. }
  25480. // POSITION
  25481. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25482. // NORMAL
  25483. const m = mat3( instanceMatrixNode[ 0 ].xyz, instanceMatrixNode[ 1 ].xyz, instanceMatrixNode[ 2 ].xyz );
  25484. const transformedNormal = normalLocal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  25485. const instanceNormal = m.mul( transformedNormal ).xyz;
  25486. // ASSIGNS
  25487. positionLocal.assign( instancePosition );
  25488. normalLocal.assign( instanceNormal );
  25489. // COLOR
  25490. if ( this.instanceColorNode !== null ) {
  25491. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25492. }
  25493. }
  25494. update( /*frame*/ ) {
  25495. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25496. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25497. }
  25498. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25499. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25500. }
  25501. }
  25502. }
  25503. const instance = nodeProxy( InstanceNode );
  25504. addNodeClass( 'InstanceNode', InstanceNode );
  25505. const tangentGeometry = /*#__PURE__*/ tslFn( ( stack, builder ) => {
  25506. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25507. builder.geometry.computeTangents();
  25508. }
  25509. return attribute( 'tangent', 'vec4' );
  25510. } )();
  25511. const tangentLocal = /*#__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25512. const tangentView = /*#__PURE__*/ varying( modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz, 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25513. const tangentWorld = /*#__PURE__*/ varying( tangentView.transformDirection( cameraViewMatrix ), 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25514. const transformedTangentView = /*#__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25515. const transformedTangentWorld = /*#__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25516. class BatchNode extends Node {
  25517. constructor( batchMesh ) {
  25518. super( 'void' );
  25519. this.batchMesh = batchMesh;
  25520. this.instanceColorNode = null;
  25521. this.batchingIdNode = null;
  25522. }
  25523. setup( builder ) {
  25524. // POSITION
  25525. if ( this.batchingIdNode === null ) {
  25526. if ( builder.getDrawIndex() === null ) {
  25527. this.batchingIdNode = instanceIndex;
  25528. } else {
  25529. this.batchingIdNode = drawIndex;
  25530. }
  25531. }
  25532. const getIndirectIndex = tslFn( ( [ id ] ) => {
  25533. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25534. const x = int( id ).remainder( int( size ) );
  25535. const y = int( id ).div( int( size ) );
  25536. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25537. } ).setLayout( {
  25538. name: 'getIndirectIndex',
  25539. type: 'uint',
  25540. inputs: [
  25541. { name: 'id', type: 'int' }
  25542. ]
  25543. } );
  25544. const matriceTexture = this.batchMesh._matricesTexture;
  25545. const size = textureSize( textureLoad( matriceTexture ), 0 );
  25546. const j = float( getIndirectIndex( int( this.batchingIdNode ) ) ).mul( 4 ).toVar();
  25547. const x = int( j.mod( size ) );
  25548. const y = int( j ).div( int( size ) );
  25549. const batchingMatrix = mat4(
  25550. textureLoad( matriceTexture, ivec2( x, y ) ),
  25551. textureLoad( matriceTexture, ivec2( x.add( 1 ), y ) ),
  25552. textureLoad( matriceTexture, ivec2( x.add( 2 ), y ) ),
  25553. textureLoad( matriceTexture, ivec2( x.add( 3 ), y ) )
  25554. );
  25555. const bm = mat3(
  25556. batchingMatrix[ 0 ].xyz,
  25557. batchingMatrix[ 1 ].xyz,
  25558. batchingMatrix[ 2 ].xyz
  25559. );
  25560. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25561. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25562. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25563. normalLocal.assign( batchingNormal );
  25564. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25565. tangentLocal.mulAssign( bm );
  25566. }
  25567. }
  25568. }
  25569. const batch = nodeProxy( BatchNode );
  25570. addNodeClass( 'batch', BatchNode );
  25571. class SkinningNode extends Node {
  25572. constructor( skinnedMesh, useReference = false ) {
  25573. super( 'void' );
  25574. this.skinnedMesh = skinnedMesh;
  25575. this.useReference = useReference;
  25576. this.updateType = NodeUpdateType.OBJECT;
  25577. //
  25578. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25579. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25580. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25581. if ( useReference ) {
  25582. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25583. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25584. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25585. } else {
  25586. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25587. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25588. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25589. }
  25590. this.bindMatrixNode = bindMatrixNode;
  25591. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25592. this.boneMatricesNode = boneMatricesNode;
  25593. }
  25594. setup( builder ) {
  25595. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode, boneMatricesNode } = this;
  25596. const boneMatX = boneMatricesNode.element( skinIndexNode.x );
  25597. const boneMatY = boneMatricesNode.element( skinIndexNode.y );
  25598. const boneMatZ = boneMatricesNode.element( skinIndexNode.z );
  25599. const boneMatW = boneMatricesNode.element( skinIndexNode.w );
  25600. // POSITION
  25601. const skinVertex = bindMatrixNode.mul( positionLocal );
  25602. const skinned = add(
  25603. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25604. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25605. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25606. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25607. );
  25608. const skinPosition = bindMatrixInverseNode.mul( skinned ).xyz;
  25609. // NORMAL
  25610. let skinMatrix = add(
  25611. skinWeightNode.x.mul( boneMatX ),
  25612. skinWeightNode.y.mul( boneMatY ),
  25613. skinWeightNode.z.mul( boneMatZ ),
  25614. skinWeightNode.w.mul( boneMatW )
  25615. );
  25616. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25617. const skinNormal = skinMatrix.transformDirection( normalLocal ).xyz;
  25618. // ASSIGNS
  25619. positionLocal.assign( skinPosition );
  25620. normalLocal.assign( skinNormal );
  25621. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25622. tangentLocal.assign( skinNormal );
  25623. }
  25624. }
  25625. generate( builder, output ) {
  25626. if ( output !== 'void' ) {
  25627. return positionLocal.build( builder, output );
  25628. }
  25629. }
  25630. update( frame ) {
  25631. const object = this.useReference ? frame.object : this.skinnedMesh;
  25632. object.skeleton.update();
  25633. }
  25634. }
  25635. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25636. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25637. addNodeClass( 'SkinningNode', SkinningNode );
  25638. class LoopNode extends Node {
  25639. constructor( params = [] ) {
  25640. super();
  25641. this.params = params;
  25642. }
  25643. getVarName( index ) {
  25644. return String.fromCharCode( 'i'.charCodeAt() + index );
  25645. }
  25646. getProperties( builder ) {
  25647. const properties = builder.getNodeProperties( this );
  25648. if ( properties.stackNode !== undefined ) return properties;
  25649. //
  25650. const inputs = {};
  25651. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25652. const param = this.params[ i ];
  25653. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25654. const type = ( param.isNode !== true && param.type ) || 'int';
  25655. inputs[ name ] = expression( name, type );
  25656. }
  25657. const stack = builder.addStack(); // TODO: cache() it
  25658. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25659. properties.stackNode = stack;
  25660. builder.removeStack();
  25661. return properties;
  25662. }
  25663. getNodeType( builder ) {
  25664. const { returnsNode } = this.getProperties( builder );
  25665. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25666. }
  25667. setup( builder ) {
  25668. // setup properties
  25669. this.getProperties( builder );
  25670. }
  25671. generate( builder ) {
  25672. const properties = this.getProperties( builder );
  25673. const params = this.params;
  25674. const stackNode = properties.stackNode;
  25675. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25676. const param = params[ i ];
  25677. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25678. if ( param.isNode ) {
  25679. type = 'int';
  25680. name = this.getVarName( i );
  25681. start = '0';
  25682. end = param.build( builder, type );
  25683. condition = '<';
  25684. } else {
  25685. type = param.type || 'int';
  25686. name = param.name || this.getVarName( i );
  25687. start = param.start;
  25688. end = param.end;
  25689. condition = param.condition;
  25690. update = param.update;
  25691. if ( typeof start === 'number' ) start = start.toString();
  25692. else if ( start && start.isNode ) start = start.build( builder, type );
  25693. if ( typeof end === 'number' ) end = end.toString();
  25694. else if ( end && end.isNode ) end = end.build( builder, type );
  25695. if ( start !== undefined && end === undefined ) {
  25696. start = start + ' - 1';
  25697. end = '0';
  25698. condition = '>=';
  25699. } else if ( end !== undefined && start === undefined ) {
  25700. start = '0';
  25701. condition = '<';
  25702. }
  25703. if ( condition === undefined ) {
  25704. if ( Number( start ) > Number( end ) ) {
  25705. condition = '>=';
  25706. } else {
  25707. condition = '<';
  25708. }
  25709. }
  25710. }
  25711. const internalParam = { start, end, condition };
  25712. //
  25713. const startSnippet = internalParam.start;
  25714. const endSnippet = internalParam.end;
  25715. let declarationSnippet = '';
  25716. let conditionalSnippet = '';
  25717. let updateSnippet = '';
  25718. if ( ! update ) {
  25719. if ( type === 'int' || type === 'uint' ) {
  25720. if ( condition.includes( '<' ) ) update = '++';
  25721. else update = '--';
  25722. } else {
  25723. if ( condition.includes( '<' ) ) update = '+= 1.';
  25724. else update = '-= 1.';
  25725. }
  25726. }
  25727. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25728. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25729. updateSnippet += name + ' ' + update;
  25730. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25731. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25732. }
  25733. const stackSnippet = stackNode.build( builder, 'void' );
  25734. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25735. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25736. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25737. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25738. }
  25739. builder.addFlowTab();
  25740. return returnsSnippet;
  25741. }
  25742. }
  25743. const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25744. const Continue = () => expression( 'continue' ).append();
  25745. const Break = () => expression( 'break' ).append();
  25746. addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) );
  25747. addNodeClass( 'LoopNode', LoopNode );
  25748. const morphTextures = new WeakMap();
  25749. const morphVec4 = new Vector4();
  25750. const getMorph = tslFn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25751. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25752. const y = texelIndex.div( width );
  25753. const x = texelIndex.sub( y.mul( width ) );
  25754. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25755. return bufferAttrib.mul( influence );
  25756. } );
  25757. function getEntry( geometry ) {
  25758. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25759. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25760. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25761. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25762. // into an array of data textures. Each layer represents a single morph target.
  25763. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25764. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25765. let entry = morphTextures.get( geometry );
  25766. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25767. if ( entry !== undefined ) entry.texture.dispose();
  25768. const morphTargets = geometry.morphAttributes.position || [];
  25769. const morphNormals = geometry.morphAttributes.normal || [];
  25770. const morphColors = geometry.morphAttributes.color || [];
  25771. let vertexDataCount = 0;
  25772. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25773. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25774. if ( hasMorphColors === true ) vertexDataCount = 3;
  25775. let width = geometry.attributes.position.count * vertexDataCount;
  25776. let height = 1;
  25777. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25778. if ( width > maxTextureSize ) {
  25779. height = Math.ceil( width / maxTextureSize );
  25780. width = maxTextureSize;
  25781. }
  25782. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25783. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25784. bufferTexture.type = FloatType;
  25785. bufferTexture.needsUpdate = true;
  25786. // fill buffer
  25787. const vertexDataStride = vertexDataCount * 4;
  25788. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25789. const morphTarget = morphTargets[ i ];
  25790. const morphNormal = morphNormals[ i ];
  25791. const morphColor = morphColors[ i ];
  25792. const offset = width * height * 4 * i;
  25793. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25794. const stride = j * vertexDataStride;
  25795. if ( hasMorphPosition === true ) {
  25796. morphVec4.fromBufferAttribute( morphTarget, j );
  25797. buffer[ offset + stride + 0 ] = morphVec4.x;
  25798. buffer[ offset + stride + 1 ] = morphVec4.y;
  25799. buffer[ offset + stride + 2 ] = morphVec4.z;
  25800. buffer[ offset + stride + 3 ] = 0;
  25801. }
  25802. if ( hasMorphNormals === true ) {
  25803. morphVec4.fromBufferAttribute( morphNormal, j );
  25804. buffer[ offset + stride + 4 ] = morphVec4.x;
  25805. buffer[ offset + stride + 5 ] = morphVec4.y;
  25806. buffer[ offset + stride + 6 ] = morphVec4.z;
  25807. buffer[ offset + stride + 7 ] = 0;
  25808. }
  25809. if ( hasMorphColors === true ) {
  25810. morphVec4.fromBufferAttribute( morphColor, j );
  25811. buffer[ offset + stride + 8 ] = morphVec4.x;
  25812. buffer[ offset + stride + 9 ] = morphVec4.y;
  25813. buffer[ offset + stride + 10 ] = morphVec4.z;
  25814. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morphVec4.w : 1;
  25815. }
  25816. }
  25817. }
  25818. entry = {
  25819. count: morphTargetsCount,
  25820. texture: bufferTexture,
  25821. stride: vertexDataCount,
  25822. size: new Vector2( width, height )
  25823. };
  25824. morphTextures.set( geometry, entry );
  25825. function disposeTexture() {
  25826. bufferTexture.dispose();
  25827. morphTextures.delete( geometry );
  25828. geometry.removeEventListener( 'dispose', disposeTexture );
  25829. }
  25830. geometry.addEventListener( 'dispose', disposeTexture );
  25831. }
  25832. return entry;
  25833. }
  25834. class MorphNode extends Node {
  25835. constructor( mesh ) {
  25836. super( 'void' );
  25837. this.mesh = mesh;
  25838. this.morphBaseInfluence = uniform( 1 );
  25839. this.updateType = NodeUpdateType.OBJECT;
  25840. }
  25841. setup( builder ) {
  25842. const { geometry } = builder;
  25843. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25844. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25845. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25846. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25847. // nodes
  25848. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25849. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25850. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25851. const width = int( size.width );
  25852. loop( morphTargetsCount, ( { i } ) => {
  25853. const influence = float( 0 ).toVar();
  25854. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25855. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25856. } else {
  25857. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25858. }
  25859. if ( hasMorphPosition === true ) {
  25860. positionLocal.addAssign( getMorph( {
  25861. bufferMap,
  25862. influence,
  25863. stride,
  25864. width,
  25865. depth: i,
  25866. offset: int( 0 )
  25867. } ) );
  25868. }
  25869. if ( hasMorphNormals === true ) {
  25870. normalLocal.addAssign( getMorph( {
  25871. bufferMap,
  25872. influence,
  25873. stride,
  25874. width,
  25875. depth: i,
  25876. offset: int( 1 )
  25877. } ) );
  25878. }
  25879. } );
  25880. }
  25881. update() {
  25882. const morphBaseInfluence = this.morphBaseInfluence;
  25883. if ( this.mesh.geometry.morphTargetsRelative ) {
  25884. morphBaseInfluence.value = 1;
  25885. } else {
  25886. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25887. }
  25888. }
  25889. }
  25890. const morphReference = nodeProxy( MorphNode );
  25891. addNodeClass( 'MorphNode', MorphNode );
  25892. const reflectView = /*#__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  25893. const refractView = /*#__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  25894. const reflectVector = /*#__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25895. const refractVector = /*#__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25896. class CubeTextureNode extends TextureNode {
  25897. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  25898. super( value, uvNode, levelNode, biasNode );
  25899. this.isCubeTextureNode = true;
  25900. }
  25901. getInputType( /*builder*/ ) {
  25902. return 'cubeTexture';
  25903. }
  25904. getDefaultUV() {
  25905. const texture = this.value;
  25906. if ( texture.mapping === CubeReflectionMapping ) {
  25907. return reflectVector;
  25908. } else if ( texture.mapping === CubeRefractionMapping ) {
  25909. return refractVector;
  25910. } else {
  25911. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  25912. return vec3( 0, 0, 0 );
  25913. }
  25914. }
  25915. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  25916. setupUV( builder, uvNode ) {
  25917. const texture = this.value;
  25918. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  25919. return vec3( uvNode.x.negate(), uvNode.yz );
  25920. } else {
  25921. return uvNode;
  25922. }
  25923. }
  25924. generateUV( builder, cubeUV ) {
  25925. return cubeUV.build( builder, 'vec3' );
  25926. }
  25927. }
  25928. const cubeTexture = nodeProxy( CubeTextureNode );
  25929. addNodeElement( 'cubeTexture', cubeTexture );
  25930. addNodeClass( 'CubeTextureNode', CubeTextureNode );
  25931. class LightingNode extends Node {
  25932. constructor() {
  25933. super( 'vec3' );
  25934. this.isLightingNode = true;
  25935. }
  25936. generate( /*builder*/ ) {
  25937. console.warn( 'Abstract function.' );
  25938. }
  25939. }
  25940. addNodeClass( 'LightingNode', LightingNode );
  25941. let overrideMaterial = null;
  25942. class AnalyticLightNode extends LightingNode {
  25943. constructor( light = null ) {
  25944. super();
  25945. this.updateType = NodeUpdateType.FRAME;
  25946. this.light = light;
  25947. this.rtt = null;
  25948. this.shadowNode = null;
  25949. this.shadowMaskNode = null;
  25950. this.color = new Color();
  25951. this._defaultColorNode = uniform( this.color );
  25952. this.colorNode = this._defaultColorNode;
  25953. this.isAnalyticLightNode = true;
  25954. }
  25955. getCacheKey() {
  25956. return super.getCacheKey() + '-' + ( this.light.id + '-' + ( this.light.castShadow ? '1' : '0' ) );
  25957. }
  25958. getHash() {
  25959. return this.light.uuid;
  25960. }
  25961. setupShadow( builder ) {
  25962. const { object } = builder;
  25963. if ( object.receiveShadow === false ) return;
  25964. let shadowNode = this.shadowNode;
  25965. if ( shadowNode === null ) {
  25966. if ( overrideMaterial === null ) {
  25967. overrideMaterial = builder.createNodeMaterial();
  25968. overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  25969. overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  25970. }
  25971. const shadow = this.light.shadow;
  25972. const rtt = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25973. const depthTexture = new DepthTexture();
  25974. depthTexture.minFilter = NearestFilter;
  25975. depthTexture.magFilter = NearestFilter;
  25976. depthTexture.image.width = shadow.mapSize.width;
  25977. depthTexture.image.height = shadow.mapSize.height;
  25978. depthTexture.compareFunction = LessCompare;
  25979. rtt.depthTexture = depthTexture;
  25980. shadow.camera.updateProjectionMatrix();
  25981. //
  25982. const shadowIntensity = reference( 'intensity', 'float', shadow );
  25983. const bias = reference( 'bias', 'float', shadow );
  25984. const normalBias = reference( 'normalBias', 'float', shadow );
  25985. const position = object.material.shadowPositionNode || positionWorld;
  25986. let shadowCoord = uniform( shadow.matrix ).mul( position.add( normalWorld.mul( normalBias ) ) );
  25987. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25988. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25989. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25990. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25991. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25992. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25993. let coordZ = shadowCoord.z.add( bias );
  25994. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25995. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  25996. }
  25997. shadowCoord = vec3(
  25998. shadowCoord.x,
  25999. shadowCoord.y.oneMinus(), // follow webgpu standards
  26000. coordZ
  26001. );
  26002. const textureCompare = ( depthTexture, shadowCoord, compare ) => texture( depthTexture, shadowCoord ).compare( compare );
  26003. //const textureCompare = ( depthTexture, shadowCoord, compare ) => compare.step( texture( depthTexture, shadowCoord ) );
  26004. // BasicShadowMap
  26005. shadowNode = textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z );
  26006. // PCFShadowMap
  26007. /*
  26008. const mapSize = reference( 'mapSize', 'vec2', shadow );
  26009. const radius = reference( 'radius', 'float', shadow );
  26010. const texelSize = vec2( 1 ).div( mapSize );
  26011. const dx0 = texelSize.x.negate().mul( radius );
  26012. const dy0 = texelSize.y.negate().mul( radius );
  26013. const dx1 = texelSize.x.mul( radius );
  26014. const dy1 = texelSize.y.mul( radius );
  26015. const dx2 = dx0.mul( 2 );
  26016. const dy2 = dy0.mul( 2 );
  26017. const dx3 = dx1.mul( 2 );
  26018. const dy3 = dy1.mul( 2 );
  26019. shadowNode = add(
  26020. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  26021. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  26022. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  26023. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  26024. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  26025. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  26026. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  26027. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  26028. textureCompare( depthTexture, shadowCoord.xy, shadowCoord.z ),
  26029. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  26030. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  26031. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  26032. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  26033. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  26034. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  26035. textureCompare( depthTexture, shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  26036. textureCompare( depthTexture, shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  26037. ).mul( 1 / 17 );
  26038. */
  26039. //
  26040. const shadowColor = texture( rtt.texture, shadowCoord );
  26041. const shadowMaskNode = frustumTest.mix( 1, shadowNode.mix( shadowColor.a.mix( 1, shadowColor ), 1 ) );
  26042. this.rtt = rtt;
  26043. this.colorNode = this.colorNode.mul( mix( 1, shadowMaskNode, shadowIntensity ) );
  26044. this.shadowNode = shadowNode;
  26045. this.shadowMaskNode = shadowMaskNode;
  26046. //
  26047. this.updateBeforeType = NodeUpdateType.RENDER;
  26048. }
  26049. }
  26050. setup( builder ) {
  26051. if ( this.light.castShadow ) this.setupShadow( builder );
  26052. else if ( this.shadowNode !== null ) this.disposeShadow();
  26053. }
  26054. updateShadow( frame ) {
  26055. const { rtt, light } = this;
  26056. const { renderer, scene, camera } = frame;
  26057. const currentOverrideMaterial = scene.overrideMaterial;
  26058. scene.overrideMaterial = overrideMaterial;
  26059. rtt.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  26060. light.shadow.updateMatrices( light );
  26061. light.shadow.camera.layers.mask = camera.layers.mask;
  26062. const currentToneMapping = renderer.toneMapping;
  26063. const currentRenderTarget = renderer.getRenderTarget();
  26064. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26065. renderer.setRenderObjectFunction( ( object, ...params ) => {
  26066. if ( object.castShadow === true ) {
  26067. renderer.renderObject( object, ...params );
  26068. }
  26069. } );
  26070. renderer.setRenderTarget( rtt );
  26071. renderer.toneMapping = NoToneMapping;
  26072. renderer.render( scene, light.shadow.camera );
  26073. renderer.setRenderTarget( currentRenderTarget );
  26074. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26075. renderer.toneMapping = currentToneMapping;
  26076. scene.overrideMaterial = currentOverrideMaterial;
  26077. }
  26078. disposeShadow() {
  26079. this.rtt.dispose();
  26080. this.shadowNode = null;
  26081. this.shadowMaskNode = null;
  26082. this.rtt = null;
  26083. this.colorNode = this._defaultColorNode;
  26084. }
  26085. updateBefore( frame ) {
  26086. const { light } = this;
  26087. if ( light.castShadow ) this.updateShadow( frame );
  26088. }
  26089. update( /*frame*/ ) {
  26090. const { light } = this;
  26091. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26092. }
  26093. }
  26094. addNodeClass( 'AnalyticLightNode', AnalyticLightNode );
  26095. const LightNodes = new WeakMap();
  26096. const sortLights = ( lights ) => {
  26097. return lights.sort( ( a, b ) => a.id - b.id );
  26098. };
  26099. class LightsNode extends Node {
  26100. constructor( lightNodes = [] ) {
  26101. super( 'vec3' );
  26102. this.totalDiffuseNode = vec3().temp( 'totalDiffuse' );
  26103. this.totalSpecularNode = vec3().temp( 'totalSpecular' );
  26104. this.outgoingLightNode = vec3().temp( 'outgoingLight' );
  26105. this.lightNodes = lightNodes;
  26106. this._hash = null;
  26107. }
  26108. get hasLight() {
  26109. return this.lightNodes.length > 0;
  26110. }
  26111. getHash() {
  26112. if ( this._hash === null ) {
  26113. const hash = [];
  26114. for ( const lightNode of this.lightNodes ) {
  26115. hash.push( lightNode.getHash() );
  26116. }
  26117. this._hash = 'lights-' + hash.join( ',' );
  26118. }
  26119. return this._hash;
  26120. }
  26121. analyze( builder ) {
  26122. const properties = builder.getDataFromNode( this );
  26123. for ( const node of properties.nodes ) {
  26124. node.build( builder );
  26125. }
  26126. }
  26127. setup( builder ) {
  26128. const context = builder.context;
  26129. const lightingModel = context.lightingModel;
  26130. let outgoingLightNode = this.outgoingLightNode;
  26131. if ( lightingModel ) {
  26132. const { lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  26133. context.outgoingLight = outgoingLightNode;
  26134. const stack = builder.addStack();
  26135. //
  26136. const properties = builder.getDataFromNode( this );
  26137. properties.nodes = stack.nodes;
  26138. //
  26139. lightingModel.start( context, stack, builder );
  26140. // lights
  26141. for ( const lightNode of lightNodes ) {
  26142. lightNode.build( builder );
  26143. }
  26144. //
  26145. lightingModel.indirect( context, stack, builder );
  26146. //
  26147. const { backdrop, backdropAlpha } = context;
  26148. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26149. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26150. if ( backdrop !== null ) {
  26151. if ( backdropAlpha !== null ) {
  26152. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26153. } else {
  26154. totalDiffuse = vec3( backdrop );
  26155. }
  26156. context.material.transparent = true;
  26157. }
  26158. totalDiffuseNode.assign( totalDiffuse );
  26159. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26160. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26161. //
  26162. lightingModel.finish( context, stack, builder );
  26163. //
  26164. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26165. }
  26166. return outgoingLightNode;
  26167. }
  26168. _getLightNodeById( id ) {
  26169. for ( const lightNode of this.lightNodes ) {
  26170. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26171. return lightNode;
  26172. }
  26173. }
  26174. return null;
  26175. }
  26176. fromLights( lights = [] ) {
  26177. const lightNodes = [];
  26178. lights = sortLights( lights );
  26179. for ( const light of lights ) {
  26180. let lightNode = this._getLightNodeById( light.id );
  26181. if ( lightNode === null ) {
  26182. const lightClass = light.constructor;
  26183. const lightNodeClass = LightNodes.has( lightClass ) ? LightNodes.get( lightClass ) : AnalyticLightNode;
  26184. lightNode = nodeObject( new lightNodeClass( light ) );
  26185. }
  26186. lightNodes.push( lightNode );
  26187. }
  26188. this.lightNodes = lightNodes;
  26189. this._hash = null;
  26190. return this;
  26191. }
  26192. }
  26193. const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) );
  26194. const lightsNode = nodeProxy( LightsNode );
  26195. function addLightNode( lightClass, lightNodeClass ) {
  26196. if ( LightNodes.has( lightClass ) ) {
  26197. console.warn( `Redefinition of light node ${ lightNodeClass.type }` );
  26198. return;
  26199. }
  26200. if ( typeof lightClass !== 'function' ) throw new Error( `Light ${ lightClass.name } is not a class` );
  26201. if ( typeof lightNodeClass !== 'function' || ! lightNodeClass.type ) throw new Error( `Light node ${ lightNodeClass.type } is not a class` );
  26202. LightNodes.set( lightClass, lightNodeClass );
  26203. }
  26204. class AONode extends LightingNode {
  26205. constructor( aoNode = null ) {
  26206. super();
  26207. this.aoNode = aoNode;
  26208. }
  26209. setup( builder ) {
  26210. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  26211. }
  26212. }
  26213. addNodeClass( 'AONode', AONode );
  26214. class LightingContextNode extends ContextNode {
  26215. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26216. super( node );
  26217. this.lightingModel = lightingModel;
  26218. this.backdropNode = backdropNode;
  26219. this.backdropAlphaNode = backdropAlphaNode;
  26220. this._context = null;
  26221. }
  26222. getContext() {
  26223. const { backdropNode, backdropAlphaNode } = this;
  26224. const directDiffuse = vec3().temp( 'directDiffuse' ),
  26225. directSpecular = vec3().temp( 'directSpecular' ),
  26226. indirectDiffuse = vec3().temp( 'indirectDiffuse' ),
  26227. indirectSpecular = vec3().temp( 'indirectSpecular' );
  26228. const reflectedLight = {
  26229. directDiffuse,
  26230. directSpecular,
  26231. indirectDiffuse,
  26232. indirectSpecular
  26233. };
  26234. const context = {
  26235. radiance: vec3().temp( 'radiance' ),
  26236. irradiance: vec3().temp( 'irradiance' ),
  26237. iblIrradiance: vec3().temp( 'iblIrradiance' ),
  26238. ambientOcclusion: float( 1 ).temp( 'ambientOcclusion' ),
  26239. reflectedLight,
  26240. backdrop: backdropNode,
  26241. backdropAlpha: backdropAlphaNode
  26242. };
  26243. return context;
  26244. }
  26245. setup( builder ) {
  26246. this.context = this._context || ( this._context = this.getContext() );
  26247. this.context.lightingModel = this.lightingModel || builder.context.lightingModel;
  26248. return super.setup( builder );
  26249. }
  26250. }
  26251. const lightingContext = nodeProxy( LightingContextNode );
  26252. addNodeElement( 'lightingContext', lightingContext );
  26253. addNodeClass( 'LightingContextNode', LightingContextNode );
  26254. class IrradianceNode extends LightingNode {
  26255. constructor( node ) {
  26256. super();
  26257. this.node = node;
  26258. }
  26259. setup( builder ) {
  26260. builder.context.irradiance.addAssign( this.node );
  26261. }
  26262. }
  26263. addNodeClass( 'IrradianceNode', IrradianceNode );
  26264. let resolution, viewportResult;
  26265. class ViewportNode extends Node {
  26266. constructor( scope ) {
  26267. super();
  26268. this.scope = scope;
  26269. this.isViewportNode = true;
  26270. }
  26271. getNodeType() {
  26272. if ( this.scope === ViewportNode.VIEWPORT ) return 'vec4';
  26273. else if ( this.scope === ViewportNode.COORDINATE ) return 'vec3';
  26274. else return 'vec2';
  26275. }
  26276. getUpdateType() {
  26277. let updateType = NodeUpdateType.NONE;
  26278. if ( this.scope === ViewportNode.RESOLUTION || this.scope === ViewportNode.VIEWPORT ) {
  26279. updateType = NodeUpdateType.RENDER;
  26280. }
  26281. this.updateType = updateType;
  26282. return updateType;
  26283. }
  26284. update( { renderer } ) {
  26285. if ( this.scope === ViewportNode.VIEWPORT ) {
  26286. renderer.getViewport( viewportResult );
  26287. } else {
  26288. renderer.getDrawingBufferSize( resolution );
  26289. }
  26290. }
  26291. setup( /*builder*/ ) {
  26292. const scope = this.scope;
  26293. let output = null;
  26294. if ( scope === ViewportNode.RESOLUTION ) {
  26295. output = uniform( resolution || ( resolution = new Vector2() ) );
  26296. } else if ( scope === ViewportNode.VIEWPORT ) {
  26297. output = uniform( viewportResult || ( viewportResult = new Vector4() ) );
  26298. } else {
  26299. output = viewportCoordinate.div( viewportResolution );
  26300. let outX = output.x;
  26301. let outY = output.y;
  26302. if ( /bottom/i.test( scope ) ) outY = outY.oneMinus();
  26303. if ( /right/i.test( scope ) ) outX = outX.oneMinus();
  26304. output = vec2( outX, outY );
  26305. }
  26306. return output;
  26307. }
  26308. generate( builder ) {
  26309. if ( this.scope === ViewportNode.COORDINATE ) {
  26310. let coord = builder.getFragCoord();
  26311. if ( builder.isFlipY() ) {
  26312. // follow webgpu standards
  26313. const resolution = builder.getNodeProperties( viewportResolution ).outputNode.build( builder );
  26314. coord = `${ builder.getType( 'vec3' ) }( ${ coord }.x, ${ resolution }.y - ${ coord }.y, ${ coord }.z )`;
  26315. }
  26316. return coord;
  26317. }
  26318. return super.generate( builder );
  26319. }
  26320. }
  26321. ViewportNode.COORDINATE = 'coordinate';
  26322. ViewportNode.RESOLUTION = 'resolution';
  26323. ViewportNode.VIEWPORT = 'viewport';
  26324. ViewportNode.TOP_LEFT = 'topLeft';
  26325. ViewportNode.BOTTOM_LEFT = 'bottomLeft';
  26326. ViewportNode.TOP_RIGHT = 'topRight';
  26327. ViewportNode.BOTTOM_RIGHT = 'bottomRight';
  26328. const viewportCoordinate = nodeImmutable( ViewportNode, ViewportNode.COORDINATE );
  26329. const viewportResolution = nodeImmutable( ViewportNode, ViewportNode.RESOLUTION );
  26330. const viewport = nodeImmutable( ViewportNode, ViewportNode.VIEWPORT );
  26331. const viewportTopLeft = nodeImmutable( ViewportNode, ViewportNode.TOP_LEFT );
  26332. const viewportBottomLeft = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_LEFT );
  26333. const viewportTopRight = nodeImmutable( ViewportNode, ViewportNode.TOP_RIGHT );
  26334. const viewportBottomRight = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_RIGHT );
  26335. addNodeClass( 'ViewportNode', ViewportNode );
  26336. const _size$5 = new Vector2();
  26337. class ViewportTextureNode extends TextureNode {
  26338. constructor( uvNode = viewportTopLeft, levelNode = null, framebufferTexture = null ) {
  26339. if ( framebufferTexture === null ) {
  26340. framebufferTexture = new FramebufferTexture();
  26341. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26342. }
  26343. super( framebufferTexture, uvNode, levelNode );
  26344. this.generateMipmaps = false;
  26345. this.isOutputTextureNode = true;
  26346. this.updateBeforeType = NodeUpdateType.FRAME;
  26347. }
  26348. updateBefore( frame ) {
  26349. const renderer = frame.renderer;
  26350. renderer.getDrawingBufferSize( _size$5 );
  26351. //
  26352. const framebufferTexture = this.value;
  26353. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  26354. framebufferTexture.image.width = _size$5.width;
  26355. framebufferTexture.image.height = _size$5.height;
  26356. framebufferTexture.needsUpdate = true;
  26357. }
  26358. //
  26359. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26360. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26361. renderer.copyFramebufferToTexture( framebufferTexture );
  26362. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26363. }
  26364. clone() {
  26365. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26366. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26367. return viewportTextureNode;
  26368. }
  26369. }
  26370. const viewportTexture = nodeProxy( ViewportTextureNode );
  26371. const viewportMipTexture = nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26372. addNodeElement( 'viewportTexture', viewportTexture );
  26373. addNodeElement( 'viewportMipTexture', viewportMipTexture );
  26374. addNodeClass( 'ViewportTextureNode', ViewportTextureNode );
  26375. let sharedDepthbuffer = null;
  26376. class ViewportDepthTextureNode extends ViewportTextureNode {
  26377. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  26378. if ( sharedDepthbuffer === null ) {
  26379. sharedDepthbuffer = new DepthTexture();
  26380. }
  26381. super( uvNode, levelNode, sharedDepthbuffer );
  26382. }
  26383. }
  26384. const viewportDepthTexture = nodeProxy( ViewportDepthTextureNode );
  26385. addNodeElement( 'viewportDepthTexture', viewportDepthTexture );
  26386. addNodeClass( 'ViewportDepthTextureNode', ViewportDepthTextureNode );
  26387. class ViewportDepthNode extends Node {
  26388. constructor( scope, valueNode = null ) {
  26389. super( 'float' );
  26390. this.scope = scope;
  26391. this.valueNode = valueNode;
  26392. this.isViewportDepthNode = true;
  26393. }
  26394. generate( builder ) {
  26395. const { scope } = this;
  26396. if ( scope === ViewportDepthNode.DEPTH ) {
  26397. return builder.getFragDepth();
  26398. }
  26399. return super.generate( builder );
  26400. }
  26401. setup( { camera } ) {
  26402. const { scope } = this;
  26403. const texture = this.valueNode;
  26404. let node = null;
  26405. if ( scope === ViewportDepthNode.DEPTH ) {
  26406. if ( texture !== null ) {
  26407. node = depthBase().assign( texture );
  26408. } else {
  26409. if ( camera.isPerspectiveCamera ) {
  26410. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26411. } else {
  26412. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26413. }
  26414. }
  26415. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26416. if ( texture !== null ) {
  26417. if ( camera.isPerspectiveCamera ) {
  26418. const viewZ = perspectiveDepthToViewZ( texture, cameraNear, cameraFar );
  26419. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26420. } else {
  26421. node = texture;
  26422. }
  26423. } else {
  26424. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26425. }
  26426. }
  26427. return node;
  26428. }
  26429. }
  26430. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26431. // -near maps to 0; -far maps to 1
  26432. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26433. // maps orthographic depth in [ 0, 1 ] to viewZ
  26434. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26435. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26436. // -near maps to 0; -far maps to 1
  26437. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26438. // maps perspective depth in [ 0, 1 ] to viewZ
  26439. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26440. ViewportDepthNode.DEPTH = 'depth';
  26441. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26442. const depthBase = nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26443. const depth = nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26444. const linearDepth = nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26445. const viewportLinearDepth = linearDepth( viewportDepthTexture() );
  26446. depth.assign = ( value ) => depthBase( value );
  26447. addNodeClass( 'ViewportDepthNode', ViewportDepthNode );
  26448. class ClippingNode extends Node {
  26449. constructor( scope = ClippingNode.DEFAULT ) {
  26450. super();
  26451. this.scope = scope;
  26452. }
  26453. setup( builder ) {
  26454. super.setup( builder );
  26455. const clippingContext = builder.clippingContext;
  26456. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26457. const numClippingPlanes = globalClippingCount + localClippingCount;
  26458. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26459. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26460. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26461. } else {
  26462. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26463. }
  26464. }
  26465. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26466. return tslFn( () => {
  26467. const clippingPlanes = uniforms( planes );
  26468. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26469. const distanceGradient = property( 'float', 'distanceToGradient' );
  26470. const clipOpacity = property( 'float', 'clipOpacity' );
  26471. clipOpacity.assign( 1 );
  26472. let plane;
  26473. loop( numUnionClippingPlanes, ( { i } ) => {
  26474. plane = clippingPlanes.element( i );
  26475. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26476. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26477. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26478. clipOpacity.equal( 0.0 ).discard();
  26479. } );
  26480. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26481. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26482. unionClipOpacity.assign( 1 );
  26483. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26484. plane = clippingPlanes.element( i );
  26485. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26486. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26487. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26488. } );
  26489. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26490. }
  26491. diffuseColor.a.mulAssign( clipOpacity );
  26492. diffuseColor.a.equal( 0.0 ).discard();
  26493. } )();
  26494. }
  26495. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26496. return tslFn( () => {
  26497. const clippingPlanes = uniforms( planes );
  26498. let plane;
  26499. loop( numUnionClippingPlanes, ( { i } ) => {
  26500. plane = clippingPlanes.element( i );
  26501. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26502. } );
  26503. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26504. const clipped = property( 'bool', 'clipped' );
  26505. clipped.assign( true );
  26506. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26507. plane = clippingPlanes.element( i );
  26508. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26509. } );
  26510. clipped.discard();
  26511. }
  26512. } )();
  26513. }
  26514. }
  26515. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26516. ClippingNode.DEFAULT = 'default';
  26517. const clipping = () => nodeObject( new ClippingNode() );
  26518. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26519. class FrontFacingNode extends Node {
  26520. constructor() {
  26521. super( 'bool' );
  26522. this.isFrontFacingNode = true;
  26523. }
  26524. generate( builder ) {
  26525. const { renderer, material } = builder;
  26526. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  26527. if ( material.side === BackSide ) {
  26528. return 'false';
  26529. }
  26530. }
  26531. return builder.getFrontFacing();
  26532. }
  26533. }
  26534. const frontFacing = nodeImmutable( FrontFacingNode );
  26535. const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  26536. addNodeClass( 'FrontFacingNode', FrontFacingNode );
  26537. const NodeMaterials = new Map();
  26538. class NodeMaterial extends Material {
  26539. constructor() {
  26540. super();
  26541. this.isNodeMaterial = true;
  26542. this.type = this.constructor.type;
  26543. this.forceSinglePass = false;
  26544. this.fog = true;
  26545. this.lights = true;
  26546. this.normals = true;
  26547. this.lightsNode = null;
  26548. this.envNode = null;
  26549. this.aoNode = null;
  26550. this.colorNode = null;
  26551. this.normalNode = null;
  26552. this.opacityNode = null;
  26553. this.backdropNode = null;
  26554. this.backdropAlphaNode = null;
  26555. this.alphaTestNode = null;
  26556. this.positionNode = null;
  26557. this.depthNode = null;
  26558. this.shadowNode = null;
  26559. this.shadowPositionNode = null;
  26560. this.outputNode = null;
  26561. this.mrtNode = null;
  26562. this.fragmentNode = null;
  26563. this.vertexNode = null;
  26564. }
  26565. customProgramCacheKey() {
  26566. return this.type + getCacheKey( this );
  26567. }
  26568. build( builder ) {
  26569. this.setup( builder );
  26570. }
  26571. setup( builder ) {
  26572. // < VERTEX STAGE >
  26573. builder.addStack();
  26574. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26575. builder.addFlow( 'vertex', builder.removeStack() );
  26576. // < FRAGMENT STAGE >
  26577. builder.addStack();
  26578. let resultNode;
  26579. const clippingNode = this.setupClipping( builder );
  26580. if ( this.depthWrite === true ) this.setupDepth( builder );
  26581. if ( this.fragmentNode === null ) {
  26582. if ( this.normals === true ) this.setupNormal( builder );
  26583. this.setupDiffuseColor( builder );
  26584. this.setupVariants( builder );
  26585. const outgoingLightNode = this.setupLighting( builder );
  26586. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26587. // force unsigned floats - useful for RenderTargets
  26588. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26589. resultNode = this.setupOutput( builder, basicOutput );
  26590. // OUTPUT NODE
  26591. output.assign( resultNode );
  26592. //
  26593. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26594. // MRT
  26595. const renderTarget = builder.renderer.getRenderTarget();
  26596. if ( renderTarget !== null ) {
  26597. const mrt = builder.renderer.getMRT();
  26598. const materialMRT = this.mrtNode;
  26599. if ( mrt !== null ) {
  26600. resultNode = mrt;
  26601. if ( materialMRT !== null ) {
  26602. resultNode = mrt.merge( materialMRT );
  26603. }
  26604. } else if ( materialMRT !== null ) {
  26605. resultNode = materialMRT;
  26606. }
  26607. }
  26608. } else {
  26609. let fragmentNode = this.fragmentNode;
  26610. if ( fragmentNode.isOutputStructNode !== true ) {
  26611. fragmentNode = vec4( fragmentNode );
  26612. }
  26613. resultNode = this.setupOutput( builder, fragmentNode );
  26614. }
  26615. builder.stack.outputNode = resultNode;
  26616. builder.addFlow( 'fragment', builder.removeStack() );
  26617. }
  26618. setupClipping( builder ) {
  26619. if ( builder.clippingContext === null ) return null;
  26620. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26621. let result = null;
  26622. if ( globalClippingCount || localClippingCount ) {
  26623. if ( this.alphaToCoverage ) {
  26624. // to be added to flow when the color/alpha value has been determined
  26625. result = clippingAlpha();
  26626. } else {
  26627. builder.stack.add( clipping() );
  26628. }
  26629. }
  26630. return result;
  26631. }
  26632. setupDepth( builder ) {
  26633. const { renderer } = builder;
  26634. // Depth
  26635. let depthNode = this.depthNode;
  26636. if ( depthNode === null && renderer.logarithmicDepthBuffer === true ) {
  26637. const fragDepth = modelViewProjection().w.add( 1 );
  26638. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  26639. }
  26640. if ( depthNode !== null ) {
  26641. depth.assign( depthNode ).append();
  26642. }
  26643. }
  26644. setupPosition( builder ) {
  26645. const { object } = builder;
  26646. const geometry = object.geometry;
  26647. builder.addStack();
  26648. // Vertex
  26649. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26650. morphReference( object ).append();
  26651. }
  26652. if ( object.isSkinnedMesh === true ) {
  26653. skinningReference( object ).append();
  26654. }
  26655. if ( this.displacementMap ) {
  26656. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26657. const displacementScale = materialReference( 'displacementScale', 'float' );
  26658. const displacementBias = materialReference( 'displacementBias', 'float' );
  26659. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26660. }
  26661. if ( object.isBatchedMesh ) {
  26662. batch( object ).append();
  26663. }
  26664. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26665. instance( object ).append();
  26666. }
  26667. if ( this.positionNode !== null ) {
  26668. positionLocal.assign( this.positionNode );
  26669. }
  26670. const mvp = modelViewProjection();
  26671. builder.context.vertex = builder.removeStack();
  26672. builder.context.mvp = mvp;
  26673. return mvp;
  26674. }
  26675. setupDiffuseColor( { object, geometry } ) {
  26676. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26677. // VERTEX COLORS
  26678. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26679. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26680. }
  26681. // Instanced colors
  26682. if ( object.instanceColor ) {
  26683. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26684. colorNode = instanceColor.mul( colorNode );
  26685. }
  26686. // COLOR
  26687. diffuseColor.assign( colorNode );
  26688. // OPACITY
  26689. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26690. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26691. // ALPHA TEST
  26692. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26693. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26694. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26695. }
  26696. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26697. diffuseColor.a.assign( 1.0 );
  26698. }
  26699. }
  26700. setupVariants( /*builder*/ ) {
  26701. // Interface function.
  26702. }
  26703. setupNormal() {
  26704. // NORMAL VIEW
  26705. if ( this.flatShading === true ) {
  26706. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  26707. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  26708. } else {
  26709. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26710. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  26711. }
  26712. }
  26713. setupEnvironment( builder ) {
  26714. let node = null;
  26715. if ( this.envNode ) {
  26716. node = this.envNode;
  26717. } else if ( this.envMap ) {
  26718. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  26719. } else if ( builder.environmentNode ) {
  26720. node = builder.environmentNode;
  26721. }
  26722. return node;
  26723. }
  26724. setupLightMap( builder ) {
  26725. let node = null;
  26726. if ( builder.material.lightMap ) {
  26727. node = new IrradianceNode( materialLightMap );
  26728. }
  26729. return node;
  26730. }
  26731. setupLights( builder ) {
  26732. const materialLightsNode = [];
  26733. //
  26734. const envNode = this.setupEnvironment( builder );
  26735. if ( envNode && envNode.isLightingNode ) {
  26736. materialLightsNode.push( envNode );
  26737. }
  26738. const lightMapNode = this.setupLightMap( builder );
  26739. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26740. materialLightsNode.push( lightMapNode );
  26741. }
  26742. if ( this.aoNode !== null || builder.material.aoMap ) {
  26743. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26744. materialLightsNode.push( new AONode( aoNode ) );
  26745. }
  26746. let lightsN = this.lightsNode || builder.lightsNode;
  26747. if ( materialLightsNode.length > 0 ) {
  26748. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  26749. }
  26750. return lightsN;
  26751. }
  26752. setupLightingModel( /*builder*/ ) {
  26753. // Interface function.
  26754. }
  26755. setupLighting( builder ) {
  26756. const { material } = builder;
  26757. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26758. // OUTGOING LIGHT
  26759. const lights = this.lights === true || this.lightsNode !== null;
  26760. const lightsNode = lights ? this.setupLights( builder ) : null;
  26761. let outgoingLightNode = diffuseColor.rgb;
  26762. if ( lightsNode && lightsNode.hasLight !== false ) {
  26763. const lightingModel = this.setupLightingModel( builder );
  26764. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26765. } else if ( backdropNode !== null ) {
  26766. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26767. }
  26768. // EMISSIVE
  26769. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26770. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26771. outgoingLightNode = outgoingLightNode.add( emissive );
  26772. }
  26773. return outgoingLightNode;
  26774. }
  26775. setupOutput( builder, outputNode ) {
  26776. // FOG
  26777. if ( this.fog === true ) {
  26778. const fogNode = builder.fogNode;
  26779. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26780. }
  26781. return outputNode;
  26782. }
  26783. setDefaultValues( material ) {
  26784. // This approach is to reuse the native refreshUniforms*
  26785. // and turn available the use of features like transmission and environment in core
  26786. for ( const property in material ) {
  26787. const value = material[ property ];
  26788. if ( this[ property ] === undefined ) {
  26789. this[ property ] = value;
  26790. if ( value && value.clone ) this[ property ] = value.clone();
  26791. }
  26792. }
  26793. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26794. for ( const key in descriptors ) {
  26795. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26796. descriptors[ key ].get !== undefined ) {
  26797. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26798. }
  26799. }
  26800. }
  26801. toJSON( meta ) {
  26802. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26803. if ( isRoot ) {
  26804. meta = {
  26805. textures: {},
  26806. images: {},
  26807. nodes: {}
  26808. };
  26809. }
  26810. const data = Material.prototype.toJSON.call( this, meta );
  26811. const nodeChildren = getNodeChildren( this );
  26812. data.inputNodes = {};
  26813. for ( const { property, childNode } of nodeChildren ) {
  26814. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26815. }
  26816. // TODO: Copied from Object3D.toJSON
  26817. function extractFromCache( cache ) {
  26818. const values = [];
  26819. for ( const key in cache ) {
  26820. const data = cache[ key ];
  26821. delete data.metadata;
  26822. values.push( data );
  26823. }
  26824. return values;
  26825. }
  26826. if ( isRoot ) {
  26827. const textures = extractFromCache( meta.textures );
  26828. const images = extractFromCache( meta.images );
  26829. const nodes = extractFromCache( meta.nodes );
  26830. if ( textures.length > 0 ) data.textures = textures;
  26831. if ( images.length > 0 ) data.images = images;
  26832. if ( nodes.length > 0 ) data.nodes = nodes;
  26833. }
  26834. return data;
  26835. }
  26836. copy( source ) {
  26837. this.lightsNode = source.lightsNode;
  26838. this.envNode = source.envNode;
  26839. this.colorNode = source.colorNode;
  26840. this.normalNode = source.normalNode;
  26841. this.opacityNode = source.opacityNode;
  26842. this.backdropNode = source.backdropNode;
  26843. this.backdropAlphaNode = source.backdropAlphaNode;
  26844. this.alphaTestNode = source.alphaTestNode;
  26845. this.positionNode = source.positionNode;
  26846. this.depthNode = source.depthNode;
  26847. this.shadowNode = source.shadowNode;
  26848. this.shadowPositionNode = source.shadowPositionNode;
  26849. this.outputNode = source.outputNode;
  26850. this.mrtNode = source.mrtNode;
  26851. this.fragmentNode = source.fragmentNode;
  26852. this.vertexNode = source.vertexNode;
  26853. return super.copy( source );
  26854. }
  26855. static fromMaterial( material ) {
  26856. if ( material.isNodeMaterial === true ) { // is already a node material
  26857. return material;
  26858. }
  26859. const type = material.type.replace( 'Material', 'NodeMaterial' );
  26860. const nodeMaterial = createNodeMaterialFromType( type );
  26861. if ( nodeMaterial === undefined ) {
  26862. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  26863. }
  26864. for ( const key in material ) {
  26865. nodeMaterial[ key ] = material[ key ];
  26866. }
  26867. return nodeMaterial;
  26868. }
  26869. }
  26870. function addNodeMaterial( type, nodeMaterial ) {
  26871. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  26872. if ( NodeMaterials.has( type ) ) {
  26873. console.warn( `Redefinition of node material ${ type }` );
  26874. return;
  26875. }
  26876. NodeMaterials.set( type, nodeMaterial );
  26877. nodeMaterial.type = type;
  26878. }
  26879. function createNodeMaterialFromType( type ) {
  26880. const Material = NodeMaterials.get( type );
  26881. if ( Material !== undefined ) {
  26882. return new Material();
  26883. }
  26884. }
  26885. addNodeMaterial( 'NodeMaterial', NodeMaterial );
  26886. class Uniform {
  26887. constructor( name, value ) {
  26888. this.name = name;
  26889. this.value = value;
  26890. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  26891. this.itemSize = 0;
  26892. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  26893. }
  26894. setValue( value ) {
  26895. this.value = value;
  26896. }
  26897. getValue() {
  26898. return this.value;
  26899. }
  26900. }
  26901. class NumberUniform extends Uniform {
  26902. constructor( name, value = 0 ) {
  26903. super( name, value );
  26904. this.isNumberUniform = true;
  26905. this.boundary = 4;
  26906. this.itemSize = 1;
  26907. }
  26908. }
  26909. class Vector2Uniform extends Uniform {
  26910. constructor( name, value = new Vector2() ) {
  26911. super( name, value );
  26912. this.isVector2Uniform = true;
  26913. this.boundary = 8;
  26914. this.itemSize = 2;
  26915. }
  26916. }
  26917. class Vector3Uniform extends Uniform {
  26918. constructor( name, value = new Vector3() ) {
  26919. super( name, value );
  26920. this.isVector3Uniform = true;
  26921. this.boundary = 16;
  26922. this.itemSize = 3;
  26923. }
  26924. }
  26925. class Vector4Uniform extends Uniform {
  26926. constructor( name, value = new Vector4() ) {
  26927. super( name, value );
  26928. this.isVector4Uniform = true;
  26929. this.boundary = 16;
  26930. this.itemSize = 4;
  26931. }
  26932. }
  26933. class ColorUniform extends Uniform {
  26934. constructor( name, value = new Color() ) {
  26935. super( name, value );
  26936. this.isColorUniform = true;
  26937. this.boundary = 16;
  26938. this.itemSize = 3;
  26939. }
  26940. }
  26941. class Matrix3Uniform extends Uniform {
  26942. constructor( name, value = new Matrix3() ) {
  26943. super( name, value );
  26944. this.isMatrix3Uniform = true;
  26945. this.boundary = 48;
  26946. this.itemSize = 12;
  26947. }
  26948. }
  26949. class Matrix4Uniform extends Uniform {
  26950. constructor( name, value = new Matrix4() ) {
  26951. super( name, value );
  26952. this.isMatrix4Uniform = true;
  26953. this.boundary = 64;
  26954. this.itemSize = 16;
  26955. }
  26956. }
  26957. class NumberNodeUniform extends NumberUniform {
  26958. constructor( nodeUniform ) {
  26959. super( nodeUniform.name, nodeUniform.value );
  26960. this.nodeUniform = nodeUniform;
  26961. }
  26962. getValue() {
  26963. return this.nodeUniform.value;
  26964. }
  26965. }
  26966. class Vector2NodeUniform extends Vector2Uniform {
  26967. constructor( nodeUniform ) {
  26968. super( nodeUniform.name, nodeUniform.value );
  26969. this.nodeUniform = nodeUniform;
  26970. }
  26971. getValue() {
  26972. return this.nodeUniform.value;
  26973. }
  26974. }
  26975. class Vector3NodeUniform extends Vector3Uniform {
  26976. constructor( nodeUniform ) {
  26977. super( nodeUniform.name, nodeUniform.value );
  26978. this.nodeUniform = nodeUniform;
  26979. }
  26980. getValue() {
  26981. return this.nodeUniform.value;
  26982. }
  26983. }
  26984. class Vector4NodeUniform extends Vector4Uniform {
  26985. constructor( nodeUniform ) {
  26986. super( nodeUniform.name, nodeUniform.value );
  26987. this.nodeUniform = nodeUniform;
  26988. }
  26989. getValue() {
  26990. return this.nodeUniform.value;
  26991. }
  26992. }
  26993. class ColorNodeUniform extends ColorUniform {
  26994. constructor( nodeUniform ) {
  26995. super( nodeUniform.name, nodeUniform.value );
  26996. this.nodeUniform = nodeUniform;
  26997. }
  26998. getValue() {
  26999. return this.nodeUniform.value;
  27000. }
  27001. }
  27002. class Matrix3NodeUniform extends Matrix3Uniform {
  27003. constructor( nodeUniform ) {
  27004. super( nodeUniform.name, nodeUniform.value );
  27005. this.nodeUniform = nodeUniform;
  27006. }
  27007. getValue() {
  27008. return this.nodeUniform.value;
  27009. }
  27010. }
  27011. class Matrix4NodeUniform extends Matrix4Uniform {
  27012. constructor( nodeUniform ) {
  27013. super( nodeUniform.name, nodeUniform.value );
  27014. this.nodeUniform = nodeUniform;
  27015. }
  27016. getValue() {
  27017. return this.nodeUniform.value;
  27018. }
  27019. }
  27020. class CondNode extends Node {
  27021. constructor( condNode, ifNode, elseNode = null ) {
  27022. super();
  27023. this.condNode = condNode;
  27024. this.ifNode = ifNode;
  27025. this.elseNode = elseNode;
  27026. }
  27027. getNodeType( builder ) {
  27028. const ifType = this.ifNode.getNodeType( builder );
  27029. if ( this.elseNode !== null ) {
  27030. const elseType = this.elseNode.getNodeType( builder );
  27031. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  27032. return elseType;
  27033. }
  27034. }
  27035. return ifType;
  27036. }
  27037. setup( builder ) {
  27038. const properties = builder.getNodeProperties( this );
  27039. properties.condNode = this.condNode.cache();
  27040. properties.ifNode = this.ifNode.cache();
  27041. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  27042. }
  27043. generate( builder, output ) {
  27044. const type = this.getNodeType( builder );
  27045. const nodeData = builder.getDataFromNode( this );
  27046. if ( nodeData.nodeProperty !== undefined ) {
  27047. return nodeData.nodeProperty;
  27048. }
  27049. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  27050. const needsOutput = output !== 'void';
  27051. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  27052. nodeData.nodeProperty = nodeProperty;
  27053. const nodeSnippet = condNode.build( builder, 'bool' );
  27054. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  27055. let ifSnippet = ifNode.build( builder, type );
  27056. if ( ifSnippet ) {
  27057. if ( needsOutput ) {
  27058. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  27059. } else {
  27060. ifSnippet = 'return ' + ifSnippet + ';';
  27061. }
  27062. }
  27063. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  27064. if ( elseNode !== null ) {
  27065. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  27066. let elseSnippet = elseNode.build( builder, type );
  27067. if ( elseSnippet ) {
  27068. if ( needsOutput ) {
  27069. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  27070. } else {
  27071. elseSnippet = 'return ' + elseSnippet + ';';
  27072. }
  27073. }
  27074. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  27075. } else {
  27076. builder.addFlowCode( '\n\n' );
  27077. }
  27078. return builder.format( nodeProperty, type, output );
  27079. }
  27080. }
  27081. const cond = nodeProxy( CondNode );
  27082. addNodeElement( 'cond', cond );
  27083. addNodeClass( 'CondNode', CondNode );
  27084. class StackNode extends Node {
  27085. constructor( parent = null ) {
  27086. super();
  27087. this.nodes = [];
  27088. this.outputNode = null;
  27089. this.parent = parent;
  27090. this._currentCond = null;
  27091. this.isStackNode = true;
  27092. }
  27093. getNodeType( builder ) {
  27094. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  27095. }
  27096. add( node ) {
  27097. this.nodes.push( node );
  27098. return this;
  27099. }
  27100. if( boolNode, method ) {
  27101. const methodNode = new ShaderNode( method );
  27102. this._currentCond = cond( boolNode, methodNode );
  27103. return this.add( this._currentCond );
  27104. }
  27105. elseif( boolNode, method ) {
  27106. const methodNode = new ShaderNode( method );
  27107. const ifNode = cond( boolNode, methodNode );
  27108. this._currentCond.elseNode = ifNode;
  27109. this._currentCond = ifNode;
  27110. return this;
  27111. }
  27112. else( method ) {
  27113. this._currentCond.elseNode = new ShaderNode( method );
  27114. return this;
  27115. }
  27116. build( builder, ...params ) {
  27117. const previousStack = getCurrentStack();
  27118. setCurrentStack( this );
  27119. for ( const node of this.nodes ) {
  27120. node.build( builder, 'void' );
  27121. }
  27122. setCurrentStack( previousStack );
  27123. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  27124. }
  27125. }
  27126. const stack = nodeProxy( StackNode );
  27127. addNodeClass( 'StackNode', StackNode );
  27128. class EquirectUVNode extends TempNode {
  27129. constructor( dirNode = positionWorldDirection ) {
  27130. super( 'vec2' );
  27131. this.dirNode = dirNode;
  27132. }
  27133. setup() {
  27134. const dir = this.dirNode;
  27135. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27136. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27137. return vec2( u, v );
  27138. }
  27139. }
  27140. const equirectUV = nodeProxy( EquirectUVNode );
  27141. addNodeClass( 'EquirectUVNode', EquirectUVNode );
  27142. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27143. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27144. constructor( size = 1, options = {} ) {
  27145. super( size, options );
  27146. this.isCubeRenderTarget = true;
  27147. }
  27148. fromEquirectangularTexture( renderer, texture$1 ) {
  27149. const currentMinFilter = texture$1.minFilter;
  27150. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27151. texture$1.generateMipmaps = true;
  27152. this.texture.type = texture$1.type;
  27153. this.texture.colorSpace = texture$1.colorSpace;
  27154. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27155. this.texture.minFilter = texture$1.minFilter;
  27156. this.texture.magFilter = texture$1.magFilter;
  27157. const geometry = new BoxGeometry( 5, 5, 5 );
  27158. const uvNode = equirectUV( positionWorldDirection );
  27159. const material = createNodeMaterialFromType( 'MeshBasicNodeMaterial' );
  27160. material.colorNode = texture( texture$1, uvNode, 0 );
  27161. material.side = BackSide;
  27162. material.blending = NoBlending;
  27163. const mesh = new Mesh( geometry, material );
  27164. const scene = new Scene();
  27165. scene.add( mesh );
  27166. // Avoid blurred poles
  27167. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27168. const camera = new CubeCamera( 1, 10, this );
  27169. camera.update( renderer, scene );
  27170. texture$1.minFilter = currentMinFilter;
  27171. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27172. mesh.geometry.dispose();
  27173. mesh.material.dispose();
  27174. return this;
  27175. }
  27176. }
  27177. // These defines must match with PMREMGenerator
  27178. const cubeUV_r0 = float( 1.0 );
  27179. const cubeUV_m0 = float( - 2.0 );
  27180. const cubeUV_r1 = float( 0.8 );
  27181. const cubeUV_m1 = float( - 1.0 );
  27182. const cubeUV_r4 = float( 0.4 );
  27183. const cubeUV_m4 = float( 2.0 );
  27184. const cubeUV_r5 = float( 0.305 );
  27185. const cubeUV_m5 = float( 3.0 );
  27186. const cubeUV_r6 = float( 0.21 );
  27187. const cubeUV_m6 = float( 4.0 );
  27188. const cubeUV_minMipLevel = float( 4.0 );
  27189. const cubeUV_minTileSize = float( 16.0 );
  27190. // These shader functions convert between the UV coordinates of a single face of
  27191. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  27192. // sampling a textureCube (not generally normalized ).
  27193. const getFace = tslFn( ( [ direction ] ) => {
  27194. const absDirection = vec3( abs( direction ) ).toVar();
  27195. const face = float( - 1.0 ).toVar();
  27196. If( absDirection.x.greaterThan( absDirection.z ), () => {
  27197. If( absDirection.x.greaterThan( absDirection.y ), () => {
  27198. face.assign( cond( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  27199. } ).else( () => {
  27200. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27201. } );
  27202. } ).else( () => {
  27203. If( absDirection.z.greaterThan( absDirection.y ), () => {
  27204. face.assign( cond( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  27205. } ).else( () => {
  27206. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27207. } );
  27208. } );
  27209. return face;
  27210. } ).setLayout( {
  27211. name: 'getFace',
  27212. type: 'float',
  27213. inputs: [
  27214. { name: 'direction', type: 'vec3' }
  27215. ]
  27216. } );
  27217. // RH coordinate system; PMREM face-indexing convention
  27218. const getUV = tslFn( ( [ direction, face ] ) => {
  27219. const uv = vec2().toVar();
  27220. If( face.equal( 0.0 ), () => {
  27221. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  27222. } ).elseif( face.equal( 1.0 ), () => {
  27223. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  27224. } ).elseif( face.equal( 2.0 ), () => {
  27225. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  27226. } ).elseif( face.equal( 3.0 ), () => {
  27227. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  27228. } ).elseif( face.equal( 4.0 ), () => {
  27229. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  27230. } ).else( () => {
  27231. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  27232. } );
  27233. return mul( 0.5, uv.add( 1.0 ) );
  27234. } ).setLayout( {
  27235. name: 'getUV',
  27236. type: 'vec2',
  27237. inputs: [
  27238. { name: 'direction', type: 'vec3' },
  27239. { name: 'face', type: 'float' }
  27240. ]
  27241. } );
  27242. const roughnessToMip = tslFn( ( [ roughness ] ) => {
  27243. const mip = float( 0.0 ).toVar();
  27244. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  27245. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  27246. } ).elseif( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  27247. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  27248. } ).elseif( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  27249. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  27250. } ).elseif( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  27251. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  27252. } ).else( () => {
  27253. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  27254. } );
  27255. return mip;
  27256. } ).setLayout( {
  27257. name: 'roughnessToMip',
  27258. type: 'float',
  27259. inputs: [
  27260. { name: 'roughness', type: 'float' }
  27261. ]
  27262. } );
  27263. // RH coordinate system; PMREM face-indexing convention
  27264. const getDirection = tslFn( ( [ uv_immutable, face ] ) => {
  27265. const uv = uv_immutable.toVar();
  27266. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  27267. const direction = vec3( uv, 1.0 ).toVar();
  27268. If( face.equal( 0.0 ), () => {
  27269. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  27270. } ).elseif( face.equal( 1.0 ), () => {
  27271. direction.assign( direction.xzy );
  27272. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  27273. } ).elseif( face.equal( 2.0 ), () => {
  27274. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  27275. } ).elseif( face.equal( 3.0 ), () => {
  27276. direction.assign( direction.zyx );
  27277. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  27278. } ).elseif( face.equal( 4.0 ), () => {
  27279. direction.assign( direction.xzy );
  27280. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  27281. } ).elseif( face.equal( 5.0 ), () => {
  27282. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  27283. } );
  27284. return direction;
  27285. } ).setLayout( {
  27286. name: 'getDirection',
  27287. type: 'vec3',
  27288. inputs: [
  27289. { name: 'uv', type: 'vec2' },
  27290. { name: 'face', type: 'float' }
  27291. ]
  27292. } );
  27293. //
  27294. const textureCubeUV = tslFn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27295. const roughness = float( roughness_immutable );
  27296. const sampleDir = vec3( sampleDir_immutable );
  27297. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  27298. const mipF = fract( mip );
  27299. const mipInt = floor( mip );
  27300. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27301. If( mipF.notEqual( 0.0 ), () => {
  27302. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27303. color0.assign( mix( color0, color1, mipF ) );
  27304. } );
  27305. return color0;
  27306. } );
  27307. const bilinearCubeUV = tslFn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27308. const mipInt = float( mipInt_immutable ).toVar();
  27309. const direction = vec3( direction_immutable );
  27310. const face = float( getFace( direction ) ).toVar();
  27311. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  27312. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  27313. const faceSize = float( exp2( mipInt ) ).toVar();
  27314. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  27315. If( face.greaterThan( 2.0 ), () => {
  27316. uv.y.addAssign( faceSize );
  27317. face.subAssign( 3.0 );
  27318. } );
  27319. uv.x.addAssign( face.mul( faceSize ) );
  27320. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  27321. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  27322. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  27323. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  27324. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  27325. } );
  27326. const getSample = tslFn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27327. const cosTheta = cos( theta );
  27328. // Rodrigues' axis-angle rotation
  27329. const sampleDirection = outputDirection.mul( cosTheta )
  27330. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  27331. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  27332. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  27333. } );
  27334. const blur = tslFn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27335. const axis = vec3( cond( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  27336. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  27337. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  27338. } );
  27339. axis.assign( normalize( axis ) );
  27340. const gl_FragColor = vec3().toVar();
  27341. 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 } ) ) );
  27342. loop( { start: int( 1 ), end: n }, ( { i } ) => {
  27343. If( i.greaterThanEqual( samples ), () => {
  27344. Break();
  27345. } );
  27346. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  27347. 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 } ) ) );
  27348. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  27349. } );
  27350. return vec4( gl_FragColor, 1 );
  27351. } );
  27352. const LOD_MIN = 4;
  27353. // The standard deviations (radians) associated with the extra mips. These are
  27354. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27355. // geometric shadowing function. These sigma values squared must match the
  27356. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27357. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27358. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27359. // samples and exit early, but not recompile the shader.
  27360. const MAX_SAMPLES = 20;
  27361. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  27362. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  27363. const _clearColor$1 = /*@__PURE__*/ new Color();
  27364. let _oldTarget = null;
  27365. let _oldActiveCubeFace = 0;
  27366. let _oldActiveMipmapLevel = 0;
  27367. // Golden Ratio
  27368. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27369. const INV_PHI = 1 / PHI;
  27370. // Vertices of a dodecahedron (except the opposites, which represent the
  27371. // same axis), used as axis directions evenly spread on a sphere.
  27372. const _axisDirections = [
  27373. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  27374. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27375. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27376. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27377. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27378. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27379. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27380. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27381. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27382. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  27383. ];
  27384. //
  27385. // WebGPU Face indices
  27386. const _faceLib = [
  27387. 3, 1, 5,
  27388. 0, 4, 2
  27389. ];
  27390. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  27391. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  27392. /**
  27393. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27394. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27395. * blur to be quickly accessed based on material roughness. It is packed into a
  27396. * special CubeUV format that allows us to perform custom interpolation so that
  27397. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27398. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27399. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27400. * higher roughness levels. In this way we maintain resolution to smoothly
  27401. * interpolate diffuse lighting while limiting sampling computation.
  27402. *
  27403. * Paper: Fast, Accurate Image-Based Lighting
  27404. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27405. */
  27406. class PMREMGenerator {
  27407. constructor( renderer ) {
  27408. this._renderer = renderer;
  27409. this._pingPongRenderTarget = null;
  27410. this._lodMax = 0;
  27411. this._cubeSize = 0;
  27412. this._lodPlanes = [];
  27413. this._sizeLods = [];
  27414. this._sigmas = [];
  27415. this._lodMeshes = [];
  27416. this._blurMaterial = null;
  27417. this._cubemapMaterial = null;
  27418. this._equirectMaterial = null;
  27419. this._backgroundBox = null;
  27420. }
  27421. /**
  27422. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27423. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27424. * in radians to be applied to the scene before PMREM generation. Optional near
  27425. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27426. * is placed at the origin).
  27427. */
  27428. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27429. _oldTarget = this._renderer.getRenderTarget();
  27430. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27431. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27432. this._setSize( 256 );
  27433. const cubeUVRenderTarget = this._allocateTargets();
  27434. cubeUVRenderTarget.depthBuffer = true;
  27435. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27436. if ( sigma > 0 ) {
  27437. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27438. }
  27439. this._applyPMREM( cubeUVRenderTarget );
  27440. this._cleanup( cubeUVRenderTarget );
  27441. return cubeUVRenderTarget;
  27442. }
  27443. /**
  27444. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27445. * or HDR. The ideal input image size is 1k (1024 x 512),
  27446. * as this matches best with the 256 x 256 cubemap output.
  27447. */
  27448. fromEquirectangular( equirectangular, renderTarget = null ) {
  27449. return this._fromTexture( equirectangular, renderTarget );
  27450. }
  27451. /**
  27452. * Generates a PMREM from an cubemap texture, which can be either LDR
  27453. * or HDR. The ideal input cube size is 256 x 256,
  27454. * as this matches best with the 256 x 256 cubemap output.
  27455. */
  27456. fromCubemap( cubemap, renderTarget = null ) {
  27457. return this._fromTexture( cubemap, renderTarget );
  27458. }
  27459. /**
  27460. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27461. * your texture's network fetch for increased concurrency.
  27462. */
  27463. compileCubemapShader() {
  27464. if ( this._cubemapMaterial === null ) {
  27465. this._cubemapMaterial = _getCubemapMaterial();
  27466. this._compileMaterial( this._cubemapMaterial );
  27467. }
  27468. }
  27469. /**
  27470. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27471. * your texture's network fetch for increased concurrency.
  27472. */
  27473. compileEquirectangularShader() {
  27474. if ( this._equirectMaterial === null ) {
  27475. this._equirectMaterial = _getEquirectMaterial();
  27476. this._compileMaterial( this._equirectMaterial );
  27477. }
  27478. }
  27479. /**
  27480. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27481. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27482. * one of them will cause any others to also become unusable.
  27483. */
  27484. dispose() {
  27485. this._dispose();
  27486. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  27487. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  27488. if ( this._backgroundBox !== null ) {
  27489. this._backgroundBox.geometry.dispose();
  27490. this._backgroundBox.material.dispose();
  27491. }
  27492. }
  27493. // private interface
  27494. _setSize( cubeSize ) {
  27495. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  27496. this._cubeSize = Math.pow( 2, this._lodMax );
  27497. }
  27498. _dispose() {
  27499. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  27500. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  27501. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  27502. this._lodPlanes[ i ].dispose();
  27503. }
  27504. }
  27505. _cleanup( outputTarget ) {
  27506. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  27507. outputTarget.scissorTest = false;
  27508. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27509. }
  27510. _fromTexture( texture, renderTarget ) {
  27511. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  27512. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  27513. } else { // Equirectangular
  27514. this._setSize( texture.image.width / 4 );
  27515. }
  27516. _oldTarget = this._renderer.getRenderTarget();
  27517. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27518. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27519. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  27520. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27521. this._applyPMREM( cubeUVRenderTarget );
  27522. this._cleanup( cubeUVRenderTarget );
  27523. return cubeUVRenderTarget;
  27524. }
  27525. _allocateTargets() {
  27526. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  27527. const height = 4 * this._cubeSize;
  27528. const params = {
  27529. magFilter: LinearFilter,
  27530. minFilter: LinearFilter,
  27531. generateMipmaps: false,
  27532. type: HalfFloatType,
  27533. format: RGBAFormat,
  27534. colorSpace: LinearSRGBColorSpace,
  27535. //depthBuffer: false
  27536. };
  27537. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  27538. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  27539. if ( this._pingPongRenderTarget !== null ) {
  27540. this._dispose();
  27541. }
  27542. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  27543. const { _lodMax } = this;
  27544. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  27545. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  27546. }
  27547. return cubeUVRenderTarget;
  27548. }
  27549. _compileMaterial( material ) {
  27550. const tmpMesh = this._lodMeshes[ 0 ];
  27551. tmpMesh.material = material;
  27552. this._renderer.compile( tmpMesh, _flatCamera );
  27553. }
  27554. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27555. const cubeCamera = _cubeCamera;
  27556. cubeCamera.near = near;
  27557. cubeCamera.far = far;
  27558. // px, py, pz, nx, ny, nz
  27559. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  27560. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27561. const renderer = this._renderer;
  27562. const originalAutoClear = renderer.autoClear;
  27563. renderer.getClearColor( _clearColor$1 );
  27564. renderer.autoClear = false;
  27565. let backgroundBox = this._backgroundBox;
  27566. if ( backgroundBox === null ) {
  27567. const backgroundMaterial = new MeshBasicMaterial( {
  27568. name: 'PMREM.Background',
  27569. side: BackSide,
  27570. depthWrite: false,
  27571. depthTest: false
  27572. } );
  27573. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27574. }
  27575. let useSolidColor = false;
  27576. const background = scene.background;
  27577. if ( background ) {
  27578. if ( background.isColor ) {
  27579. backgroundBox.material.color.copy( background );
  27580. scene.background = null;
  27581. useSolidColor = true;
  27582. }
  27583. } else {
  27584. backgroundBox.material.color.copy( _clearColor$1 );
  27585. useSolidColor = true;
  27586. }
  27587. renderer.setRenderTarget( cubeUVRenderTarget );
  27588. renderer.clear();
  27589. if ( useSolidColor ) {
  27590. renderer.render( backgroundBox, cubeCamera );
  27591. }
  27592. for ( let i = 0; i < 6; i ++ ) {
  27593. const col = i % 3;
  27594. if ( col === 0 ) {
  27595. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27596. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27597. } else if ( col === 1 ) {
  27598. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27599. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27600. } else {
  27601. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27602. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27603. }
  27604. const size = this._cubeSize;
  27605. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  27606. renderer.render( scene, cubeCamera );
  27607. }
  27608. renderer.autoClear = originalAutoClear;
  27609. scene.background = background;
  27610. }
  27611. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27612. const renderer = this._renderer;
  27613. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  27614. if ( isCubeTexture ) {
  27615. if ( this._cubemapMaterial === null ) {
  27616. this._cubemapMaterial = _getCubemapMaterial( texture );
  27617. }
  27618. } else {
  27619. if ( this._equirectMaterial === null ) {
  27620. this._equirectMaterial = _getEquirectMaterial( texture );
  27621. }
  27622. }
  27623. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  27624. material.fragmentNode.value = texture;
  27625. const mesh = this._lodMeshes[ 0 ];
  27626. mesh.material = material;
  27627. const size = this._cubeSize;
  27628. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  27629. renderer.setRenderTarget( cubeUVRenderTarget );
  27630. renderer.render( mesh, _flatCamera );
  27631. }
  27632. _applyPMREM( cubeUVRenderTarget ) {
  27633. const renderer = this._renderer;
  27634. const autoClear = renderer.autoClear;
  27635. renderer.autoClear = false;
  27636. const n = this._lodPlanes.length;
  27637. for ( let i = 1; i < n; i ++ ) {
  27638. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  27639. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  27640. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27641. }
  27642. renderer.autoClear = autoClear;
  27643. }
  27644. /**
  27645. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27646. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27647. * the blur latitudinally (around the poles), and then longitudinally (towards
  27648. * the poles) to approximate the orthogonally-separable blur. It is least
  27649. * accurate at the poles, but still does a decent job.
  27650. */
  27651. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27652. const pingPongRenderTarget = this._pingPongRenderTarget;
  27653. this._halfBlur(
  27654. cubeUVRenderTarget,
  27655. pingPongRenderTarget,
  27656. lodIn,
  27657. lodOut,
  27658. sigma,
  27659. 'latitudinal',
  27660. poleAxis );
  27661. this._halfBlur(
  27662. pingPongRenderTarget,
  27663. cubeUVRenderTarget,
  27664. lodOut,
  27665. lodOut,
  27666. sigma,
  27667. 'longitudinal',
  27668. poleAxis );
  27669. }
  27670. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27671. const renderer = this._renderer;
  27672. const blurMaterial = this._blurMaterial;
  27673. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27674. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  27675. }
  27676. // Number of standard deviations at which to cut off the discrete approximation.
  27677. const STANDARD_DEVIATIONS = 3;
  27678. const blurMesh = this._lodMeshes[ lodOut ];
  27679. blurMesh.material = blurMaterial;
  27680. const blurUniforms = blurMaterial.uniforms;
  27681. const pixels = this._sizeLods[ lodIn ] - 1;
  27682. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27683. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27684. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27685. if ( samples > MAX_SAMPLES ) {
  27686. console.warn( `sigmaRadians, ${
  27687. sigmaRadians}, is too large and will clip, as it requested ${
  27688. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27689. }
  27690. const weights = [];
  27691. let sum = 0;
  27692. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27693. const x = i / sigmaPixels;
  27694. const weight = Math.exp( - x * x / 2 );
  27695. weights.push( weight );
  27696. if ( i === 0 ) {
  27697. sum += weight;
  27698. } else if ( i < samples ) {
  27699. sum += 2 * weight;
  27700. }
  27701. }
  27702. for ( let i = 0; i < weights.length; i ++ ) {
  27703. weights[ i ] = weights[ i ] / sum;
  27704. }
  27705. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  27706. blurUniforms.envMap.value = targetIn.texture;
  27707. blurUniforms.samples.value = samples;
  27708. blurUniforms.weights.array = weights;
  27709. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  27710. if ( poleAxis ) {
  27711. blurUniforms.poleAxis.value = poleAxis;
  27712. }
  27713. const { _lodMax } = this;
  27714. blurUniforms.dTheta.value = radiansPerPixel;
  27715. blurUniforms.mipInt.value = _lodMax - lodIn;
  27716. const outputSize = this._sizeLods[ lodOut ];
  27717. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  27718. const y = 4 * ( this._cubeSize - outputSize );
  27719. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27720. renderer.setRenderTarget( targetOut );
  27721. renderer.render( blurMesh, _flatCamera );
  27722. }
  27723. }
  27724. function _createPlanes( lodMax ) {
  27725. const lodPlanes = [];
  27726. const sizeLods = [];
  27727. const sigmas = [];
  27728. const lodMeshes = [];
  27729. let lod = lodMax;
  27730. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27731. for ( let i = 0; i < totalLods; i ++ ) {
  27732. const sizeLod = Math.pow( 2, lod );
  27733. sizeLods.push( sizeLod );
  27734. let sigma = 1.0 / sizeLod;
  27735. if ( i > lodMax - LOD_MIN ) {
  27736. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  27737. } else if ( i === 0 ) {
  27738. sigma = 0;
  27739. }
  27740. sigmas.push( sigma );
  27741. const texelSize = 1.0 / ( sizeLod - 2 );
  27742. const min = - texelSize;
  27743. const max = 1 + texelSize;
  27744. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27745. const cubeFaces = 6;
  27746. const vertices = 6;
  27747. const positionSize = 3;
  27748. const uvSize = 2;
  27749. const faceIndexSize = 1;
  27750. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27751. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27752. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27753. for ( let face = 0; face < cubeFaces; face ++ ) {
  27754. const x = ( face % 3 ) * 2 / 3 - 1;
  27755. const y = face > 2 ? 0 : - 1;
  27756. const coordinates = [
  27757. x, y, 0,
  27758. x + 2 / 3, y, 0,
  27759. x + 2 / 3, y + 1, 0,
  27760. x, y, 0,
  27761. x + 2 / 3, y + 1, 0,
  27762. x, y + 1, 0
  27763. ];
  27764. const faceIdx = _faceLib[ face ];
  27765. position.set( coordinates, positionSize * vertices * faceIdx );
  27766. uv.set( uv1, uvSize * vertices * faceIdx );
  27767. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  27768. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  27769. }
  27770. const planes = new BufferGeometry();
  27771. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27772. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27773. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27774. lodPlanes.push( planes );
  27775. lodMeshes.push( new Mesh( planes, null ) );
  27776. if ( lod > LOD_MIN ) {
  27777. lod --;
  27778. }
  27779. }
  27780. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  27781. }
  27782. function _createRenderTarget( width, height, params ) {
  27783. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  27784. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27785. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27786. cubeUVRenderTarget.texture.isPMREMTexture = true;
  27787. cubeUVRenderTarget.scissorTest = true;
  27788. return cubeUVRenderTarget;
  27789. }
  27790. function _setViewport( target, x, y, width, height ) {
  27791. const viewY = target.height - height - y;
  27792. target.viewport.set( x, viewY, width, height );
  27793. target.scissor.set( x, viewY, width, height );
  27794. }
  27795. function _getMaterial() {
  27796. const material = new NodeMaterial();
  27797. material.depthTest = false;
  27798. material.depthWrite = false;
  27799. material.blending = NoBlending;
  27800. return material;
  27801. }
  27802. function _getBlurShader( lodMax, width, height ) {
  27803. const weights = uniforms( new Array( MAX_SAMPLES ).fill( 0 ) );
  27804. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  27805. const dTheta = uniform( 0 );
  27806. const n = float( MAX_SAMPLES );
  27807. const latitudinal = uniform( 0 ); // false, bool
  27808. const samples = uniform( 1 ); // int
  27809. const envMap = texture( null );
  27810. const mipInt = uniform( 0 ); // int
  27811. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  27812. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  27813. const CUBEUV_MAX_MIP = float( lodMax );
  27814. const materialUniforms = {
  27815. n,
  27816. latitudinal,
  27817. weights,
  27818. poleAxis,
  27819. outputDirection,
  27820. dTheta,
  27821. samples,
  27822. envMap,
  27823. mipInt,
  27824. CUBEUV_TEXEL_WIDTH,
  27825. CUBEUV_TEXEL_HEIGHT,
  27826. CUBEUV_MAX_MIP
  27827. };
  27828. const material = _getMaterial();
  27829. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  27830. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  27831. return material;
  27832. }
  27833. function _getCubemapMaterial( envTexture ) {
  27834. const material = _getMaterial();
  27835. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  27836. return material;
  27837. }
  27838. function _getEquirectMaterial( envTexture ) {
  27839. const material = _getMaterial();
  27840. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  27841. return material;
  27842. }
  27843. let _id$3 = 0;
  27844. class BindGroup {
  27845. constructor( name = '', bindings = [] ) {
  27846. this.name = name;
  27847. this.bindings = bindings;
  27848. this.id = _id$3 ++;
  27849. }
  27850. }
  27851. const rendererCache = new WeakMap();
  27852. const typeFromLength = new Map( [
  27853. [ 2, 'vec2' ],
  27854. [ 3, 'vec3' ],
  27855. [ 4, 'vec4' ],
  27856. [ 9, 'mat3' ],
  27857. [ 16, 'mat4' ]
  27858. ] );
  27859. const typeFromArray = new Map( [
  27860. [ Int8Array, 'int' ],
  27861. [ Int16Array, 'int' ],
  27862. [ Int32Array, 'int' ],
  27863. [ Uint8Array, 'uint' ],
  27864. [ Uint16Array, 'uint' ],
  27865. [ Uint32Array, 'uint' ],
  27866. [ Float32Array, 'float' ]
  27867. ] );
  27868. const toFloat = ( value ) => {
  27869. value = Number( value );
  27870. return value + ( value % 1 ? '' : '.0' );
  27871. };
  27872. class NodeBuilder {
  27873. constructor( object, renderer, parser ) {
  27874. this.object = object;
  27875. this.material = ( object && object.material ) || null;
  27876. this.geometry = ( object && object.geometry ) || null;
  27877. this.renderer = renderer;
  27878. this.parser = parser;
  27879. this.scene = null;
  27880. this.camera = null;
  27881. this.nodes = [];
  27882. this.updateNodes = [];
  27883. this.updateBeforeNodes = [];
  27884. this.updateAfterNodes = [];
  27885. this.hashNodes = {};
  27886. this.lightsNode = null;
  27887. this.environmentNode = null;
  27888. this.fogNode = null;
  27889. this.clippingContext = null;
  27890. this.vertexShader = null;
  27891. this.fragmentShader = null;
  27892. this.computeShader = null;
  27893. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  27894. this.flowCode = { vertex: '', fragment: '', compute: '' };
  27895. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  27896. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  27897. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  27898. this.bindingsIndexes = {};
  27899. this.bindGroups = null;
  27900. this.attributes = [];
  27901. this.bufferAttributes = [];
  27902. this.varyings = [];
  27903. this.codes = {};
  27904. this.vars = {};
  27905. this.flow = { code: '' };
  27906. this.chaining = [];
  27907. this.stack = stack();
  27908. this.stacks = [];
  27909. this.tab = '\t';
  27910. this.instanceBindGroups = true;
  27911. this.currentFunctionNode = null;
  27912. this.context = {
  27913. keywords: new NodeKeywords(),
  27914. material: this.material
  27915. };
  27916. this.cache = new NodeCache();
  27917. this.globalCache = this.cache;
  27918. this.flowsData = new WeakMap();
  27919. this.shaderStage = null;
  27920. this.buildStage = null;
  27921. }
  27922. getBingGroupsCache() {
  27923. let bindGroupsCache = rendererCache.get( this.renderer );
  27924. if ( bindGroupsCache === undefined ) {
  27925. bindGroupsCache = new ChainMap();
  27926. rendererCache.set( this.renderer, bindGroupsCache );
  27927. }
  27928. return bindGroupsCache;
  27929. }
  27930. createRenderTarget( width, height, options ) {
  27931. return new RenderTarget( width, height, options );
  27932. }
  27933. createCubeRenderTarget( size, options ) {
  27934. return new CubeRenderTarget( size, options );
  27935. }
  27936. createPMREMGenerator() {
  27937. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  27938. return new PMREMGenerator( this.renderer );
  27939. }
  27940. includes( node ) {
  27941. return this.nodes.includes( node );
  27942. }
  27943. _getBindGroup( groupName, bindings ) {
  27944. const bindGroupsCache = this.getBingGroupsCache();
  27945. //
  27946. const bindingsArray = [];
  27947. let sharedGroup = true;
  27948. for ( const binding of bindings ) {
  27949. bindingsArray.push( binding );
  27950. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  27951. }
  27952. //
  27953. let bindGroup;
  27954. if ( sharedGroup ) {
  27955. bindGroup = bindGroupsCache.get( bindingsArray );
  27956. if ( bindGroup === undefined ) {
  27957. bindGroup = new BindGroup( groupName, bindingsArray );
  27958. bindGroupsCache.set( bindingsArray, bindGroup );
  27959. }
  27960. } else {
  27961. bindGroup = new BindGroup( groupName, bindingsArray );
  27962. }
  27963. return bindGroup;
  27964. }
  27965. getBindGroupArray( groupName, shaderStage ) {
  27966. const bindings = this.bindings[ shaderStage ];
  27967. let bindGroup = bindings[ groupName ];
  27968. if ( bindGroup === undefined ) {
  27969. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  27970. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  27971. }
  27972. bindings[ groupName ] = bindGroup = [];
  27973. }
  27974. return bindGroup;
  27975. }
  27976. getBindings() {
  27977. let bindingsGroups = this.bindGroups;
  27978. if ( bindingsGroups === null ) {
  27979. const groups = {};
  27980. const bindings = this.bindings;
  27981. for ( const shaderStage of shaderStages ) {
  27982. for ( const groupName in bindings[ shaderStage ] ) {
  27983. const uniforms = bindings[ shaderStage ][ groupName ];
  27984. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  27985. groupUniforms.push( ...uniforms );
  27986. }
  27987. }
  27988. bindingsGroups = [];
  27989. for ( const groupName in groups ) {
  27990. const group = groups[ groupName ];
  27991. const bindingsGroup = this._getBindGroup( groupName, group );
  27992. bindingsGroups.push( bindingsGroup );
  27993. }
  27994. this.bindGroups = bindingsGroups;
  27995. }
  27996. return bindingsGroups;
  27997. }
  27998. setHashNode( node, hash ) {
  27999. this.hashNodes[ hash ] = node;
  28000. }
  28001. addNode( node ) {
  28002. if ( this.nodes.includes( node ) === false ) {
  28003. this.nodes.push( node );
  28004. this.setHashNode( node, node.getHash( this ) );
  28005. }
  28006. }
  28007. buildUpdateNodes() {
  28008. for ( const node of this.nodes ) {
  28009. const updateType = node.getUpdateType();
  28010. const updateBeforeType = node.getUpdateBeforeType();
  28011. const updateAfterType = node.getUpdateAfterType();
  28012. if ( updateType !== NodeUpdateType.NONE ) {
  28013. this.updateNodes.push( node.getSelf() );
  28014. }
  28015. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  28016. this.updateBeforeNodes.push( node );
  28017. }
  28018. if ( updateAfterType !== NodeUpdateType.NONE ) {
  28019. this.updateAfterNodes.push( node );
  28020. }
  28021. }
  28022. }
  28023. get currentNode() {
  28024. return this.chaining[ this.chaining.length - 1 ];
  28025. }
  28026. isFilteredTexture( texture ) {
  28027. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  28028. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  28029. }
  28030. addChain( node ) {
  28031. /*
  28032. if ( this.chaining.indexOf( node ) !== - 1 ) {
  28033. console.warn( 'Recursive node: ', node );
  28034. }
  28035. */
  28036. this.chaining.push( node );
  28037. }
  28038. removeChain( node ) {
  28039. const lastChain = this.chaining.pop();
  28040. if ( lastChain !== node ) {
  28041. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  28042. }
  28043. }
  28044. getMethod( method ) {
  28045. return method;
  28046. }
  28047. getNodeFromHash( hash ) {
  28048. return this.hashNodes[ hash ];
  28049. }
  28050. addFlow( shaderStage, node ) {
  28051. this.flowNodes[ shaderStage ].push( node );
  28052. return node;
  28053. }
  28054. setContext( context ) {
  28055. this.context = context;
  28056. }
  28057. getContext() {
  28058. return this.context;
  28059. }
  28060. getSharedContext() {
  28061. ({ ...this.context });
  28062. return this.context;
  28063. }
  28064. setCache( cache ) {
  28065. this.cache = cache;
  28066. }
  28067. getCache() {
  28068. return this.cache;
  28069. }
  28070. getCacheFromNode( node, parent = true ) {
  28071. const data = this.getDataFromNode( node );
  28072. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  28073. return data.cache;
  28074. }
  28075. isAvailable( /*name*/ ) {
  28076. return false;
  28077. }
  28078. getVertexIndex() {
  28079. console.warn( 'Abstract function.' );
  28080. }
  28081. getInstanceIndex() {
  28082. console.warn( 'Abstract function.' );
  28083. }
  28084. getDrawIndex() {
  28085. console.warn( 'Abstract function.' );
  28086. }
  28087. getFrontFacing() {
  28088. console.warn( 'Abstract function.' );
  28089. }
  28090. getFragCoord() {
  28091. console.warn( 'Abstract function.' );
  28092. }
  28093. isFlipY() {
  28094. return false;
  28095. }
  28096. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  28097. console.warn( 'Abstract function.' );
  28098. }
  28099. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  28100. console.warn( 'Abstract function.' );
  28101. }
  28102. generateConst( type, value = null ) {
  28103. if ( value === null ) {
  28104. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  28105. else if ( type === 'bool' ) value = false;
  28106. else if ( type === 'color' ) value = new Color();
  28107. else if ( type === 'vec2' ) value = new Vector2();
  28108. else if ( type === 'vec3' ) value = new Vector3();
  28109. else if ( type === 'vec4' ) value = new Vector4();
  28110. }
  28111. if ( type === 'float' ) return toFloat( value );
  28112. if ( type === 'int' ) return `${ Math.round( value ) }`;
  28113. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  28114. if ( type === 'bool' ) return value ? 'true' : 'false';
  28115. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  28116. const typeLength = this.getTypeLength( type );
  28117. const componentType = this.getComponentType( type );
  28118. const generateConst = value => this.generateConst( componentType, value );
  28119. if ( typeLength === 2 ) {
  28120. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  28121. } else if ( typeLength === 3 ) {
  28122. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  28123. } else if ( typeLength === 4 ) {
  28124. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  28125. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  28126. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  28127. } else if ( typeLength > 4 ) {
  28128. return `${ this.getType( type ) }()`;
  28129. }
  28130. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  28131. }
  28132. getType( type ) {
  28133. if ( type === 'color' ) return 'vec3';
  28134. return type;
  28135. }
  28136. hasGeometryAttribute( name ) {
  28137. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  28138. }
  28139. getAttribute( name, type ) {
  28140. const attributes = this.attributes;
  28141. // find attribute
  28142. for ( const attribute of attributes ) {
  28143. if ( attribute.name === name ) {
  28144. return attribute;
  28145. }
  28146. }
  28147. // create a new if no exist
  28148. const attribute = new NodeAttribute( name, type );
  28149. attributes.push( attribute );
  28150. return attribute;
  28151. }
  28152. getPropertyName( node/*, shaderStage*/ ) {
  28153. return node.name;
  28154. }
  28155. isVector( type ) {
  28156. return /vec\d/.test( type );
  28157. }
  28158. isMatrix( type ) {
  28159. return /mat\d/.test( type );
  28160. }
  28161. isReference( type ) {
  28162. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  28163. }
  28164. needsColorSpaceToLinear( /*texture*/ ) {
  28165. return false;
  28166. }
  28167. getComponentTypeFromTexture( texture ) {
  28168. const type = texture.type;
  28169. if ( texture.isDataTexture ) {
  28170. if ( type === IntType ) return 'int';
  28171. if ( type === UnsignedIntType ) return 'uint';
  28172. }
  28173. return 'float';
  28174. }
  28175. getElementType( type ) {
  28176. if ( type === 'mat2' ) return 'vec2';
  28177. if ( type === 'mat3' ) return 'vec3';
  28178. if ( type === 'mat4' ) return 'vec4';
  28179. return this.getComponentType( type );
  28180. }
  28181. getComponentType( type ) {
  28182. type = this.getVectorType( type );
  28183. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  28184. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  28185. if ( componentType === null ) return null;
  28186. if ( componentType[ 1 ] === 'b' ) return 'bool';
  28187. if ( componentType[ 1 ] === 'i' ) return 'int';
  28188. if ( componentType[ 1 ] === 'u' ) return 'uint';
  28189. return 'float';
  28190. }
  28191. getVectorType( type ) {
  28192. if ( type === 'color' ) return 'vec3';
  28193. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  28194. return type;
  28195. }
  28196. getTypeFromLength( length, componentType = 'float' ) {
  28197. if ( length === 1 ) return componentType;
  28198. const baseType = typeFromLength.get( length );
  28199. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  28200. return prefix + baseType;
  28201. }
  28202. getTypeFromArray( array ) {
  28203. return typeFromArray.get( array.constructor );
  28204. }
  28205. getTypeFromAttribute( attribute ) {
  28206. let dataAttribute = attribute;
  28207. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  28208. const array = dataAttribute.array;
  28209. const itemSize = attribute.itemSize;
  28210. const normalized = attribute.normalized;
  28211. let arrayType;
  28212. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  28213. arrayType = this.getTypeFromArray( array );
  28214. }
  28215. return this.getTypeFromLength( itemSize, arrayType );
  28216. }
  28217. getTypeLength( type ) {
  28218. const vecType = this.getVectorType( type );
  28219. const vecNum = /vec([2-4])/.exec( vecType );
  28220. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  28221. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  28222. if ( /mat2/.test( type ) === true ) return 4;
  28223. if ( /mat3/.test( type ) === true ) return 9;
  28224. if ( /mat4/.test( type ) === true ) return 16;
  28225. return 0;
  28226. }
  28227. getVectorFromMatrix( type ) {
  28228. return type.replace( 'mat', 'vec' );
  28229. }
  28230. changeComponentType( type, newComponentType ) {
  28231. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  28232. }
  28233. getIntegerType( type ) {
  28234. const componentType = this.getComponentType( type );
  28235. if ( componentType === 'int' || componentType === 'uint' ) return type;
  28236. return this.changeComponentType( type, 'int' );
  28237. }
  28238. addStack() {
  28239. this.stack = stack( this.stack );
  28240. this.stacks.push( getCurrentStack() || this.stack );
  28241. setCurrentStack( this.stack );
  28242. return this.stack;
  28243. }
  28244. removeStack() {
  28245. const lastStack = this.stack;
  28246. this.stack = lastStack.parent;
  28247. setCurrentStack( this.stacks.pop() );
  28248. return lastStack;
  28249. }
  28250. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  28251. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  28252. let nodeData = cache.getData( node );
  28253. if ( nodeData === undefined ) {
  28254. nodeData = {};
  28255. cache.setData( node, nodeData );
  28256. }
  28257. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  28258. return nodeData[ shaderStage ];
  28259. }
  28260. getNodeProperties( node, shaderStage = 'any' ) {
  28261. const nodeData = this.getDataFromNode( node, shaderStage );
  28262. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  28263. }
  28264. getBufferAttributeFromNode( node, type ) {
  28265. const nodeData = this.getDataFromNode( node );
  28266. let bufferAttribute = nodeData.bufferAttribute;
  28267. if ( bufferAttribute === undefined ) {
  28268. const index = this.uniforms.index ++;
  28269. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  28270. this.bufferAttributes.push( bufferAttribute );
  28271. nodeData.bufferAttribute = bufferAttribute;
  28272. }
  28273. return bufferAttribute;
  28274. }
  28275. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  28276. const nodeData = this.getDataFromNode( node, shaderStage );
  28277. if ( nodeData.structType === undefined ) {
  28278. const index = this.structs.index ++;
  28279. node.name = `StructType${ index }`;
  28280. this.structs[ shaderStage ].push( node );
  28281. nodeData.structType = node;
  28282. }
  28283. return node;
  28284. }
  28285. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  28286. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  28287. let nodeUniform = nodeData.uniform;
  28288. if ( nodeUniform === undefined ) {
  28289. const index = this.uniforms.index ++;
  28290. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  28291. this.uniforms[ shaderStage ].push( nodeUniform );
  28292. nodeData.uniform = nodeUniform;
  28293. }
  28294. return nodeUniform;
  28295. }
  28296. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  28297. const nodeData = this.getDataFromNode( node, shaderStage );
  28298. let nodeVar = nodeData.variable;
  28299. if ( nodeVar === undefined ) {
  28300. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  28301. if ( name === null ) name = 'nodeVar' + vars.length;
  28302. nodeVar = new NodeVar( name, type );
  28303. vars.push( nodeVar );
  28304. nodeData.variable = nodeVar;
  28305. }
  28306. return nodeVar;
  28307. }
  28308. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  28309. const nodeData = this.getDataFromNode( node, 'any' );
  28310. let nodeVarying = nodeData.varying;
  28311. if ( nodeVarying === undefined ) {
  28312. const varyings = this.varyings;
  28313. const index = varyings.length;
  28314. if ( name === null ) name = 'nodeVarying' + index;
  28315. nodeVarying = new NodeVarying( name, type );
  28316. varyings.push( nodeVarying );
  28317. nodeData.varying = nodeVarying;
  28318. }
  28319. return nodeVarying;
  28320. }
  28321. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  28322. const nodeData = this.getDataFromNode( node );
  28323. let nodeCode = nodeData.code;
  28324. if ( nodeCode === undefined ) {
  28325. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  28326. const index = codes.length;
  28327. nodeCode = new NodeCode( 'nodeCode' + index, type );
  28328. codes.push( nodeCode );
  28329. nodeData.code = nodeCode;
  28330. }
  28331. return nodeCode;
  28332. }
  28333. addLineFlowCode( code ) {
  28334. if ( code === '' ) return this;
  28335. code = this.tab + code;
  28336. if ( ! /;\s*$/.test( code ) ) {
  28337. code = code + ';\n';
  28338. }
  28339. this.flow.code += code;
  28340. return this;
  28341. }
  28342. addFlowCode( code ) {
  28343. this.flow.code += code;
  28344. return this;
  28345. }
  28346. addFlowTab() {
  28347. this.tab += '\t';
  28348. return this;
  28349. }
  28350. removeFlowTab() {
  28351. this.tab = this.tab.slice( 0, - 1 );
  28352. return this;
  28353. }
  28354. getFlowData( node/*, shaderStage*/ ) {
  28355. return this.flowsData.get( node );
  28356. }
  28357. flowNode( node ) {
  28358. const output = node.getNodeType( this );
  28359. const flowData = this.flowChildNode( node, output );
  28360. this.flowsData.set( node, flowData );
  28361. return flowData;
  28362. }
  28363. buildFunctionNode( shaderNode ) {
  28364. const fn = new FunctionNode();
  28365. const previous = this.currentFunctionNode;
  28366. this.currentFunctionNode = fn;
  28367. fn.code = this.buildFunctionCode( shaderNode );
  28368. this.currentFunctionNode = previous;
  28369. return fn;
  28370. }
  28371. flowShaderNode( shaderNode ) {
  28372. const layout = shaderNode.layout;
  28373. let inputs;
  28374. if ( shaderNode.isArrayInput ) {
  28375. inputs = [];
  28376. for ( const input of layout.inputs ) {
  28377. inputs.push( new ParameterNode( input.type, input.name ) );
  28378. }
  28379. } else {
  28380. inputs = {};
  28381. for ( const input of layout.inputs ) {
  28382. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  28383. }
  28384. }
  28385. //
  28386. shaderNode.layout = null;
  28387. const callNode = shaderNode.call( inputs );
  28388. const flowData = this.flowStagesNode( callNode, layout.type );
  28389. shaderNode.layout = layout;
  28390. return flowData;
  28391. }
  28392. flowStagesNode( node, output = null ) {
  28393. const previousFlow = this.flow;
  28394. const previousVars = this.vars;
  28395. const previousCache = this.cache;
  28396. const previousBuildStage = this.buildStage;
  28397. const previousStack = this.stack;
  28398. const flow = {
  28399. code: ''
  28400. };
  28401. this.flow = flow;
  28402. this.vars = {};
  28403. this.cache = new NodeCache();
  28404. this.stack = stack();
  28405. for ( const buildStage of defaultBuildStages ) {
  28406. this.setBuildStage( buildStage );
  28407. flow.result = node.build( this, output );
  28408. }
  28409. flow.vars = this.getVars( this.shaderStage );
  28410. this.flow = previousFlow;
  28411. this.vars = previousVars;
  28412. this.cache = previousCache;
  28413. this.stack = previousStack;
  28414. this.setBuildStage( previousBuildStage );
  28415. return flow;
  28416. }
  28417. getFunctionOperator() {
  28418. return null;
  28419. }
  28420. flowChildNode( node, output = null ) {
  28421. const previousFlow = this.flow;
  28422. const flow = {
  28423. code: ''
  28424. };
  28425. this.flow = flow;
  28426. flow.result = node.build( this, output );
  28427. this.flow = previousFlow;
  28428. return flow;
  28429. }
  28430. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  28431. const previousShaderStage = this.shaderStage;
  28432. this.setShaderStage( shaderStage );
  28433. const flowData = this.flowChildNode( node, output );
  28434. if ( propertyName !== null ) {
  28435. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  28436. }
  28437. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  28438. this.setShaderStage( previousShaderStage );
  28439. return flowData;
  28440. }
  28441. getAttributesArray() {
  28442. return this.attributes.concat( this.bufferAttributes );
  28443. }
  28444. getAttributes( /*shaderStage*/ ) {
  28445. console.warn( 'Abstract function.' );
  28446. }
  28447. getVaryings( /*shaderStage*/ ) {
  28448. console.warn( 'Abstract function.' );
  28449. }
  28450. getVar( type, name ) {
  28451. return `${ this.getType( type ) } ${ name }`;
  28452. }
  28453. getVars( shaderStage ) {
  28454. let snippet = '';
  28455. const vars = this.vars[ shaderStage ];
  28456. if ( vars !== undefined ) {
  28457. for ( const variable of vars ) {
  28458. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  28459. }
  28460. }
  28461. return snippet;
  28462. }
  28463. getUniforms( /*shaderStage*/ ) {
  28464. console.warn( 'Abstract function.' );
  28465. }
  28466. getCodes( shaderStage ) {
  28467. const codes = this.codes[ shaderStage ];
  28468. let code = '';
  28469. if ( codes !== undefined ) {
  28470. for ( const nodeCode of codes ) {
  28471. code += nodeCode.code + '\n';
  28472. }
  28473. }
  28474. return code;
  28475. }
  28476. getHash() {
  28477. return this.vertexShader + this.fragmentShader + this.computeShader;
  28478. }
  28479. setShaderStage( shaderStage ) {
  28480. this.shaderStage = shaderStage;
  28481. }
  28482. getShaderStage() {
  28483. return this.shaderStage;
  28484. }
  28485. setBuildStage( buildStage ) {
  28486. this.buildStage = buildStage;
  28487. }
  28488. getBuildStage() {
  28489. return this.buildStage;
  28490. }
  28491. buildCode() {
  28492. console.warn( 'Abstract function.' );
  28493. }
  28494. build() {
  28495. const { object, material } = this;
  28496. if ( material !== null ) {
  28497. NodeMaterial.fromMaterial( material ).build( this );
  28498. } else {
  28499. this.addFlow( 'compute', object );
  28500. }
  28501. // setup() -> stage 1: create possible new nodes and returns an output reference node
  28502. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  28503. // generate() -> stage 3: generate shader
  28504. for ( const buildStage of defaultBuildStages ) {
  28505. this.setBuildStage( buildStage );
  28506. if ( this.context.vertex && this.context.vertex.isNode ) {
  28507. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  28508. }
  28509. for ( const shaderStage of shaderStages ) {
  28510. this.setShaderStage( shaderStage );
  28511. const flowNodes = this.flowNodes[ shaderStage ];
  28512. for ( const node of flowNodes ) {
  28513. if ( buildStage === 'generate' ) {
  28514. this.flowNode( node );
  28515. } else {
  28516. node.build( this );
  28517. }
  28518. }
  28519. }
  28520. }
  28521. this.setBuildStage( null );
  28522. this.setShaderStage( null );
  28523. // stage 4: build code for a specific output
  28524. this.buildCode();
  28525. this.buildUpdateNodes();
  28526. return this;
  28527. }
  28528. getNodeUniform( uniformNode, type ) {
  28529. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  28530. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  28531. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  28532. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  28533. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  28534. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  28535. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  28536. throw new Error( `Uniform "${type}" not declared.` );
  28537. }
  28538. createNodeMaterial( type = 'NodeMaterial' ) {
  28539. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28540. return createNodeMaterialFromType( type );
  28541. }
  28542. format( snippet, fromType, toType ) {
  28543. fromType = this.getVectorType( fromType );
  28544. toType = this.getVectorType( toType );
  28545. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  28546. return snippet;
  28547. }
  28548. const fromTypeLength = this.getTypeLength( fromType );
  28549. const toTypeLength = this.getTypeLength( toType );
  28550. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  28551. // @TODO: ignore for now
  28552. return snippet;
  28553. }
  28554. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  28555. // @TODO: ignore for now
  28556. return snippet;
  28557. }
  28558. if ( fromTypeLength === toTypeLength ) {
  28559. return `${ this.getType( toType ) }( ${ snippet } )`;
  28560. }
  28561. if ( fromTypeLength > toTypeLength ) {
  28562. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  28563. }
  28564. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  28565. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  28566. }
  28567. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  28568. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  28569. }
  28570. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  28571. // convert a number value to vector type, e.g:
  28572. // vec3( 1u ) -> vec3( float( 1u ) )
  28573. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  28574. }
  28575. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  28576. }
  28577. getSignature() {
  28578. return `// Three.js r${ REVISION } - Node System\n`;
  28579. }
  28580. }
  28581. class NodeFrame {
  28582. constructor() {
  28583. this.time = 0;
  28584. this.deltaTime = 0;
  28585. this.frameId = 0;
  28586. this.renderId = 0;
  28587. this.startTime = null;
  28588. this.updateMap = new WeakMap();
  28589. this.updateBeforeMap = new WeakMap();
  28590. this.updateAfterMap = new WeakMap();
  28591. this.renderer = null;
  28592. this.material = null;
  28593. this.camera = null;
  28594. this.object = null;
  28595. this.scene = null;
  28596. }
  28597. _getMaps( referenceMap, nodeRef ) {
  28598. let maps = referenceMap.get( nodeRef );
  28599. if ( maps === undefined ) {
  28600. maps = {
  28601. renderMap: new WeakMap(),
  28602. frameMap: new WeakMap()
  28603. };
  28604. referenceMap.set( nodeRef, maps );
  28605. }
  28606. return maps;
  28607. }
  28608. updateBeforeNode( node ) {
  28609. const updateType = node.getUpdateBeforeType();
  28610. const reference = node.updateReference( this );
  28611. if ( updateType === NodeUpdateType.FRAME ) {
  28612. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  28613. if ( frameMap.get( reference ) !== this.frameId ) {
  28614. if ( node.updateBefore( this ) !== false ) {
  28615. frameMap.set( reference, this.frameId );
  28616. }
  28617. }
  28618. } else if ( updateType === NodeUpdateType.RENDER ) {
  28619. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  28620. if ( renderMap.get( reference ) !== this.renderId ) {
  28621. if ( node.updateBefore( this ) !== false ) {
  28622. renderMap.set( reference, this.renderId );
  28623. }
  28624. }
  28625. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28626. node.updateBefore( this );
  28627. }
  28628. }
  28629. updateAfterNode( node ) {
  28630. const updateType = node.getUpdateAfterType();
  28631. const reference = node.updateReference( this );
  28632. if ( updateType === NodeUpdateType.FRAME ) {
  28633. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  28634. if ( frameMap.get( reference ) !== this.frameId ) {
  28635. if ( node.updateAfter( this ) !== false ) {
  28636. frameMap.set( reference, this.frameId );
  28637. }
  28638. }
  28639. } else if ( updateType === NodeUpdateType.RENDER ) {
  28640. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  28641. if ( renderMap.get( reference ) !== this.renderId ) {
  28642. if ( node.updateAfter( this ) !== false ) {
  28643. renderMap.set( reference, this.renderId );
  28644. }
  28645. }
  28646. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28647. node.updateAfter( this );
  28648. }
  28649. }
  28650. updateNode( node ) {
  28651. const updateType = node.getUpdateType();
  28652. const reference = node.updateReference( this );
  28653. if ( updateType === NodeUpdateType.FRAME ) {
  28654. const { frameMap } = this._getMaps( this.updateMap, reference );
  28655. if ( frameMap.get( reference ) !== this.frameId ) {
  28656. if ( node.update( this ) !== false ) {
  28657. frameMap.set( reference, this.frameId );
  28658. }
  28659. }
  28660. } else if ( updateType === NodeUpdateType.RENDER ) {
  28661. const { renderMap } = this._getMaps( this.updateMap, reference );
  28662. if ( renderMap.get( reference ) !== this.renderId ) {
  28663. if ( node.update( this ) !== false ) {
  28664. renderMap.set( reference, this.renderId );
  28665. }
  28666. }
  28667. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28668. node.update( this );
  28669. }
  28670. }
  28671. update() {
  28672. this.frameId ++;
  28673. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  28674. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  28675. this.lastTime = performance.now();
  28676. this.time += this.deltaTime;
  28677. }
  28678. }
  28679. class NodeFunctionInput {
  28680. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  28681. this.type = type;
  28682. this.name = name;
  28683. this.count = count;
  28684. this.qualifier = qualifier;
  28685. this.isConst = isConst;
  28686. }
  28687. }
  28688. NodeFunctionInput.isNodeFunctionInput = true;
  28689. class StructTypeNode extends Node {
  28690. constructor( types ) {
  28691. super();
  28692. this.types = types;
  28693. this.isStructTypeNode = true;
  28694. }
  28695. getMemberTypes() {
  28696. return this.types;
  28697. }
  28698. }
  28699. addNodeClass( 'StructTypeNode', StructTypeNode );
  28700. class OutputStructNode extends Node {
  28701. constructor( ...members ) {
  28702. super();
  28703. this.members = members;
  28704. this.isOutputStructNode = true;
  28705. }
  28706. setup( builder ) {
  28707. super.setup( builder );
  28708. const members = this.members;
  28709. const types = [];
  28710. for ( let i = 0; i < members.length; i ++ ) {
  28711. types.push( members[ i ].getNodeType( builder ) );
  28712. }
  28713. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  28714. }
  28715. generate( builder, output ) {
  28716. const propertyName = builder.getOutputStructName();
  28717. const members = this.members;
  28718. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  28719. for ( let i = 0; i < members.length; i ++ ) {
  28720. const snippet = members[ i ].build( builder, output );
  28721. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  28722. }
  28723. return propertyName;
  28724. }
  28725. }
  28726. const outputStruct = nodeProxy( OutputStructNode );
  28727. addNodeClass( 'OutputStructNode', OutputStructNode );
  28728. function getTextureIndex( textures, name ) {
  28729. for ( let i = 0; i < textures.length; i ++ ) {
  28730. if ( textures[ i ].name === name ) {
  28731. return i;
  28732. }
  28733. }
  28734. return - 1;
  28735. }
  28736. class MRTNode extends OutputStructNode {
  28737. constructor( outputNodes ) {
  28738. super();
  28739. this.outputNodes = outputNodes;
  28740. this.isMRTNode = true;
  28741. }
  28742. merge( mrtNode ) {
  28743. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  28744. return mrt( outputs );
  28745. }
  28746. setup( builder ) {
  28747. const outputNodes = this.outputNodes;
  28748. const mrt = builder.renderer.getRenderTarget();
  28749. const members = [];
  28750. if ( Array.isArray( outputNodes ) ) {
  28751. for ( let i = 0; i < outputNodes.length; i ++ ) {
  28752. members.push( vec4( outputNodes[ i ] ) );
  28753. }
  28754. } else {
  28755. const textures = mrt.textures;
  28756. for ( const name in outputNodes ) {
  28757. const index = getTextureIndex( textures, name );
  28758. members[ index ] = vec4( outputNodes[ name ] );
  28759. }
  28760. }
  28761. this.members = members;
  28762. return super.setup( builder );
  28763. }
  28764. }
  28765. const mrt = nodeProxy( MRTNode );
  28766. addNodeClass( 'MRTNode', MRTNode );
  28767. class HashNode extends Node {
  28768. constructor( seedNode ) {
  28769. super();
  28770. this.seedNode = seedNode;
  28771. }
  28772. setup( /*builder*/ ) {
  28773. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  28774. const state = this.seedNode.toUint().mul( 747796405 ).add( 2891336453 );
  28775. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  28776. const result = word.shiftRight( 22 ).bitXor( word );
  28777. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  28778. }
  28779. }
  28780. const hash = nodeProxy( HashNode );
  28781. addNodeElement( 'hash', hash );
  28782. addNodeClass( 'HashNode', HashNode );
  28783. // remapping functions https://iquilezles.org/articles/functions/
  28784. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  28785. 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 ) );
  28786. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  28787. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  28788. addNodeElement( 'parabola', parabola );
  28789. addNodeElement( 'gain', gain );
  28790. addNodeElement( 'pcurve', pcurve );
  28791. addNodeElement( 'sinc', sinc );
  28792. // https://github.com/cabbibo/glsl-tri-noise-3d
  28793. const tri = tslFn( ( [ x ] ) => {
  28794. return x.fract().sub( .5 ).abs();
  28795. } );
  28796. const tri3 = tslFn( ( [ p ] ) => {
  28797. 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. ) ) ) ) );
  28798. } );
  28799. const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => {
  28800. const p = vec3( p_immutable ).toVar();
  28801. const z = float( 1.4 ).toVar();
  28802. const rz = float( 0.0 ).toVar();
  28803. const bp = vec3( p ).toVar();
  28804. loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  28805. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  28806. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  28807. bp.mulAssign( 1.8 );
  28808. z.mulAssign( 1.5 );
  28809. p.mulAssign( 1.2 );
  28810. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  28811. rz.addAssign( t.div( z ) );
  28812. bp.addAssign( 0.14 );
  28813. } );
  28814. return rz;
  28815. } );
  28816. // layouts
  28817. tri.setLayout( {
  28818. name: 'tri',
  28819. type: 'float',
  28820. inputs: [
  28821. { name: 'x', type: 'float' }
  28822. ]
  28823. } );
  28824. tri3.setLayout( {
  28825. name: 'tri3',
  28826. type: 'vec3',
  28827. inputs: [
  28828. { name: 'p', type: 'vec3' }
  28829. ]
  28830. } );
  28831. triNoise3D.setLayout( {
  28832. name: 'triNoise3D',
  28833. type: 'float',
  28834. inputs: [
  28835. { name: 'p', type: 'vec3' },
  28836. { name: 'spd', type: 'float' },
  28837. { name: 'time', type: 'float' }
  28838. ]
  28839. } );
  28840. let discardExpression;
  28841. class DiscardNode extends CondNode {
  28842. constructor( condNode ) {
  28843. discardExpression = discardExpression || expression( 'discard' );
  28844. super( condNode, discardExpression );
  28845. }
  28846. }
  28847. const inlineDiscard = nodeProxy( DiscardNode );
  28848. const discard = ( condNode ) => inlineDiscard( condNode ).append();
  28849. const Return = () => expression( 'return' ).append();
  28850. addNodeElement( 'discard', discard ); // @TODO: Check... this cause a little confusing using in chaining
  28851. addNodeClass( 'DiscardNode', DiscardNode );
  28852. class FunctionOverloadingNode extends Node {
  28853. constructor( functionNodes = [], ...parametersNodes ) {
  28854. super();
  28855. this.functionNodes = functionNodes;
  28856. this.parametersNodes = parametersNodes;
  28857. this._candidateFnCall = null;
  28858. this.global = true;
  28859. }
  28860. getNodeType() {
  28861. return this.functionNodes[ 0 ].shaderNode.layout.type;
  28862. }
  28863. setup( builder ) {
  28864. const params = this.parametersNodes;
  28865. let candidateFnCall = this._candidateFnCall;
  28866. if ( candidateFnCall === null ) {
  28867. let candidateFn = null;
  28868. let candidateScore = - 1;
  28869. for ( const functionNode of this.functionNodes ) {
  28870. const shaderNode = functionNode.shaderNode;
  28871. const layout = shaderNode.layout;
  28872. if ( layout === null ) {
  28873. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  28874. }
  28875. const inputs = layout.inputs;
  28876. if ( params.length === inputs.length ) {
  28877. let score = 0;
  28878. for ( let i = 0; i < params.length; i ++ ) {
  28879. const param = params[ i ];
  28880. const input = inputs[ i ];
  28881. if ( param.getNodeType( builder ) === input.type ) {
  28882. score ++;
  28883. } else {
  28884. score = 0;
  28885. }
  28886. }
  28887. if ( score > candidateScore ) {
  28888. candidateFn = functionNode;
  28889. candidateScore = score;
  28890. }
  28891. }
  28892. }
  28893. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  28894. }
  28895. return candidateFnCall;
  28896. }
  28897. }
  28898. const overloadingBaseFn = nodeProxy( FunctionOverloadingNode );
  28899. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  28900. addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode );
  28901. class MatcapUVNode extends TempNode {
  28902. constructor() {
  28903. super( 'vec2' );
  28904. }
  28905. setup() {
  28906. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28907. const y = positionViewDirection.cross( x );
  28908. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28909. }
  28910. }
  28911. const matcapUV = nodeImmutable( MatcapUVNode );
  28912. addNodeClass( 'MatcapUVNode', MatcapUVNode );
  28913. class TimerNode extends UniformNode {
  28914. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  28915. super( value );
  28916. this.scope = scope;
  28917. this.scale = scale;
  28918. this.updateType = NodeUpdateType.FRAME;
  28919. }
  28920. /*
  28921. @TODO:
  28922. getNodeType( builder ) {
  28923. const scope = this.scope;
  28924. if ( scope === TimerNode.FRAME ) {
  28925. return 'uint';
  28926. }
  28927. return 'float';
  28928. }
  28929. */
  28930. update( frame ) {
  28931. const scope = this.scope;
  28932. const scale = this.scale;
  28933. if ( scope === TimerNode.LOCAL ) {
  28934. this.value += frame.deltaTime * scale;
  28935. } else if ( scope === TimerNode.DELTA ) {
  28936. this.value = frame.deltaTime * scale;
  28937. } else if ( scope === TimerNode.FRAME ) {
  28938. this.value = frame.frameId;
  28939. } else {
  28940. // global
  28941. this.value = frame.time * scale;
  28942. }
  28943. }
  28944. serialize( data ) {
  28945. super.serialize( data );
  28946. data.scope = this.scope;
  28947. data.scale = this.scale;
  28948. }
  28949. deserialize( data ) {
  28950. super.deserialize( data );
  28951. this.scope = data.scope;
  28952. this.scale = data.scale;
  28953. }
  28954. }
  28955. TimerNode.LOCAL = 'local';
  28956. TimerNode.GLOBAL = 'global';
  28957. TimerNode.DELTA = 'delta';
  28958. TimerNode.FRAME = 'frame';
  28959. // @TODO: add support to use node in timeScale
  28960. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  28961. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  28962. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  28963. const frameId = nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  28964. addNodeClass( 'TimerNode', TimerNode );
  28965. class OscNode extends Node {
  28966. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  28967. super();
  28968. this.method = method;
  28969. this.timeNode = timeNode;
  28970. }
  28971. getNodeType( builder ) {
  28972. return this.timeNode.getNodeType( builder );
  28973. }
  28974. setup() {
  28975. const method = this.method;
  28976. const timeNode = nodeObject( this.timeNode );
  28977. let outputNode = null;
  28978. if ( method === OscNode.SINE ) {
  28979. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  28980. } else if ( method === OscNode.SQUARE ) {
  28981. outputNode = timeNode.fract().round();
  28982. } else if ( method === OscNode.TRIANGLE ) {
  28983. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  28984. } else if ( method === OscNode.SAWTOOTH ) {
  28985. outputNode = timeNode.fract();
  28986. }
  28987. return outputNode;
  28988. }
  28989. serialize( data ) {
  28990. super.serialize( data );
  28991. data.method = this.method;
  28992. }
  28993. deserialize( data ) {
  28994. super.deserialize( data );
  28995. this.method = data.method;
  28996. }
  28997. }
  28998. OscNode.SINE = 'sine';
  28999. OscNode.SQUARE = 'square';
  29000. OscNode.TRIANGLE = 'triangle';
  29001. OscNode.SAWTOOTH = 'sawtooth';
  29002. const oscSine = nodeProxy( OscNode, OscNode.SINE );
  29003. const oscSquare = nodeProxy( OscNode, OscNode.SQUARE );
  29004. const oscTriangle = nodeProxy( OscNode, OscNode.TRIANGLE );
  29005. const oscSawtooth = nodeProxy( OscNode, OscNode.SAWTOOTH );
  29006. addNodeClass( 'OscNode', OscNode );
  29007. class PackingNode extends TempNode {
  29008. constructor( scope, node ) {
  29009. super();
  29010. this.scope = scope;
  29011. this.node = node;
  29012. }
  29013. getNodeType( builder ) {
  29014. return this.node.getNodeType( builder );
  29015. }
  29016. setup() {
  29017. const { scope, node } = this;
  29018. let result = null;
  29019. if ( scope === PackingNode.DIRECTION_TO_COLOR ) {
  29020. result = node.mul( 0.5 ).add( 0.5 );
  29021. } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) {
  29022. result = node.mul( 2.0 ).sub( 1 );
  29023. }
  29024. return result;
  29025. }
  29026. }
  29027. PackingNode.DIRECTION_TO_COLOR = 'directionToColor';
  29028. PackingNode.COLOR_TO_DIRECTION = 'colorToDirection';
  29029. const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR );
  29030. const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION );
  29031. addNodeElement( 'directionToColor', directionToColor );
  29032. addNodeElement( 'colorToDirection', colorToDirection );
  29033. addNodeClass( 'PackingNode', PackingNode );
  29034. class RemapNode extends Node {
  29035. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  29036. super();
  29037. this.node = node;
  29038. this.inLowNode = inLowNode;
  29039. this.inHighNode = inHighNode;
  29040. this.outLowNode = outLowNode;
  29041. this.outHighNode = outHighNode;
  29042. this.doClamp = true;
  29043. }
  29044. setup() {
  29045. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  29046. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  29047. if ( doClamp === true ) t = t.clamp();
  29048. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  29049. }
  29050. }
  29051. const remap = nodeProxy( RemapNode, null, null, { doClamp: false } );
  29052. const remapClamp = nodeProxy( RemapNode );
  29053. addNodeElement( 'remap', remap );
  29054. addNodeElement( 'remapClamp', remapClamp );
  29055. addNodeClass( 'RemapNode', RemapNode );
  29056. class RotateUVNode extends TempNode {
  29057. constructor( uvNode, rotationNode, centerNode = vec2( 0.5 ) ) {
  29058. super( 'vec2' );
  29059. this.uvNode = uvNode;
  29060. this.rotationNode = rotationNode;
  29061. this.centerNode = centerNode;
  29062. }
  29063. setup() {
  29064. const { uvNode, rotationNode, centerNode } = this;
  29065. const vector = uvNode.sub( centerNode );
  29066. return vector.rotate( rotationNode ).add( centerNode );
  29067. }
  29068. }
  29069. const rotateUV = nodeProxy( RotateUVNode );
  29070. addNodeElement( 'rotateUV', rotateUV );
  29071. addNodeClass( 'RotateUVNode', RotateUVNode );
  29072. class RotateNode extends TempNode {
  29073. constructor( positionNode, rotationNode ) {
  29074. super();
  29075. this.positionNode = positionNode;
  29076. this.rotationNode = rotationNode;
  29077. }
  29078. getNodeType( builder ) {
  29079. return this.positionNode.getNodeType( builder );
  29080. }
  29081. setup( builder ) {
  29082. const { rotationNode, positionNode } = this;
  29083. const nodeType = this.getNodeType( builder );
  29084. if ( nodeType === 'vec2' ) {
  29085. const cosAngle = rotationNode.cos();
  29086. const sinAngle = rotationNode.sin();
  29087. const rotationMatrix = mat2(
  29088. cosAngle, sinAngle,
  29089. sinAngle.negate(), cosAngle
  29090. );
  29091. return rotationMatrix.mul( positionNode );
  29092. } else {
  29093. const rotation = rotationNode;
  29094. 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 ) );
  29095. 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 ) );
  29096. 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 ) );
  29097. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29098. }
  29099. }
  29100. }
  29101. const rotate = nodeProxy( RotateNode );
  29102. addNodeElement( 'rotate', rotate );
  29103. addNodeClass( 'RotateNode', RotateNode );
  29104. class SpriteSheetUVNode extends Node {
  29105. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  29106. super( 'vec2' );
  29107. this.countNode = countNode;
  29108. this.uvNode = uvNode;
  29109. this.frameNode = frameNode;
  29110. }
  29111. setup() {
  29112. const { frameNode, uvNode, countNode } = this;
  29113. const { width, height } = countNode;
  29114. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  29115. const column = frameNum.mod( width );
  29116. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  29117. const scale = countNode.reciprocal();
  29118. const uvFrameOffset = vec2( column, row );
  29119. return uvNode.add( uvFrameOffset ).mul( scale );
  29120. }
  29121. }
  29122. const spritesheetUV = nodeProxy( SpriteSheetUVNode );
  29123. addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode );
  29124. class StorageArrayElementNode extends ArrayElementNode {
  29125. constructor( storageBufferNode, indexNode ) {
  29126. super( storageBufferNode, indexNode );
  29127. this.isStorageArrayElementNode = true;
  29128. }
  29129. set storageBufferNode( value ) {
  29130. this.node = value;
  29131. }
  29132. get storageBufferNode() {
  29133. return this.node;
  29134. }
  29135. setup( builder ) {
  29136. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29137. if ( ! this.node.instanceIndex && this.node.bufferObject === true ) {
  29138. builder.setupPBO( this.node );
  29139. }
  29140. }
  29141. return super.setup( builder );
  29142. }
  29143. generate( builder, output ) {
  29144. let snippet;
  29145. const isAssignContext = builder.context.assign;
  29146. //
  29147. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29148. const { node } = this;
  29149. if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) {
  29150. snippet = builder.generatePBO( this );
  29151. } else {
  29152. snippet = node.build( builder );
  29153. }
  29154. } else {
  29155. snippet = super.generate( builder );
  29156. }
  29157. if ( isAssignContext !== true ) {
  29158. const type = this.getNodeType( builder );
  29159. snippet = builder.format( snippet, type, output );
  29160. }
  29161. return snippet;
  29162. }
  29163. }
  29164. const storageElement = nodeProxy( StorageArrayElementNode );
  29165. addNodeElement( 'storageElement', storageElement );
  29166. addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode );
  29167. class TriplanarTexturesNode extends Node {
  29168. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  29169. super( 'vec4' );
  29170. this.textureXNode = textureXNode;
  29171. this.textureYNode = textureYNode;
  29172. this.textureZNode = textureZNode;
  29173. this.scaleNode = scaleNode;
  29174. this.positionNode = positionNode;
  29175. this.normalNode = normalNode;
  29176. }
  29177. setup() {
  29178. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  29179. // Ref: https://github.com/keijiro/StandardTriplanar
  29180. // Blending factor of triplanar mapping
  29181. let bf = normalNode.abs().normalize();
  29182. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  29183. // Triplanar mapping
  29184. const tx = positionNode.yz.mul( scaleNode );
  29185. const ty = positionNode.zx.mul( scaleNode );
  29186. const tz = positionNode.xy.mul( scaleNode );
  29187. // Base color
  29188. const textureX = textureXNode.value;
  29189. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  29190. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  29191. const cx = texture( textureX, tx ).mul( bf.x );
  29192. const cy = texture( textureY, ty ).mul( bf.y );
  29193. const cz = texture( textureZ, tz ).mul( bf.z );
  29194. return add( cx, cy, cz );
  29195. }
  29196. }
  29197. const triplanarTextures = nodeProxy( TriplanarTexturesNode );
  29198. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  29199. addNodeElement( 'triplanarTexture', triplanarTexture );
  29200. addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode );
  29201. const _reflectorPlane = new Plane();
  29202. const _normal = new Vector3();
  29203. const _reflectorWorldPosition = new Vector3();
  29204. const _cameraWorldPosition = new Vector3();
  29205. const _rotationMatrix = new Matrix4();
  29206. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  29207. const clipPlane = new Vector4();
  29208. const _view = new Vector3();
  29209. const _target = new Vector3();
  29210. const _q = new Vector4();
  29211. const _size$4 = new Vector2();
  29212. const _defaultRT = new RenderTarget();
  29213. const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y );
  29214. let _inReflector = false;
  29215. class ReflectorNode extends TextureNode {
  29216. constructor( parameters = {} ) {
  29217. super( _defaultRT.texture, _defaultUV );
  29218. const {
  29219. target = new Object3D(),
  29220. resolution = 1,
  29221. generateMipmaps = false,
  29222. bounces = true
  29223. } = parameters;
  29224. //
  29225. this.target = target;
  29226. this.resolution = resolution;
  29227. this.generateMipmaps = generateMipmaps;
  29228. this.bounces = bounces;
  29229. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  29230. this.virtualCameras = new WeakMap();
  29231. this.renderTargets = new WeakMap();
  29232. }
  29233. _updateResolution( renderTarget, renderer ) {
  29234. const resolution = this.resolution;
  29235. renderer.getDrawingBufferSize( _size$4 );
  29236. renderTarget.setSize( Math.round( _size$4.width * resolution ), Math.round( _size$4.height * resolution ) );
  29237. }
  29238. setup( builder ) {
  29239. this._updateResolution( _defaultRT, builder.renderer );
  29240. return super.setup( builder );
  29241. }
  29242. getTextureNode() {
  29243. return this.textureNode;
  29244. }
  29245. getVirtualCamera( camera ) {
  29246. let virtualCamera = this.virtualCameras.get( camera );
  29247. if ( virtualCamera === undefined ) {
  29248. virtualCamera = camera.clone();
  29249. this.virtualCameras.set( camera, virtualCamera );
  29250. }
  29251. return virtualCamera;
  29252. }
  29253. getRenderTarget( camera ) {
  29254. let renderTarget = this.renderTargets.get( camera );
  29255. if ( renderTarget === undefined ) {
  29256. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  29257. if ( this.generateMipmaps === true ) {
  29258. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  29259. renderTarget.texture.generateMipmaps = true;
  29260. }
  29261. this.renderTargets.set( camera, renderTarget );
  29262. }
  29263. return renderTarget;
  29264. }
  29265. updateBefore( frame ) {
  29266. if ( this.bounces === false && _inReflector ) return false;
  29267. _inReflector = true;
  29268. const { scene, camera, renderer, material } = frame;
  29269. const { target } = this;
  29270. const virtualCamera = this.getVirtualCamera( camera );
  29271. const renderTarget = this.getRenderTarget( virtualCamera );
  29272. renderer.getDrawingBufferSize( _size$4 );
  29273. this._updateResolution( renderTarget, renderer );
  29274. //
  29275. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  29276. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  29277. _rotationMatrix.extractRotation( target.matrixWorld );
  29278. _normal.set( 0, 0, 1 );
  29279. _normal.applyMatrix4( _rotationMatrix );
  29280. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  29281. // Avoid rendering when reflector is facing away
  29282. if ( _view.dot( _normal ) > 0 ) return;
  29283. _view.reflect( _normal ).negate();
  29284. _view.add( _reflectorWorldPosition );
  29285. _rotationMatrix.extractRotation( camera.matrixWorld );
  29286. _lookAtPosition.set( 0, 0, - 1 );
  29287. _lookAtPosition.applyMatrix4( _rotationMatrix );
  29288. _lookAtPosition.add( _cameraWorldPosition );
  29289. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  29290. _target.reflect( _normal ).negate();
  29291. _target.add( _reflectorWorldPosition );
  29292. //
  29293. virtualCamera.coordinateSystem = camera.coordinateSystem;
  29294. virtualCamera.position.copy( _view );
  29295. virtualCamera.up.set( 0, 1, 0 );
  29296. virtualCamera.up.applyMatrix4( _rotationMatrix );
  29297. virtualCamera.up.reflect( _normal );
  29298. virtualCamera.lookAt( _target );
  29299. virtualCamera.near = camera.near;
  29300. virtualCamera.far = camera.far;
  29301. virtualCamera.updateMatrixWorld();
  29302. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  29303. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  29304. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  29305. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  29306. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  29307. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  29308. const projectionMatrix = virtualCamera.projectionMatrix;
  29309. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  29310. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  29311. _q.z = - 1.0;
  29312. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  29313. // Calculate the scaled plane vector
  29314. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  29315. const clipBias = 0;
  29316. // Replacing the third row of the projection matrix
  29317. projectionMatrix.elements[ 2 ] = clipPlane.x;
  29318. projectionMatrix.elements[ 6 ] = clipPlane.y;
  29319. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  29320. projectionMatrix.elements[ 14 ] = clipPlane.w;
  29321. //
  29322. this.value = renderTarget.texture;
  29323. material.visible = false;
  29324. const currentRenderTarget = renderer.getRenderTarget();
  29325. renderer.setRenderTarget( renderTarget );
  29326. renderer.render( scene, virtualCamera );
  29327. renderer.setRenderTarget( currentRenderTarget );
  29328. material.visible = true;
  29329. _inReflector = false;
  29330. }
  29331. }
  29332. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  29333. // Helper for passes that need to fill the viewport with a single quad.
  29334. const _camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  29335. // https://github.com/mrdoob/three.js/pull/21358
  29336. class QuadGeometry extends BufferGeometry {
  29337. constructor( flipY = false ) {
  29338. super();
  29339. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  29340. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  29341. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  29342. }
  29343. }
  29344. const _geometry = new QuadGeometry();
  29345. class QuadMesh extends Mesh {
  29346. constructor( material = null ) {
  29347. super( _geometry, material );
  29348. this.camera = _camera;
  29349. }
  29350. renderAsync( renderer ) {
  29351. return renderer.renderAsync( this, _camera );
  29352. }
  29353. render( renderer ) {
  29354. renderer.render( this, _camera );
  29355. }
  29356. }
  29357. const _size$3 = new Vector2();
  29358. class RTTNode extends TextureNode {
  29359. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  29360. const renderTarget = new RenderTarget( width, height, options );
  29361. super( renderTarget.texture, uv() );
  29362. this.node = node;
  29363. this.width = width;
  29364. this.height = height;
  29365. this.renderTarget = renderTarget;
  29366. this.textureNeedsUpdate = true;
  29367. this.autoUpdate = true;
  29368. this.updateMap = new WeakMap();
  29369. this._rttNode = null;
  29370. this._quadMesh = new QuadMesh( new NodeMaterial() );
  29371. this.updateBeforeType = NodeUpdateType.RENDER;
  29372. }
  29373. get autoSize() {
  29374. return this.width === null;
  29375. }
  29376. setup( builder ) {
  29377. this._rttNode = this.node.context( builder.getSharedContext() );
  29378. this._quadMesh.material.needsUpdate = true;
  29379. return super.setup( builder );
  29380. }
  29381. setSize( width, height ) {
  29382. this.width = width;
  29383. this.height = height;
  29384. const effectiveWidth = width * this.pixelRatio;
  29385. const effectiveHeight = height * this.pixelRatio;
  29386. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  29387. this.textureNeedsUpdate = true;
  29388. }
  29389. setPixelRatio( pixelRatio ) {
  29390. this.pixelRatio = pixelRatio;
  29391. this.setSize( this.width, this.height );
  29392. }
  29393. updateBefore( { renderer } ) {
  29394. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  29395. this.textureNeedsUpdate = false;
  29396. //
  29397. if ( this.autoSize === true ) {
  29398. this.pixelRatio = renderer.getPixelRatio();
  29399. const size = renderer.getSize( _size$3 );
  29400. this.setSize( size.width, size.height );
  29401. }
  29402. //
  29403. this._quadMesh.material.fragmentNode = this._rttNode;
  29404. //
  29405. const currentRenderTarget = renderer.getRenderTarget();
  29406. renderer.setRenderTarget( this.renderTarget );
  29407. this._quadMesh.render( renderer );
  29408. renderer.setRenderTarget( currentRenderTarget );
  29409. }
  29410. clone() {
  29411. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  29412. newNode.sampler = this.sampler;
  29413. newNode.referenceNode = this;
  29414. return newNode;
  29415. }
  29416. }
  29417. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  29418. addNodeElement( 'toTexture', ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ) );
  29419. addNodeClass( 'RTTNode', RTTNode );
  29420. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  29421. const bitangentGeometry = /*#__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  29422. const bitangentLocal = /*#__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  29423. const bitangentView = /*#__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  29424. const bitangentWorld = /*#__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  29425. const transformedBitangentView = /*#__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  29426. const transformedBitangentWorld = /*#__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  29427. const TBNViewMatrix = mat3( tangentView, bitangentView, normalView );
  29428. const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  29429. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  29430. const transformedBentNormalView = ( () => {
  29431. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  29432. let bentNormal = anisotropyB.cross( positionViewDirection );
  29433. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  29434. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  29435. return bentNormal;
  29436. } )();
  29437. class VertexColorNode extends AttributeNode {
  29438. constructor( index = 0 ) {
  29439. super( null, 'vec4' );
  29440. this.isVertexColorNode = true;
  29441. this.index = index;
  29442. }
  29443. getAttributeName( /*builder*/ ) {
  29444. const index = this.index;
  29445. return 'color' + ( index > 0 ? index : '' );
  29446. }
  29447. generate( builder ) {
  29448. const attributeName = this.getAttributeName( builder );
  29449. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  29450. let result;
  29451. if ( geometryAttribute === true ) {
  29452. result = super.generate( builder );
  29453. } else {
  29454. // Vertex color fallback should be white
  29455. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  29456. }
  29457. return result;
  29458. }
  29459. serialize( data ) {
  29460. super.serialize( data );
  29461. data.index = this.index;
  29462. }
  29463. deserialize( data ) {
  29464. super.deserialize( data );
  29465. this.index = data.index;
  29466. }
  29467. }
  29468. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  29469. addNodeClass( 'VertexColorNode', VertexColorNode );
  29470. class RendererReferenceNode extends ReferenceNode {
  29471. constructor( property, inputType, renderer = null ) {
  29472. super( property, inputType, renderer );
  29473. this.renderer = renderer;
  29474. }
  29475. updateReference( state ) {
  29476. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  29477. return this.reference;
  29478. }
  29479. }
  29480. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  29481. addNodeClass( 'RendererReferenceNode', RendererReferenceNode );
  29482. // Mipped Bicubic Texture Filtering by N8
  29483. // https://www.shadertoy.com/view/Dl2SDW
  29484. const bC = 1.0 / 6.0;
  29485. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  29486. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  29487. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  29488. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  29489. const g0 = ( a ) => w0( a ).add( w1( a ) );
  29490. const g1 = ( a ) => w2( a ).add( w3( a ) );
  29491. // h0 and h1 are the two offset functions
  29492. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  29493. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  29494. const bicubic = ( textureNode, texelSize, lod ) => {
  29495. const uv = textureNode.uvNode;
  29496. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  29497. const iuv = floor( uvScaled );
  29498. const fuv = fract( uvScaled );
  29499. const g0x = g0( fuv.x );
  29500. const g1x = g1( fuv.x );
  29501. const h0x = h0( fuv.x );
  29502. const h1x = h1( fuv.x );
  29503. const h0y = h0( fuv.y );
  29504. const h1y = h1( fuv.y );
  29505. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29506. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29507. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29508. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29509. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  29510. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  29511. return a.add( b );
  29512. };
  29513. const textureBicubicMethod = ( textureNode, lodNode ) => {
  29514. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  29515. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  29516. const fLodSizeInv = div( 1.0, fLodSize );
  29517. const cLodSizeInv = div( 1.0, cLodSize );
  29518. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  29519. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  29520. return fract( lodNode ).mix( fSample, cSample );
  29521. };
  29522. class TextureBicubicNode extends TempNode {
  29523. constructor( textureNode, blurNode = float( 3 ) ) {
  29524. super( 'vec4' );
  29525. this.textureNode = textureNode;
  29526. this.blurNode = blurNode;
  29527. }
  29528. setup() {
  29529. return textureBicubicMethod( this.textureNode, this.blurNode );
  29530. }
  29531. }
  29532. const textureBicubic = nodeProxy( TextureBicubicNode );
  29533. addNodeElement( 'bicubic', textureBicubic );
  29534. addNodeClass( 'TextureBicubicNode', TextureBicubicNode );
  29535. class PointUVNode extends Node {
  29536. constructor() {
  29537. super( 'vec2' );
  29538. this.isPointUVNode = true;
  29539. }
  29540. generate( /*builder*/ ) {
  29541. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  29542. }
  29543. }
  29544. const pointUV = nodeImmutable( PointUVNode );
  29545. addNodeClass( 'PointUVNode', PointUVNode );
  29546. class SceneNode extends Node {
  29547. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  29548. super();
  29549. this.scope = scope;
  29550. this.scene = scene;
  29551. }
  29552. setup( builder ) {
  29553. const scope = this.scope;
  29554. const scene = this.scene !== null ? this.scene : builder.scene;
  29555. let output;
  29556. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  29557. output = reference( 'backgroundBlurriness', 'float', scene );
  29558. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  29559. output = reference( 'backgroundIntensity', 'float', scene );
  29560. } else {
  29561. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  29562. }
  29563. return output;
  29564. }
  29565. }
  29566. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  29567. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  29568. const backgroundBlurriness = nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  29569. const backgroundIntensity = nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  29570. addNodeClass( 'SceneNode', SceneNode );
  29571. const GPUPrimitiveTopology = {
  29572. PointList: 'point-list',
  29573. LineList: 'line-list',
  29574. LineStrip: 'line-strip',
  29575. TriangleList: 'triangle-list',
  29576. TriangleStrip: 'triangle-strip',
  29577. };
  29578. const GPUCompareFunction = {
  29579. Never: 'never',
  29580. Less: 'less',
  29581. Equal: 'equal',
  29582. LessEqual: 'less-equal',
  29583. Greater: 'greater',
  29584. NotEqual: 'not-equal',
  29585. GreaterEqual: 'greater-equal',
  29586. Always: 'always'
  29587. };
  29588. const GPUStoreOp = {
  29589. Store: 'store',
  29590. Discard: 'discard'
  29591. };
  29592. const GPULoadOp = {
  29593. Load: 'load',
  29594. Clear: 'clear'
  29595. };
  29596. const GPUFrontFace = {
  29597. CCW: 'ccw',
  29598. CW: 'cw'
  29599. };
  29600. const GPUCullMode = {
  29601. None: 'none',
  29602. Front: 'front',
  29603. Back: 'back'
  29604. };
  29605. const GPUIndexFormat = {
  29606. Uint16: 'uint16',
  29607. Uint32: 'uint32'
  29608. };
  29609. const GPUTextureFormat = {
  29610. // 8-bit formats
  29611. R8Unorm: 'r8unorm',
  29612. R8Snorm: 'r8snorm',
  29613. R8Uint: 'r8uint',
  29614. R8Sint: 'r8sint',
  29615. // 16-bit formats
  29616. R16Uint: 'r16uint',
  29617. R16Sint: 'r16sint',
  29618. R16Float: 'r16float',
  29619. RG8Unorm: 'rg8unorm',
  29620. RG8Snorm: 'rg8snorm',
  29621. RG8Uint: 'rg8uint',
  29622. RG8Sint: 'rg8sint',
  29623. // 32-bit formats
  29624. R32Uint: 'r32uint',
  29625. R32Sint: 'r32sint',
  29626. R32Float: 'r32float',
  29627. RG16Uint: 'rg16uint',
  29628. RG16Sint: 'rg16sint',
  29629. RG16Float: 'rg16float',
  29630. RGBA8Unorm: 'rgba8unorm',
  29631. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  29632. RGBA8Snorm: 'rgba8snorm',
  29633. RGBA8Uint: 'rgba8uint',
  29634. RGBA8Sint: 'rgba8sint',
  29635. BGRA8Unorm: 'bgra8unorm',
  29636. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  29637. // Packed 32-bit formats
  29638. RGB9E5UFloat: 'rgb9e5ufloat',
  29639. RGB10A2Unorm: 'rgb10a2unorm',
  29640. RG11B10uFloat: 'rgb10a2unorm',
  29641. // 64-bit formats
  29642. RG32Uint: 'rg32uint',
  29643. RG32Sint: 'rg32sint',
  29644. RG32Float: 'rg32float',
  29645. RGBA16Uint: 'rgba16uint',
  29646. RGBA16Sint: 'rgba16sint',
  29647. RGBA16Float: 'rgba16float',
  29648. // 128-bit formats
  29649. RGBA32Uint: 'rgba32uint',
  29650. RGBA32Sint: 'rgba32sint',
  29651. RGBA32Float: 'rgba32float',
  29652. // Depth and stencil formats
  29653. Stencil8: 'stencil8',
  29654. Depth16Unorm: 'depth16unorm',
  29655. Depth24Plus: 'depth24plus',
  29656. Depth24PlusStencil8: 'depth24plus-stencil8',
  29657. Depth32Float: 'depth32float',
  29658. // 'depth32float-stencil8' extension
  29659. Depth32FloatStencil8: 'depth32float-stencil8',
  29660. // BC compressed formats usable if 'texture-compression-bc' is both
  29661. // supported by the device/user agent and enabled in requestDevice.
  29662. BC1RGBAUnorm: 'bc1-rgba-unorm',
  29663. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  29664. BC2RGBAUnorm: 'bc2-rgba-unorm',
  29665. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  29666. BC3RGBAUnorm: 'bc3-rgba-unorm',
  29667. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  29668. BC4RUnorm: 'bc4-r-unorm',
  29669. BC4RSnorm: 'bc4-r-snorm',
  29670. BC5RGUnorm: 'bc5-rg-unorm',
  29671. BC5RGSnorm: 'bc5-rg-snorm',
  29672. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  29673. BC6HRGBFloat: 'bc6h-rgb-float',
  29674. BC7RGBAUnorm: 'bc7-rgba-unorm',
  29675. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  29676. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  29677. // supported by the device/user agent and enabled in requestDevice.
  29678. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  29679. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  29680. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  29681. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  29682. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  29683. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  29684. EACR11Unorm: 'eac-r11unorm',
  29685. EACR11Snorm: 'eac-r11snorm',
  29686. EACRG11Unorm: 'eac-rg11unorm',
  29687. EACRG11Snorm: 'eac-rg11snorm',
  29688. // ASTC compressed formats usable if 'texture-compression-astc' is both
  29689. // supported by the device/user agent and enabled in requestDevice.
  29690. ASTC4x4Unorm: 'astc-4x4-unorm',
  29691. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  29692. ASTC5x4Unorm: 'astc-5x4-unorm',
  29693. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  29694. ASTC5x5Unorm: 'astc-5x5-unorm',
  29695. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  29696. ASTC6x5Unorm: 'astc-6x5-unorm',
  29697. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  29698. ASTC6x6Unorm: 'astc-6x6-unorm',
  29699. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  29700. ASTC8x5Unorm: 'astc-8x5-unorm',
  29701. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  29702. ASTC8x6Unorm: 'astc-8x6-unorm',
  29703. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  29704. ASTC8x8Unorm: 'astc-8x8-unorm',
  29705. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  29706. ASTC10x5Unorm: 'astc-10x5-unorm',
  29707. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  29708. ASTC10x6Unorm: 'astc-10x6-unorm',
  29709. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  29710. ASTC10x8Unorm: 'astc-10x8-unorm',
  29711. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  29712. ASTC10x10Unorm: 'astc-10x10-unorm',
  29713. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  29714. ASTC12x10Unorm: 'astc-12x10-unorm',
  29715. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  29716. ASTC12x12Unorm: 'astc-12x12-unorm',
  29717. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  29718. };
  29719. const GPUAddressMode = {
  29720. ClampToEdge: 'clamp-to-edge',
  29721. Repeat: 'repeat',
  29722. MirrorRepeat: 'mirror-repeat'
  29723. };
  29724. const GPUFilterMode = {
  29725. Linear: 'linear',
  29726. Nearest: 'nearest'
  29727. };
  29728. const GPUBlendFactor = {
  29729. Zero: 'zero',
  29730. One: 'one',
  29731. Src: 'src',
  29732. OneMinusSrc: 'one-minus-src',
  29733. SrcAlpha: 'src-alpha',
  29734. OneMinusSrcAlpha: 'one-minus-src-alpha',
  29735. Dst: 'dst',
  29736. OneMinusDstColor: 'one-minus-dst',
  29737. DstAlpha: 'dst-alpha',
  29738. OneMinusDstAlpha: 'one-minus-dst-alpha',
  29739. SrcAlphaSaturated: 'src-alpha-saturated',
  29740. Constant: 'constant',
  29741. OneMinusConstant: 'one-minus-constant'
  29742. };
  29743. const GPUBlendOperation = {
  29744. Add: 'add',
  29745. Subtract: 'subtract',
  29746. ReverseSubtract: 'reverse-subtract',
  29747. Min: 'min',
  29748. Max: 'max'
  29749. };
  29750. const GPUColorWriteFlags = {
  29751. None: 0,
  29752. Red: 0x1,
  29753. Green: 0x2,
  29754. Blue: 0x4,
  29755. Alpha: 0x8,
  29756. All: 0xF
  29757. };
  29758. const GPUStencilOperation = {
  29759. Keep: 'keep',
  29760. Zero: 'zero',
  29761. Replace: 'replace',
  29762. Invert: 'invert',
  29763. IncrementClamp: 'increment-clamp',
  29764. DecrementClamp: 'decrement-clamp',
  29765. IncrementWrap: 'increment-wrap',
  29766. DecrementWrap: 'decrement-wrap'
  29767. };
  29768. const GPUBufferBindingType = {
  29769. Uniform: 'uniform',
  29770. Storage: 'storage',
  29771. ReadOnlyStorage: 'read-only-storage'
  29772. };
  29773. const GPUStorageTextureAccess = {
  29774. WriteOnly: 'write-only',
  29775. ReadOnly: 'read-only',
  29776. ReadWrite: 'read-write',
  29777. };
  29778. const GPUTextureSampleType = {
  29779. Float: 'float',
  29780. UnfilterableFloat: 'unfilterable-float',
  29781. Depth: 'depth',
  29782. SInt: 'sint',
  29783. UInt: 'uint'
  29784. };
  29785. const GPUTextureDimension = {
  29786. OneD: '1d',
  29787. TwoD: '2d',
  29788. ThreeD: '3d'
  29789. };
  29790. const GPUTextureViewDimension = {
  29791. OneD: '1d',
  29792. TwoD: '2d',
  29793. TwoDArray: '2d-array',
  29794. Cube: 'cube',
  29795. CubeArray: 'cube-array',
  29796. ThreeD: '3d'
  29797. };
  29798. const GPUTextureAspect = {
  29799. All: 'all',
  29800. StencilOnly: 'stencil-only',
  29801. DepthOnly: 'depth-only'
  29802. };
  29803. const GPUInputStepMode = {
  29804. Vertex: 'vertex',
  29805. Instance: 'instance'
  29806. };
  29807. const GPUFeatureName = {
  29808. DepthClipControl: 'depth-clip-control',
  29809. Depth32FloatStencil8: 'depth32float-stencil8',
  29810. TextureCompressionBC: 'texture-compression-bc',
  29811. TextureCompressionETC2: 'texture-compression-etc2',
  29812. TextureCompressionASTC: 'texture-compression-astc',
  29813. TimestampQuery: 'timestamp-query',
  29814. IndirectFirstInstance: 'indirect-first-instance',
  29815. ShaderF16: 'shader-f16',
  29816. RG11B10UFloat: 'rg11b10ufloat-renderable',
  29817. BGRA8UNormStorage: 'bgra8unorm-storage',
  29818. Float32Filterable: 'float32-filterable'
  29819. };
  29820. class StorageBufferNode extends BufferNode {
  29821. constructor( value, bufferType, bufferCount = 0 ) {
  29822. super( value, bufferType, bufferCount );
  29823. this.isStorageBufferNode = true;
  29824. this.access = GPUBufferBindingType.Storage;
  29825. this.bufferObject = false;
  29826. this.bufferCount = bufferCount;
  29827. this._attribute = null;
  29828. this._varying = null;
  29829. this.global = true;
  29830. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  29831. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  29832. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  29833. else value.isStorageBufferAttribute = true;
  29834. }
  29835. }
  29836. getHash( builder ) {
  29837. if ( this.bufferCount === 0 ) {
  29838. let bufferData = builder.globalCache.getData( this.value );
  29839. if ( bufferData === undefined ) {
  29840. bufferData = {
  29841. node: this
  29842. };
  29843. builder.globalCache.setData( this.value, bufferData );
  29844. }
  29845. return bufferData.node.uuid;
  29846. }
  29847. return this.uuid;
  29848. }
  29849. getInputType( /*builder*/ ) {
  29850. return 'storageBuffer';
  29851. }
  29852. element( indexNode ) {
  29853. return storageElement( this, indexNode );
  29854. }
  29855. setBufferObject( value ) {
  29856. this.bufferObject = value;
  29857. return this;
  29858. }
  29859. setAccess( value ) {
  29860. this.access = value;
  29861. return this;
  29862. }
  29863. toReadOnly() {
  29864. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  29865. }
  29866. generate( builder ) {
  29867. if ( builder.isAvailable( 'storageBuffer' ) ) {
  29868. return super.generate( builder );
  29869. }
  29870. const nodeType = this.getNodeType( builder );
  29871. if ( this._attribute === null ) {
  29872. this._attribute = bufferAttribute( this.value );
  29873. this._varying = varying( this._attribute );
  29874. }
  29875. const output = this._varying.build( builder, nodeType );
  29876. builder.registerTransform( output, this._attribute );
  29877. return output;
  29878. }
  29879. }
  29880. // Read-Write Storage
  29881. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  29882. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  29883. addNodeClass( 'StorageBufferNode', StorageBufferNode );
  29884. class StorageTextureNode extends TextureNode {
  29885. constructor( value, uvNode, storeNode = null ) {
  29886. super( value, uvNode );
  29887. this.storeNode = storeNode;
  29888. this.isStorageTextureNode = true;
  29889. this.access = GPUStorageTextureAccess.WriteOnly;
  29890. }
  29891. getInputType( /*builder*/ ) {
  29892. return 'storageTexture';
  29893. }
  29894. setup( builder ) {
  29895. super.setup( builder );
  29896. const properties = builder.getNodeProperties( this );
  29897. properties.storeNode = this.storeNode;
  29898. }
  29899. setAccess( value ) {
  29900. this.access = value;
  29901. return this;
  29902. }
  29903. generate( builder, output ) {
  29904. let snippet;
  29905. if ( this.storeNode !== null ) {
  29906. snippet = this.generateStore( builder );
  29907. } else {
  29908. snippet = super.generate( builder, output );
  29909. }
  29910. return snippet;
  29911. }
  29912. toReadOnly() {
  29913. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  29914. }
  29915. toWriteOnly() {
  29916. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  29917. }
  29918. generateStore( builder ) {
  29919. const properties = builder.getNodeProperties( this );
  29920. const { uvNode, storeNode } = properties;
  29921. const textureProperty = super.generate( builder, 'property' );
  29922. const uvSnippet = uvNode.build( builder, 'uvec2' );
  29923. const storeSnippet = storeNode.build( builder, 'vec4' );
  29924. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  29925. builder.addLineFlowCode( snippet );
  29926. }
  29927. }
  29928. const storageTexture = nodeProxy( StorageTextureNode );
  29929. const textureStore = ( value, uvNode, storeNode ) => {
  29930. const node = storageTexture( value, uvNode, storeNode );
  29931. if ( storeNode !== null ) node.append();
  29932. return node;
  29933. };
  29934. addNodeClass( 'StorageTextureNode', StorageTextureNode );
  29935. const normal = tslFn( ( { texture, uv } ) => {
  29936. const epsilon = 0.0001;
  29937. const ret = vec3().temp();
  29938. If( uv.x.lessThan( epsilon ), () => {
  29939. ret.assign( vec3( 1, 0, 0 ) );
  29940. } ).elseif( uv.y.lessThan( epsilon ), () => {
  29941. ret.assign( vec3( 0, 1, 0 ) );
  29942. } ).elseif( uv.z.lessThan( epsilon ), () => {
  29943. ret.assign( vec3( 0, 0, 1 ) );
  29944. } ).elseif( uv.x.greaterThan( 1 - epsilon ), () => {
  29945. ret.assign( vec3( - 1, 0, 0 ) );
  29946. } ).elseif( uv.y.greaterThan( 1 - epsilon ), () => {
  29947. ret.assign( vec3( 0, - 1, 0 ) );
  29948. } ).elseif( uv.z.greaterThan( 1 - epsilon ), () => {
  29949. ret.assign( vec3( 0, 0, - 1 ) );
  29950. } ).else( () => {
  29951. const step = 0.01;
  29952. 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 );
  29953. 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 );
  29954. 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 );
  29955. ret.assign( vec3( x, y, z ) );
  29956. } );
  29957. return ret.normalize();
  29958. } );
  29959. class Texture3DNode extends TextureNode {
  29960. constructor( value, uvNode = null, levelNode = null ) {
  29961. super( value, uvNode, levelNode );
  29962. this.isTexture3DNode = true;
  29963. }
  29964. getInputType( /*builder*/ ) {
  29965. return 'texture3D';
  29966. }
  29967. getDefaultUV() {
  29968. return vec3( 0.5, 0.5, 0.5 );
  29969. }
  29970. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  29971. setupUV( builder, uvNode ) {
  29972. return uvNode;
  29973. }
  29974. generateUV( builder, uvNode ) {
  29975. return uvNode.build( builder, 'vec3' );
  29976. }
  29977. normal( uvNode ) {
  29978. return normal( { texture: this, uv: uvNode } );
  29979. }
  29980. }
  29981. const texture3D = nodeProxy( Texture3DNode );
  29982. addNodeClass( 'Texture3DNode', Texture3DNode );
  29983. class UserDataNode extends ReferenceNode {
  29984. constructor( property, inputType, userData = null ) {
  29985. super( property, inputType, userData );
  29986. this.userData = userData;
  29987. }
  29988. update( frame ) {
  29989. this.reference = this.userData !== null ? this.userData : frame.object.userData;
  29990. super.update( frame );
  29991. }
  29992. }
  29993. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  29994. addNodeClass( 'UserDataNode', UserDataNode );
  29995. const BurnNode = tslFn( ( { base, blend } ) => {
  29996. const fn = ( c ) => blend[ c ].lessThan( EPSILON ).cond( blend[ c ], base[ c ].oneMinus().div( blend[ c ] ).oneMinus().max( 0 ) );
  29997. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  29998. } ).setLayout( {
  29999. name: 'burnColor',
  30000. type: 'vec3',
  30001. inputs: [
  30002. { name: 'base', type: 'vec3' },
  30003. { name: 'blend', type: 'vec3' }
  30004. ]
  30005. } );
  30006. const DodgeNode = tslFn( ( { base, blend } ) => {
  30007. const fn = ( c ) => blend[ c ].equal( 1.0 ).cond( blend[ c ], base[ c ].div( blend[ c ].oneMinus() ).max( 0 ) );
  30008. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30009. } ).setLayout( {
  30010. name: 'dodgeColor',
  30011. type: 'vec3',
  30012. inputs: [
  30013. { name: 'base', type: 'vec3' },
  30014. { name: 'blend', type: 'vec3' }
  30015. ]
  30016. } );
  30017. const ScreenNode = tslFn( ( { base, blend } ) => {
  30018. const fn = ( c ) => base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus();
  30019. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30020. } ).setLayout( {
  30021. name: 'screenColor',
  30022. type: 'vec3',
  30023. inputs: [
  30024. { name: 'base', type: 'vec3' },
  30025. { name: 'blend', type: 'vec3' }
  30026. ]
  30027. } );
  30028. const OverlayNode = tslFn( ( { base, blend } ) => {
  30029. const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() );
  30030. //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) );
  30031. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30032. } ).setLayout( {
  30033. name: 'overlayColor',
  30034. type: 'vec3',
  30035. inputs: [
  30036. { name: 'base', type: 'vec3' },
  30037. { name: 'blend', type: 'vec3' }
  30038. ]
  30039. } );
  30040. class BlendModeNode extends TempNode {
  30041. constructor( blendMode, baseNode, blendNode ) {
  30042. super();
  30043. this.blendMode = blendMode;
  30044. this.baseNode = baseNode;
  30045. this.blendNode = blendNode;
  30046. }
  30047. setup() {
  30048. const { blendMode, baseNode, blendNode } = this;
  30049. const params = { base: baseNode, blend: blendNode };
  30050. let outputNode = null;
  30051. if ( blendMode === BlendModeNode.BURN ) {
  30052. outputNode = BurnNode( params );
  30053. } else if ( blendMode === BlendModeNode.DODGE ) {
  30054. outputNode = DodgeNode( params );
  30055. } else if ( blendMode === BlendModeNode.SCREEN ) {
  30056. outputNode = ScreenNode( params );
  30057. } else if ( blendMode === BlendModeNode.OVERLAY ) {
  30058. outputNode = OverlayNode( params );
  30059. }
  30060. return outputNode;
  30061. }
  30062. }
  30063. BlendModeNode.BURN = 'burn';
  30064. BlendModeNode.DODGE = 'dodge';
  30065. BlendModeNode.SCREEN = 'screen';
  30066. BlendModeNode.OVERLAY = 'overlay';
  30067. const burn = nodeProxy( BlendModeNode, BlendModeNode.BURN );
  30068. const dodge = nodeProxy( BlendModeNode, BlendModeNode.DODGE );
  30069. const overlay = nodeProxy( BlendModeNode, BlendModeNode.OVERLAY );
  30070. const screen = nodeProxy( BlendModeNode, BlendModeNode.SCREEN );
  30071. addNodeElement( 'burn', burn );
  30072. addNodeElement( 'dodge', dodge );
  30073. addNodeElement( 'overlay', overlay );
  30074. addNodeElement( 'screen', screen );
  30075. addNodeClass( 'BlendModeNode', BlendModeNode );
  30076. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  30077. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  30078. const dHdxy_fwd = tslFn( ( { textureNode, bumpScale } ) => {
  30079. // It's used to preserve the same TextureNode instance
  30080. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  30081. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  30082. return vec2(
  30083. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  30084. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  30085. ).mul( bumpScale );
  30086. } );
  30087. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  30088. const perturbNormalArb = tslFn( ( inputs ) => {
  30089. const { surf_pos, surf_norm, dHdxy } = inputs;
  30090. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  30091. const vSigmaX = surf_pos.dFdx().normalize();
  30092. const vSigmaY = surf_pos.dFdy().normalize();
  30093. const vN = surf_norm; // normalized
  30094. const R1 = vSigmaY.cross( vN );
  30095. const R2 = vN.cross( vSigmaX );
  30096. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  30097. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  30098. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  30099. } );
  30100. class BumpMapNode extends TempNode {
  30101. constructor( textureNode, scaleNode = null ) {
  30102. super( 'vec3' );
  30103. this.textureNode = textureNode;
  30104. this.scaleNode = scaleNode;
  30105. }
  30106. setup() {
  30107. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  30108. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  30109. return perturbNormalArb( {
  30110. surf_pos: positionView,
  30111. surf_norm: normalView,
  30112. dHdxy
  30113. } );
  30114. }
  30115. }
  30116. const bumpMap = nodeProxy( BumpMapNode );
  30117. addNodeElement( 'bumpMap', bumpMap );
  30118. addNodeClass( 'BumpMapNode', BumpMapNode );
  30119. const saturationNode = tslFn( ( { color, adjustment } ) => {
  30120. return adjustment.mix( luminance( color.rgb ), color.rgb );
  30121. } );
  30122. const vibranceNode = tslFn( ( { color, adjustment } ) => {
  30123. const average = add( color.r, color.g, color.b ).div( 3.0 );
  30124. const mx = color.r.max( color.g.max( color.b ) );
  30125. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  30126. return mix( color.rgb, mx, amt );
  30127. } );
  30128. const hueNode = tslFn( ( { color, adjustment } ) => {
  30129. const k = vec3( 0.57735, 0.57735, 0.57735 );
  30130. const cosAngle = adjustment.cos();
  30131. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  30132. } );
  30133. class ColorAdjustmentNode extends TempNode {
  30134. constructor( method, colorNode, adjustmentNode = float( 1 ) ) {
  30135. super( 'vec3' );
  30136. this.method = method;
  30137. this.colorNode = colorNode;
  30138. this.adjustmentNode = adjustmentNode;
  30139. }
  30140. setup() {
  30141. const { method, colorNode, adjustmentNode } = this;
  30142. const callParams = { color: colorNode, adjustment: adjustmentNode };
  30143. let outputNode = null;
  30144. if ( method === ColorAdjustmentNode.SATURATION ) {
  30145. outputNode = saturationNode( callParams );
  30146. } else if ( method === ColorAdjustmentNode.VIBRANCE ) {
  30147. outputNode = vibranceNode( callParams );
  30148. } else if ( method === ColorAdjustmentNode.HUE ) {
  30149. outputNode = hueNode( callParams );
  30150. } else {
  30151. console.error( `${ this.type }: Method "${ this.method }" not supported!` );
  30152. }
  30153. return outputNode;
  30154. }
  30155. }
  30156. ColorAdjustmentNode.SATURATION = 'saturation';
  30157. ColorAdjustmentNode.VIBRANCE = 'vibrance';
  30158. ColorAdjustmentNode.HUE = 'hue';
  30159. const saturation = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.SATURATION );
  30160. const vibrance = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.VIBRANCE );
  30161. const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE );
  30162. const lumaCoeffs = vec3( 0.2125, 0.7154, 0.0721 );
  30163. const luminance = ( color, luma = lumaCoeffs ) => dot( color, luma );
  30164. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  30165. addNodeElement( 'saturation', saturation );
  30166. addNodeElement( 'vibrance', vibrance );
  30167. addNodeElement( 'hue', hue );
  30168. addNodeElement( 'threshold', threshold );
  30169. addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode );
  30170. // Normal Mapping Without Precomputed Tangents
  30171. // http://www.thetenthplanet.de/archives/1180
  30172. const perturbNormal2Arb = tslFn( ( inputs ) => {
  30173. const { eye_pos, surf_norm, mapN, uv } = inputs;
  30174. const q0 = eye_pos.dFdx();
  30175. const q1 = eye_pos.dFdy();
  30176. const st0 = uv.dFdx();
  30177. const st1 = uv.dFdy();
  30178. const N = surf_norm; // normalized
  30179. const q1perp = q1.cross( N );
  30180. const q0perp = N.cross( q0 );
  30181. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  30182. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  30183. const det = T.dot( T ).max( B.dot( B ) );
  30184. const scale = faceDirection.mul( det.inverseSqrt() );
  30185. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  30186. } );
  30187. class NormalMapNode extends TempNode {
  30188. constructor( node, scaleNode = null ) {
  30189. super( 'vec3' );
  30190. this.node = node;
  30191. this.scaleNode = scaleNode;
  30192. this.normalMapType = TangentSpaceNormalMap;
  30193. }
  30194. setup( builder ) {
  30195. const { normalMapType, scaleNode } = this;
  30196. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  30197. if ( scaleNode !== null ) {
  30198. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  30199. }
  30200. let outputNode = null;
  30201. if ( normalMapType === ObjectSpaceNormalMap ) {
  30202. outputNode = modelNormalMatrix.mul( normalMap ).normalize();
  30203. } else if ( normalMapType === TangentSpaceNormalMap ) {
  30204. const tangent = builder.hasGeometryAttribute( 'tangent' );
  30205. if ( tangent === true ) {
  30206. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  30207. } else {
  30208. outputNode = perturbNormal2Arb( {
  30209. eye_pos: positionView,
  30210. surf_norm: normalView,
  30211. mapN: normalMap,
  30212. uv: uv()
  30213. } );
  30214. }
  30215. }
  30216. return outputNode;
  30217. }
  30218. }
  30219. const normalMap = nodeProxy( NormalMapNode );
  30220. addNodeElement( 'normalMap', normalMap );
  30221. addNodeClass( 'NormalMapNode', NormalMapNode );
  30222. class PosterizeNode extends TempNode {
  30223. constructor( sourceNode, stepsNode ) {
  30224. super();
  30225. this.sourceNode = sourceNode;
  30226. this.stepsNode = stepsNode;
  30227. }
  30228. setup() {
  30229. const { sourceNode, stepsNode } = this;
  30230. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  30231. }
  30232. }
  30233. const posterize = nodeProxy( PosterizeNode );
  30234. addNodeElement( 'posterize', posterize );
  30235. addNodeClass( 'PosterizeNode', PosterizeNode );
  30236. // exposure only
  30237. const LinearToneMappingNode = tslFn( ( { color, exposure } ) => {
  30238. return color.mul( exposure ).clamp();
  30239. } );
  30240. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  30241. const ReinhardToneMappingNode = tslFn( ( { color, exposure } ) => {
  30242. color = color.mul( exposure );
  30243. return color.div( color.add( 1.0 ) ).clamp();
  30244. } );
  30245. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  30246. const OptimizedCineonToneMappingNode = tslFn( ( { color, exposure } ) => {
  30247. // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
  30248. color = color.mul( exposure );
  30249. color = color.sub( 0.004 ).max( 0.0 );
  30250. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  30251. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  30252. return a.div( b ).pow( 2.2 );
  30253. } );
  30254. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30255. const RRTAndODTFit = tslFn( ( { color } ) => {
  30256. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  30257. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  30258. return a.div( b );
  30259. } );
  30260. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30261. const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => {
  30262. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  30263. const ACESInputMat = mat3(
  30264. 0.59719, 0.35458, 0.04823,
  30265. 0.07600, 0.90834, 0.01566,
  30266. 0.02840, 0.13383, 0.83777
  30267. );
  30268. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  30269. const ACESOutputMat = mat3(
  30270. 1.60475, - 0.53108, - 0.07367,
  30271. - 0.10208, 1.10813, - 0.00605,
  30272. - 0.00327, - 0.07276, 1.07602
  30273. );
  30274. color = color.mul( exposure ).div( 0.6 );
  30275. color = ACESInputMat.mul( color );
  30276. // Apply RRT and ODT
  30277. color = RRTAndODTFit( { color } );
  30278. color = ACESOutputMat.mul( color );
  30279. // Clamp to [0, 1]
  30280. return color.clamp();
  30281. } );
  30282. 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 ) );
  30283. 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 ) );
  30284. const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => {
  30285. const x = vec3( x_immutable ).toVar();
  30286. const x2 = vec3( x.mul( x ) ).toVar();
  30287. const x4 = vec3( x2.mul( x2 ) ).toVar();
  30288. 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 ) ) ) );
  30289. } );
  30290. const AGXToneMappingNode = tslFn( ( { color, exposure } ) => {
  30291. const colortone = vec3( color ).toVar();
  30292. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  30293. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  30294. const AgxMinEv = float( - 12.47393 );
  30295. const AgxMaxEv = float( 4.026069 );
  30296. colortone.mulAssign( exposure );
  30297. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  30298. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  30299. colortone.assign( max$1( colortone, 1e-10 ) );
  30300. colortone.assign( log2( colortone ) );
  30301. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  30302. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30303. colortone.assign( agxDefaultContrastApprox( colortone ) );
  30304. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  30305. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  30306. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  30307. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30308. return colortone;
  30309. } );
  30310. // https://modelviewer.dev/examples/tone-mapping
  30311. const NeutralToneMappingNode = tslFn( ( { color, exposure } ) => {
  30312. const StartCompression = float( 0.8 - 0.04 );
  30313. const Desaturation = float( 0.15 );
  30314. color = color.mul( exposure );
  30315. const x = min$1( color.r, min$1( color.g, color.b ) );
  30316. const offset = cond( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  30317. color.subAssign( offset );
  30318. const peak = max$1( color.r, max$1( color.g, color.b ) );
  30319. If( peak.lessThan( StartCompression ), () => {
  30320. return color;
  30321. } );
  30322. const d = sub( 1, StartCompression );
  30323. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  30324. color.mulAssign( newPeak.div( peak ) );
  30325. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  30326. return mix( color, vec3( newPeak ), g );
  30327. } ).setLayout( {
  30328. name: 'NeutralToneMapping',
  30329. type: 'vec3',
  30330. inputs: [
  30331. { name: 'color', type: 'vec3' },
  30332. { name: 'exposure', type: 'float' }
  30333. ]
  30334. } );
  30335. const toneMappingLib = {
  30336. [ LinearToneMapping ]: LinearToneMappingNode,
  30337. [ ReinhardToneMapping ]: ReinhardToneMappingNode,
  30338. [ CineonToneMapping ]: OptimizedCineonToneMappingNode,
  30339. [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode,
  30340. [ AgXToneMapping ]: AGXToneMappingNode,
  30341. [ NeutralToneMapping ]: NeutralToneMappingNode
  30342. };
  30343. class ToneMappingNode extends TempNode {
  30344. constructor( toneMapping = NoToneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  30345. super( 'vec3' );
  30346. this.toneMapping = toneMapping;
  30347. this.exposureNode = exposureNode;
  30348. this.colorNode = colorNode;
  30349. }
  30350. getCacheKey() {
  30351. let cacheKey = super.getCacheKey();
  30352. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  30353. return cacheKey;
  30354. }
  30355. setup( builder ) {
  30356. const colorNode = this.colorNode || builder.context.color;
  30357. const toneMapping = this.toneMapping;
  30358. if ( toneMapping === NoToneMapping ) return colorNode;
  30359. const toneMappingParams = { exposure: this.exposureNode, color: colorNode };
  30360. const toneMappingNode = toneMappingLib[ toneMapping ];
  30361. let outputNode = null;
  30362. if ( toneMappingNode ) {
  30363. outputNode = toneMappingNode( toneMappingParams );
  30364. } else {
  30365. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  30366. outputNode = colorNode;
  30367. }
  30368. return outputNode;
  30369. }
  30370. }
  30371. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  30372. const toneMappingExposure = rendererReference( 'toneMappingExposure', 'float' );
  30373. addNodeElement( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  30374. addNodeClass( 'ToneMappingNode', ToneMappingNode );
  30375. let _sharedFramebuffer = null;
  30376. class ViewportSharedTextureNode extends ViewportTextureNode {
  30377. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  30378. if ( _sharedFramebuffer === null ) {
  30379. _sharedFramebuffer = new FramebufferTexture();
  30380. }
  30381. super( uvNode, levelNode, _sharedFramebuffer );
  30382. }
  30383. updateReference() {
  30384. return this;
  30385. }
  30386. }
  30387. const viewportSharedTexture = nodeProxy( ViewportSharedTextureNode );
  30388. addNodeElement( 'viewportSharedTexture', viewportSharedTexture );
  30389. addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode );
  30390. const _size$2 = new Vector2();
  30391. class PassTextureNode extends TextureNode {
  30392. constructor( passNode, texture ) {
  30393. super( texture );
  30394. this.passNode = passNode;
  30395. this.setUpdateMatrix( false );
  30396. }
  30397. setup( builder ) {
  30398. this.passNode.build( builder );
  30399. return super.setup( builder );
  30400. }
  30401. clone() {
  30402. return new this.constructor( this.passNode, this.value );
  30403. }
  30404. }
  30405. class PassMultipleTextureNode extends PassTextureNode {
  30406. constructor( passNode, textureName ) {
  30407. super( passNode, null );
  30408. this.textureName = textureName;
  30409. }
  30410. setup( builder ) {
  30411. this.value = this.passNode.getTexture( this.textureName );
  30412. return super.setup( builder );
  30413. }
  30414. clone() {
  30415. return new this.constructor( this.passNode, this.textureName );
  30416. }
  30417. }
  30418. class PassNode extends TempNode {
  30419. constructor( scope, scene, camera, options = {} ) {
  30420. super( 'vec4' );
  30421. this.scope = scope;
  30422. this.scene = scene;
  30423. this.camera = camera;
  30424. this.options = options;
  30425. this._pixelRatio = 1;
  30426. this._width = 1;
  30427. this._height = 1;
  30428. const depthTexture = new DepthTexture();
  30429. depthTexture.isRenderTargetTexture = true;
  30430. //depthTexture.type = FloatType;
  30431. depthTexture.name = 'depth';
  30432. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  30433. renderTarget.texture.name = 'output';
  30434. renderTarget.depthTexture = depthTexture;
  30435. this.renderTarget = renderTarget;
  30436. this.updateBeforeType = NodeUpdateType.FRAME;
  30437. this._textures = {
  30438. output: renderTarget.texture,
  30439. depth: depthTexture
  30440. };
  30441. this._nodes = {};
  30442. this._linearDepthNode = null;
  30443. this._viewZNode = null;
  30444. this._cameraNear = uniform( 0 );
  30445. this._cameraFar = uniform( 0 );
  30446. this._mrt = null;
  30447. this.isPassNode = true;
  30448. }
  30449. setMRT( mrt ) {
  30450. this._mrt = mrt;
  30451. return this;
  30452. }
  30453. getMRT() {
  30454. return this._mrt;
  30455. }
  30456. isGlobal() {
  30457. return true;
  30458. }
  30459. getTexture( name ) {
  30460. let texture = this._textures[ name ];
  30461. if ( texture === undefined ) {
  30462. const refTexture = this.renderTarget.texture;
  30463. texture = refTexture.clone();
  30464. texture.isRenderTargetTexture = true;
  30465. texture.name = name;
  30466. this._textures[ name ] = texture;
  30467. this.renderTarget.textures.push( texture );
  30468. }
  30469. return texture;
  30470. }
  30471. getTextureNode( name = 'output' ) {
  30472. let textureNode = this._nodes[ name ];
  30473. if ( textureNode === undefined ) {
  30474. this._nodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  30475. }
  30476. return textureNode;
  30477. }
  30478. getViewZNode() {
  30479. if ( this._viewZNode === null ) {
  30480. const cameraNear = this._cameraNear;
  30481. const cameraFar = this._cameraFar;
  30482. this._viewZNode = perspectiveDepthToViewZ( this.getTextureNode( 'depth' ), cameraNear, cameraFar );
  30483. }
  30484. return this._viewZNode;
  30485. }
  30486. getLinearDepthNode() {
  30487. if ( this._linearDepthNode === null ) {
  30488. const cameraNear = this._cameraNear;
  30489. const cameraFar = this._cameraFar;
  30490. // TODO: just if ( builder.camera.isPerspectiveCamera )
  30491. this._linearDepthNode = viewZToOrthographicDepth( this.getViewZNode(), cameraNear, cameraFar );
  30492. }
  30493. return this._linearDepthNode;
  30494. }
  30495. setup( { renderer } ) {
  30496. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  30497. // Disable MSAA for WebGL backend for now
  30498. if ( renderer.backend.isWebGLBackend === true ) {
  30499. this.renderTarget.samples = 0;
  30500. }
  30501. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  30502. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  30503. }
  30504. updateBefore( frame ) {
  30505. const { renderer } = frame;
  30506. const { scene, camera } = this;
  30507. this._pixelRatio = renderer.getPixelRatio();
  30508. const size = renderer.getSize( _size$2 );
  30509. this.setSize( size.width, size.height );
  30510. const currentRenderTarget = renderer.getRenderTarget();
  30511. const currentMRT = renderer.getMRT();
  30512. this._cameraNear.value = camera.near;
  30513. this._cameraFar.value = camera.far;
  30514. renderer.setRenderTarget( this.renderTarget );
  30515. renderer.setMRT( this._mrt );
  30516. renderer.render( scene, camera );
  30517. renderer.setRenderTarget( currentRenderTarget );
  30518. renderer.setMRT( currentMRT );
  30519. }
  30520. setSize( width, height ) {
  30521. this._width = width;
  30522. this._height = height;
  30523. const effectiveWidth = this._width * this._pixelRatio;
  30524. const effectiveHeight = this._height * this._pixelRatio;
  30525. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  30526. }
  30527. setPixelRatio( pixelRatio ) {
  30528. this._pixelRatio = pixelRatio;
  30529. this.setSize( this._width, this._height );
  30530. }
  30531. dispose() {
  30532. this.renderTarget.dispose();
  30533. }
  30534. }
  30535. PassNode.COLOR = 'color';
  30536. PassNode.DEPTH = 'depth';
  30537. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  30538. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  30539. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  30540. addNodeClass( 'PassNode', PassNode );
  30541. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  30542. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  30543. const quadMesh1 = new QuadMesh();
  30544. const quadMesh2 = new QuadMesh();
  30545. class GaussianBlurNode extends TempNode {
  30546. constructor( textureNode, directionNode = null, sigma = 2 ) {
  30547. super( 'vec4' );
  30548. this.textureNode = textureNode;
  30549. this.directionNode = directionNode;
  30550. this.sigma = sigma;
  30551. this._invSize = uniform( new Vector2() );
  30552. this._passDirection = uniform( new Vector2() );
  30553. this._horizontalRT = new RenderTarget();
  30554. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  30555. this._verticalRT = new RenderTarget();
  30556. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  30557. this._textureNode = passTexture( this, this._verticalRT.texture );
  30558. this.updateBeforeType = NodeUpdateType.RENDER;
  30559. this.resolution = new Vector2( 1, 1 );
  30560. }
  30561. setSize( width, height ) {
  30562. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30563. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30564. this._invSize.value.set( 1 / width, 1 / height );
  30565. this._horizontalRT.setSize( width, height );
  30566. this._verticalRT.setSize( width, height );
  30567. }
  30568. updateBefore( frame ) {
  30569. const { renderer } = frame;
  30570. const textureNode = this.textureNode;
  30571. const map = textureNode.value;
  30572. const currentRenderTarget = renderer.getRenderTarget();
  30573. const currentMRT = renderer.getMRT();
  30574. const currentTexture = textureNode.value;
  30575. quadMesh1.material = this._material;
  30576. quadMesh2.material = this._material;
  30577. this.setSize( map.image.width, map.image.height );
  30578. const textureType = map.type;
  30579. this._horizontalRT.texture.type = textureType;
  30580. this._verticalRT.texture.type = textureType;
  30581. // clear
  30582. renderer.setMRT( null );
  30583. // horizontal
  30584. renderer.setRenderTarget( this._horizontalRT );
  30585. this._passDirection.value.set( 1, 0 );
  30586. quadMesh1.render( renderer );
  30587. // vertical
  30588. textureNode.value = this._horizontalRT.texture;
  30589. renderer.setRenderTarget( this._verticalRT );
  30590. this._passDirection.value.set( 0, 1 );
  30591. quadMesh2.render( renderer );
  30592. // restore
  30593. renderer.setRenderTarget( currentRenderTarget );
  30594. renderer.setMRT( currentMRT );
  30595. textureNode.value = currentTexture;
  30596. }
  30597. getTextureNode() {
  30598. return this._textureNode;
  30599. }
  30600. setup( builder ) {
  30601. const textureNode = this.textureNode;
  30602. if ( textureNode.isTextureNode !== true ) {
  30603. console.error( 'GaussianBlurNode requires a TextureNode.' );
  30604. return vec4();
  30605. }
  30606. //
  30607. const uvNode = textureNode.uvNode || uv();
  30608. const directionNode = vec2( this.directionNode || 1 );
  30609. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30610. const blur = tslFn( () => {
  30611. const kernelSize = 3 + ( 2 * this.sigma );
  30612. const gaussianCoefficients = this._getCoefficients( kernelSize );
  30613. const invSize = this._invSize;
  30614. const direction = directionNode.mul( this._passDirection );
  30615. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  30616. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  30617. for ( let i = 1; i < kernelSize; i ++ ) {
  30618. const x = float( i );
  30619. const w = float( gaussianCoefficients[ i ] );
  30620. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  30621. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  30622. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  30623. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  30624. weightSum.addAssign( mul( 2.0, w ) );
  30625. }
  30626. return diffuseSum.div( weightSum );
  30627. } );
  30628. //
  30629. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30630. material.fragmentNode = blur().context( builder.getSharedContext() );
  30631. material.needsUpdate = true;
  30632. //
  30633. const properties = builder.getNodeProperties( this );
  30634. properties.textureNode = textureNode;
  30635. //
  30636. return this._textureNode;
  30637. }
  30638. _getCoefficients( kernelRadius ) {
  30639. const coefficients = [];
  30640. for ( let i = 0; i < kernelRadius; i ++ ) {
  30641. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  30642. }
  30643. return coefficients;
  30644. }
  30645. }
  30646. const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( nodeObject( node ).toTexture(), directionNode, sigma ) );
  30647. addNodeElement( 'gaussianBlur', gaussianBlur );
  30648. const _size$1 = new Vector2();
  30649. const quadMeshComp = new QuadMesh();
  30650. class AfterImageNode extends TempNode {
  30651. constructor( textureNode, damp = 0.96 ) {
  30652. super( textureNode );
  30653. this.textureNode = textureNode;
  30654. this.textureNodeOld = texture();
  30655. this.damp = uniform( damp );
  30656. this._compRT = new RenderTarget();
  30657. this._compRT.texture.name = 'AfterImageNode.comp';
  30658. this._oldRT = new RenderTarget();
  30659. this._oldRT.texture.name = 'AfterImageNode.old';
  30660. this._textureNode = passTexture( this, this._compRT.texture );
  30661. this.updateBeforeType = NodeUpdateType.RENDER;
  30662. }
  30663. getTextureNode() {
  30664. return this._textureNode;
  30665. }
  30666. setSize( width, height ) {
  30667. this._compRT.setSize( width, height );
  30668. this._oldRT.setSize( width, height );
  30669. }
  30670. updateBefore( frame ) {
  30671. const { renderer } = frame;
  30672. const textureNode = this.textureNode;
  30673. const map = textureNode.value;
  30674. const textureType = map.type;
  30675. this._compRT.texture.type = textureType;
  30676. this._oldRT.texture.type = textureType;
  30677. renderer.getDrawingBufferSize( _size$1 );
  30678. this.setSize( _size$1.x, _size$1.y );
  30679. const currentRenderTarget = renderer.getRenderTarget();
  30680. const currentTexture = textureNode.value;
  30681. this.textureNodeOld.value = this._oldRT.texture;
  30682. // comp
  30683. renderer.setRenderTarget( this._compRT );
  30684. quadMeshComp.render( renderer );
  30685. // Swap the textures
  30686. const temp = this._oldRT;
  30687. this._oldRT = this._compRT;
  30688. this._compRT = temp;
  30689. renderer.setRenderTarget( currentRenderTarget );
  30690. textureNode.value = currentTexture;
  30691. }
  30692. setup( builder ) {
  30693. const textureNode = this.textureNode;
  30694. const textureNodeOld = this.textureNodeOld;
  30695. //
  30696. const uvNode = textureNode.uvNode || uv();
  30697. textureNodeOld.uvNode = uvNode;
  30698. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30699. const when_gt = tslFn( ( [ x_immutable, y_immutable ] ) => {
  30700. const y = float( y_immutable ).toVar();
  30701. const x = vec4( x_immutable ).toVar();
  30702. return max$1( sign( x.sub( y ) ), 0.0 );
  30703. } );
  30704. const afterImg = tslFn( () => {
  30705. const texelOld = vec4( textureNodeOld );
  30706. const texelNew = vec4( sampleTexture( uvNode ) );
  30707. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  30708. return max$1( texelNew, texelOld );
  30709. } );
  30710. //
  30711. const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() );
  30712. materialComposed.fragmentNode = afterImg();
  30713. quadMeshComp.material = materialComposed;
  30714. //
  30715. const properties = builder.getNodeProperties( this );
  30716. properties.textureNode = textureNode;
  30717. //
  30718. return this._textureNode;
  30719. }
  30720. }
  30721. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( node ).toTexture(), damp ) );
  30722. addNodeElement( 'afterImage', afterImage );
  30723. const quadMesh$1 = new QuadMesh();
  30724. class AnamorphicNode extends TempNode {
  30725. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  30726. super( 'vec4' );
  30727. this.textureNode = textureNode;
  30728. this.tresholdNode = tresholdNode;
  30729. this.scaleNode = scaleNode;
  30730. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  30731. this.samples = samples;
  30732. this.resolution = new Vector2( 1, 1 );
  30733. this._renderTarget = new RenderTarget();
  30734. this._renderTarget.texture.name = 'anamorphic';
  30735. this._invSize = uniform( new Vector2() );
  30736. this._textureNode = passTexture( this, this._renderTarget.texture );
  30737. this.updateBeforeType = NodeUpdateType.RENDER;
  30738. }
  30739. getTextureNode() {
  30740. return this._textureNode;
  30741. }
  30742. setSize( width, height ) {
  30743. this._invSize.value.set( 1 / width, 1 / height );
  30744. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30745. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30746. this._renderTarget.setSize( width, height );
  30747. }
  30748. updateBefore( frame ) {
  30749. const { renderer } = frame;
  30750. const textureNode = this.textureNode;
  30751. const map = textureNode.value;
  30752. this._renderTarget.texture.type = map.type;
  30753. const currentRenderTarget = renderer.getRenderTarget();
  30754. const currentTexture = textureNode.value;
  30755. quadMesh$1.material = this._material;
  30756. this.setSize( map.image.width, map.image.height );
  30757. // render
  30758. renderer.setRenderTarget( this._renderTarget );
  30759. quadMesh$1.render( renderer );
  30760. // restore
  30761. renderer.setRenderTarget( currentRenderTarget );
  30762. textureNode.value = currentTexture;
  30763. }
  30764. setup( builder ) {
  30765. const textureNode = this.textureNode;
  30766. const uvNode = textureNode.uvNode || uv();
  30767. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30768. const anamorph = tslFn( () => {
  30769. const samples = this.samples;
  30770. const halfSamples = Math.floor( samples / 2 );
  30771. const total = vec3( 0 ).toVar();
  30772. loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  30773. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  30774. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  30775. const color = sampleTexture( uv );
  30776. const pass = threshold( color, this.tresholdNode ).mul( softness );
  30777. total.addAssign( pass );
  30778. } );
  30779. return total.mul( this.colorNode );
  30780. } );
  30781. //
  30782. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30783. material.fragmentNode = anamorph();
  30784. //
  30785. const properties = builder.getNodeProperties( this );
  30786. properties.textureNode = textureNode;
  30787. //
  30788. return this._textureNode;
  30789. }
  30790. }
  30791. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ).toTexture(), nodeObject( threshold ), nodeObject( scale ), samples ) );
  30792. addNodeElement( 'anamorphic', anamorphic );
  30793. class SobelOperatorNode extends TempNode {
  30794. constructor( textureNode ) {
  30795. super();
  30796. this.textureNode = textureNode;
  30797. this.updateBeforeType = NodeUpdateType.RENDER;
  30798. this._invSize = uniform( new Vector2() );
  30799. }
  30800. updateBefore() {
  30801. const map = this.textureNode.value;
  30802. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  30803. }
  30804. setup() {
  30805. const { textureNode } = this;
  30806. const uvNode = textureNode.uvNode || uv();
  30807. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30808. const sobel = tslFn( () => {
  30809. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  30810. const texel = this._invSize;
  30811. // kernel definition (in glsl matrices are filled in column-major order)
  30812. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  30813. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  30814. // fetch the 3x3 neighbourhood of a fragment
  30815. // first column
  30816. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  30817. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  30818. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  30819. // second column
  30820. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  30821. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  30822. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  30823. // third column
  30824. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  30825. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  30826. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  30827. // gradient value in x direction
  30828. const valueGx = add(
  30829. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  30830. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  30831. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  30832. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  30833. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  30834. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  30835. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  30836. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  30837. Gx[ 2 ][ 2 ].mul( tx2y2 )
  30838. );
  30839. // gradient value in y direction
  30840. const valueGy = add(
  30841. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  30842. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  30843. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  30844. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  30845. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  30846. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  30847. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  30848. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  30849. Gy[ 2 ][ 2 ].mul( tx2y2 )
  30850. );
  30851. // magnitute of the total gradient
  30852. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  30853. return vec4( vec3( G ), 1 );
  30854. } );
  30855. const outputNode = sobel();
  30856. return outputNode;
  30857. }
  30858. }
  30859. const sobel = ( node ) => nodeObject( new SobelOperatorNode( nodeObject( node ).toTexture() ) );
  30860. addNodeElement( 'sobel', sobel );
  30861. class DepthOfFieldNode extends TempNode {
  30862. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  30863. super();
  30864. this.textureNode = textureNode;
  30865. this.viewZNode = viewZNode;
  30866. this.focusNode = focusNode;
  30867. this.apertureNode = apertureNode;
  30868. this.maxblurNode = maxblurNode;
  30869. this._aspect = uniform( 0 );
  30870. this.updateBeforeType = NodeUpdateType.RENDER;
  30871. }
  30872. updateBefore() {
  30873. const map = this.textureNode.value;
  30874. this._aspect.value = map.image.width / map.image.height;
  30875. }
  30876. setup() {
  30877. const textureNode = this.textureNode;
  30878. const uvNode = textureNode.uvNode || uv();
  30879. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30880. const dof = tslFn( () => {
  30881. const aspectcorrect = vec2( 1.0, this._aspect );
  30882. const factor = this.focusNode.add( this.viewZNode );
  30883. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  30884. const dofblur9 = dofblur.mul( 0.9 );
  30885. const dofblur7 = dofblur.mul( 0.7 );
  30886. const dofblur4 = dofblur.mul( 0.4 );
  30887. let col = vec4( 0.0 );
  30888. col = col.add( sampleTexture( uvNode ) );
  30889. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30890. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30891. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30892. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30893. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30894. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30895. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30896. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30897. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30898. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30899. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30900. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30901. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30902. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30903. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30904. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  30905. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30906. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30907. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30908. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30909. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30910. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30911. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30912. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  30913. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30914. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30915. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30916. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30917. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30918. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30919. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30920. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  30921. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30922. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30923. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30924. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30925. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30926. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30927. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30928. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  30929. col = col.div( 41 );
  30930. col.a = 1;
  30931. return vec4( col );
  30932. } );
  30933. const outputNode = dof();
  30934. return outputNode;
  30935. }
  30936. }
  30937. 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 ) ) );
  30938. addNodeElement( 'dof', dof );
  30939. class DotScreenNode extends TempNode {
  30940. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  30941. super( 'vec4' );
  30942. this.inputNode = inputNode;
  30943. this.center = uniform( center );
  30944. this.angle = uniform( angle );
  30945. this.scale = uniform( scale );
  30946. this._size = uniform( new Vector2() );
  30947. this.updateBeforeType = NodeUpdateType.RENDER;
  30948. }
  30949. updateBefore() {
  30950. const map = this.inputNode.value;
  30951. this._size.value.set( map.image.width, map.image.height );
  30952. }
  30953. setup() {
  30954. const inputNode = this.inputNode;
  30955. const pattern = tslFn( () => {
  30956. const s = sin( this.angle );
  30957. const c = cos( this.angle );
  30958. const tex = uv().mul( this._size ).sub( this.center );
  30959. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  30960. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  30961. } );
  30962. const dotScreen = tslFn( () => {
  30963. const color = inputNode;
  30964. const average = add( color.r, color.g, color.b ).div( 3 );
  30965. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  30966. } );
  30967. const outputNode = dotScreen();
  30968. return outputNode;
  30969. }
  30970. }
  30971. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  30972. addNodeElement( 'dotScreen', dotScreen );
  30973. class RGBShiftNode extends TempNode {
  30974. constructor( textureNode, amount = 0.005, angle = 0 ) {
  30975. super( 'vec4' );
  30976. this.textureNode = textureNode;
  30977. this.amount = uniform( amount );
  30978. this.angle = uniform( angle );
  30979. }
  30980. setup() {
  30981. const { textureNode } = this;
  30982. const uvNode = textureNode.uvNode || uv();
  30983. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30984. const rgbShift = tslFn( () => {
  30985. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  30986. const cr = sampleTexture( uvNode.add( offset ) );
  30987. const cga = sampleTexture( uvNode );
  30988. const cb = sampleTexture( uvNode.sub( offset ) );
  30989. return vec4( cr.r, cga.g, cb.b, cga.a );
  30990. } );
  30991. return rgbShift();
  30992. }
  30993. }
  30994. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( nodeObject( node ).toTexture(), amount, angle ) );
  30995. addNodeElement( 'rgbShift', rgbShift );
  30996. class FilmNode extends TempNode {
  30997. constructor( inputNode, intensityNode = null, uvNode = null ) {
  30998. super();
  30999. this.inputNode = inputNode;
  31000. this.intensityNode = intensityNode;
  31001. this.uvNode = uvNode;
  31002. }
  31003. setup() {
  31004. const uvNode = this.uvNode || uv();
  31005. const film = tslFn( () => {
  31006. const base = this.inputNode.rgb;
  31007. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  31008. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  31009. if ( this.intensityNode !== null ) {
  31010. color = mix( base, color, this.intensityNode );
  31011. }
  31012. return vec4( color, this.inputNode.a );
  31013. } );
  31014. const outputNode = film();
  31015. return outputNode;
  31016. }
  31017. }
  31018. const film = nodeProxy( FilmNode );
  31019. addNodeElement( 'film', film );
  31020. class Lut3DNode extends TempNode {
  31021. constructor( inputNode, lutNode, size, intensityNode ) {
  31022. super();
  31023. this.inputNode = inputNode;
  31024. this.lutNode = lutNode;
  31025. this.size = uniform( size );
  31026. this.intensityNode = intensityNode;
  31027. }
  31028. setup() {
  31029. const { inputNode, lutNode } = this;
  31030. const sampleLut = ( uv ) => lutNode.uv( uv );
  31031. const lut3D = tslFn( () => {
  31032. const base = inputNode;
  31033. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  31034. const pixelWidth = float( 1.0 ).div( this.size );
  31035. const halfPixelWidth = float( 0.5 ).div( this.size );
  31036. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  31037. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  31038. return vec4( mix( base, lutValue, this.intensityNode ) );
  31039. } );
  31040. const outputNode = lut3D();
  31041. return outputNode;
  31042. }
  31043. }
  31044. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  31045. addNodeElement( 'lut3D', lut3D );
  31046. class RenderOutputNode extends TempNode {
  31047. constructor( colorNode, toneMapping, outputColorSpace ) {
  31048. super( 'vec4' );
  31049. this.colorNode = colorNode;
  31050. this.toneMapping = toneMapping;
  31051. this.outputColorSpace = outputColorSpace;
  31052. this.isRenderOutput = true;
  31053. }
  31054. setup( { context } ) {
  31055. let outputNode = this.colorNode || context.color;
  31056. // tone mapping
  31057. const toneMapping = this.toneMapping !== null ? this.toneMapping : context.toneMapping;
  31058. const outputColorSpace = this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace;
  31059. if ( toneMapping !== NoToneMapping ) {
  31060. outputNode = outputNode.toneMapping( toneMapping );
  31061. }
  31062. // output color space
  31063. if ( outputColorSpace === SRGBColorSpace ) {
  31064. outputNode = outputNode.linearToColorSpace( outputColorSpace );
  31065. }
  31066. return outputNode;
  31067. }
  31068. }
  31069. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  31070. addNodeElement( 'renderOutput', renderOutput );
  31071. addNodeClass( 'RenderOutputNode', RenderOutputNode );
  31072. class FunctionCallNode extends TempNode {
  31073. constructor( functionNode = null, parameters = {} ) {
  31074. super();
  31075. this.functionNode = functionNode;
  31076. this.parameters = parameters;
  31077. }
  31078. setParameters( parameters ) {
  31079. this.parameters = parameters;
  31080. return this;
  31081. }
  31082. getParameters() {
  31083. return this.parameters;
  31084. }
  31085. getNodeType( builder ) {
  31086. return this.functionNode.getNodeType( builder );
  31087. }
  31088. generate( builder ) {
  31089. const params = [];
  31090. const functionNode = this.functionNode;
  31091. const inputs = functionNode.getInputs( builder );
  31092. const parameters = this.parameters;
  31093. if ( Array.isArray( parameters ) ) {
  31094. for ( let i = 0; i < parameters.length; i ++ ) {
  31095. const inputNode = inputs[ i ];
  31096. const node = parameters[ i ];
  31097. params.push( node.build( builder, inputNode.type ) );
  31098. }
  31099. } else {
  31100. for ( const inputNode of inputs ) {
  31101. const node = parameters[ inputNode.name ];
  31102. if ( node !== undefined ) {
  31103. params.push( node.build( builder, inputNode.type ) );
  31104. } else {
  31105. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  31106. }
  31107. }
  31108. }
  31109. const functionName = functionNode.build( builder, 'property' );
  31110. return `${functionName}( ${params.join( ', ' )} )`;
  31111. }
  31112. }
  31113. const call = ( func, ...params ) => {
  31114. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  31115. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  31116. };
  31117. addNodeElement( 'call', call );
  31118. addNodeClass( 'FunctionCallNode', FunctionCallNode );
  31119. class ScriptableValueNode extends Node {
  31120. constructor( value = null ) {
  31121. super();
  31122. this._value = value;
  31123. this._cache = null;
  31124. this.inputType = null;
  31125. this.outpuType = null;
  31126. this.events = new EventDispatcher();
  31127. this.isScriptableValueNode = true;
  31128. }
  31129. get isScriptableOutputNode() {
  31130. return this.outputType !== null;
  31131. }
  31132. set value( val ) {
  31133. if ( this._value === val ) return;
  31134. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  31135. URL.revokeObjectURL( this._cache );
  31136. this._cache = null;
  31137. }
  31138. this._value = val;
  31139. this.events.dispatchEvent( { type: 'change' } );
  31140. this.refresh();
  31141. }
  31142. get value() {
  31143. return this._value;
  31144. }
  31145. refresh() {
  31146. this.events.dispatchEvent( { type: 'refresh' } );
  31147. }
  31148. getValue() {
  31149. const value = this.value;
  31150. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  31151. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  31152. } else if ( value && value.value !== null && value.value !== undefined && (
  31153. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  31154. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  31155. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  31156. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  31157. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  31158. ( this.inputType === 'Color' && value.value.isColor ) ||
  31159. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  31160. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  31161. ) ) {
  31162. return value.value;
  31163. }
  31164. return this._cache || value;
  31165. }
  31166. getNodeType( builder ) {
  31167. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  31168. }
  31169. setup() {
  31170. return this.value && this.value.isNode ? this.value : float();
  31171. }
  31172. serialize( data ) {
  31173. super.serialize( data );
  31174. if ( this.value !== null ) {
  31175. if ( this.inputType === 'ArrayBuffer' ) {
  31176. data.value = arrayBufferToBase64( this.value );
  31177. } else {
  31178. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  31179. }
  31180. } else {
  31181. data.value = null;
  31182. }
  31183. data.inputType = this.inputType;
  31184. data.outputType = this.outputType;
  31185. }
  31186. deserialize( data ) {
  31187. super.deserialize( data );
  31188. let value = null;
  31189. if ( data.value !== null ) {
  31190. if ( data.inputType === 'ArrayBuffer' ) {
  31191. value = base64ToArrayBuffer( data.value );
  31192. } else if ( data.inputType === 'Texture' ) {
  31193. value = data.meta.textures[ data.value ];
  31194. } else {
  31195. value = data.meta.nodes[ data.value ] || null;
  31196. }
  31197. }
  31198. this.value = value;
  31199. this.inputType = data.inputType;
  31200. this.outputType = data.outputType;
  31201. }
  31202. }
  31203. const scriptableValue = nodeProxy( ScriptableValueNode );
  31204. addNodeElement( 'scriptableValue', scriptableValue );
  31205. addNodeClass( 'ScriptableValueNode', ScriptableValueNode );
  31206. class Resources extends Map {
  31207. get( key, callback = null, ...params ) {
  31208. if ( this.has( key ) ) return super.get( key );
  31209. if ( callback !== null ) {
  31210. const value = callback( ...params );
  31211. this.set( key, value );
  31212. return value;
  31213. }
  31214. }
  31215. }
  31216. class Parameters {
  31217. constructor( scriptableNode ) {
  31218. this.scriptableNode = scriptableNode;
  31219. }
  31220. get parameters() {
  31221. return this.scriptableNode.parameters;
  31222. }
  31223. get layout() {
  31224. return this.scriptableNode.getLayout();
  31225. }
  31226. getInputLayout( id ) {
  31227. return this.scriptableNode.getInputLayout( id );
  31228. }
  31229. get( name ) {
  31230. const param = this.parameters[ name ];
  31231. const value = param ? param.getValue() : null;
  31232. return value;
  31233. }
  31234. }
  31235. const global = new Resources();
  31236. class ScriptableNode extends Node {
  31237. constructor( codeNode = null, parameters = {} ) {
  31238. super();
  31239. this.codeNode = codeNode;
  31240. this.parameters = parameters;
  31241. this._local = new Resources();
  31242. this._output = scriptableValue();
  31243. this._outputs = {};
  31244. this._source = this.source;
  31245. this._method = null;
  31246. this._object = null;
  31247. this._value = null;
  31248. this._needsOutputUpdate = true;
  31249. this.onRefresh = this.onRefresh.bind( this );
  31250. this.isScriptableNode = true;
  31251. }
  31252. get source() {
  31253. return this.codeNode ? this.codeNode.code : '';
  31254. }
  31255. setLocal( name, value ) {
  31256. return this._local.set( name, value );
  31257. }
  31258. getLocal( name ) {
  31259. return this._local.get( name );
  31260. }
  31261. onRefresh() {
  31262. this._refresh();
  31263. }
  31264. getInputLayout( id ) {
  31265. for ( const element of this.getLayout() ) {
  31266. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  31267. return element;
  31268. }
  31269. }
  31270. }
  31271. getOutputLayout( id ) {
  31272. for ( const element of this.getLayout() ) {
  31273. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  31274. return element;
  31275. }
  31276. }
  31277. }
  31278. setOutput( name, value ) {
  31279. const outputs = this._outputs;
  31280. if ( outputs[ name ] === undefined ) {
  31281. outputs[ name ] = scriptableValue( value );
  31282. } else {
  31283. outputs[ name ].value = value;
  31284. }
  31285. return this;
  31286. }
  31287. getOutput( name ) {
  31288. return this._outputs[ name ];
  31289. }
  31290. getParameter( name ) {
  31291. return this.parameters[ name ];
  31292. }
  31293. setParameter( name, value ) {
  31294. const parameters = this.parameters;
  31295. if ( value && value.isScriptableNode ) {
  31296. this.deleteParameter( name );
  31297. parameters[ name ] = value;
  31298. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  31299. } else if ( value && value.isScriptableValueNode ) {
  31300. this.deleteParameter( name );
  31301. parameters[ name ] = value;
  31302. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31303. } else if ( parameters[ name ] === undefined ) {
  31304. parameters[ name ] = scriptableValue( value );
  31305. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  31306. } else {
  31307. parameters[ name ].value = value;
  31308. }
  31309. return this;
  31310. }
  31311. getValue() {
  31312. return this.getDefaultOutput().getValue();
  31313. }
  31314. deleteParameter( name ) {
  31315. let valueNode = this.parameters[ name ];
  31316. if ( valueNode ) {
  31317. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31318. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  31319. }
  31320. return this;
  31321. }
  31322. clearParameters() {
  31323. for ( const name of Object.keys( this.parameters ) ) {
  31324. this.deleteParameter( name );
  31325. }
  31326. this.needsUpdate = true;
  31327. return this;
  31328. }
  31329. call( name, ...params ) {
  31330. const object = this.getObject();
  31331. const method = object[ name ];
  31332. if ( typeof method === 'function' ) {
  31333. return method( ...params );
  31334. }
  31335. }
  31336. async callAsync( name, ...params ) {
  31337. const object = this.getObject();
  31338. const method = object[ name ];
  31339. if ( typeof method === 'function' ) {
  31340. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  31341. }
  31342. }
  31343. getNodeType( builder ) {
  31344. return this.getDefaultOutputNode().getNodeType( builder );
  31345. }
  31346. refresh( output = null ) {
  31347. if ( output !== null ) {
  31348. this.getOutput( output ).refresh();
  31349. } else {
  31350. this._refresh();
  31351. }
  31352. }
  31353. getObject() {
  31354. if ( this.needsUpdate ) this.dispose();
  31355. if ( this._object !== null ) return this._object;
  31356. //
  31357. const refresh = () => this.refresh();
  31358. const setOutput = ( id, value ) => this.setOutput( id, value );
  31359. const parameters = new Parameters( this );
  31360. const THREE = global.get( 'THREE' );
  31361. const TSL = global.get( 'TSL' );
  31362. const method = this.getMethod( this.codeNode );
  31363. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  31364. this._object = method( ...params );
  31365. const layout = this._object.layout;
  31366. if ( layout ) {
  31367. if ( layout.cache === false ) {
  31368. this._local.clear();
  31369. }
  31370. // default output
  31371. this._output.outputType = layout.outputType || null;
  31372. if ( Array.isArray( layout.elements ) ) {
  31373. for ( const element of layout.elements ) {
  31374. const id = element.id || element.name;
  31375. if ( element.inputType ) {
  31376. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  31377. this.getParameter( id ).inputType = element.inputType;
  31378. }
  31379. if ( element.outputType ) {
  31380. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  31381. this.getOutput( id ).outputType = element.outputType;
  31382. }
  31383. }
  31384. }
  31385. }
  31386. return this._object;
  31387. }
  31388. deserialize( data ) {
  31389. super.deserialize( data );
  31390. for ( const name in this.parameters ) {
  31391. let valueNode = this.parameters[ name ];
  31392. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  31393. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  31394. }
  31395. }
  31396. getLayout() {
  31397. return this.getObject().layout;
  31398. }
  31399. getDefaultOutputNode() {
  31400. const output = this.getDefaultOutput().value;
  31401. if ( output && output.isNode ) {
  31402. return output;
  31403. }
  31404. return float();
  31405. }
  31406. getDefaultOutput() {
  31407. return this._exec()._output;
  31408. }
  31409. getMethod() {
  31410. if ( this.needsUpdate ) this.dispose();
  31411. if ( this._method !== null ) return this._method;
  31412. //
  31413. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  31414. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  31415. const properties = interfaceProps.join( ', ' );
  31416. const declarations = 'var ' + properties + '; var output = {};\n';
  31417. const returns = '\nreturn { ...output, ' + properties + ' };';
  31418. const code = declarations + this.codeNode.code + returns;
  31419. //
  31420. this._method = new Function( ...parametersProps, code );
  31421. return this._method;
  31422. }
  31423. dispose() {
  31424. if ( this._method === null ) return;
  31425. if ( this._object && typeof this._object.dispose === 'function' ) {
  31426. this._object.dispose();
  31427. }
  31428. this._method = null;
  31429. this._object = null;
  31430. this._source = null;
  31431. this._value = null;
  31432. this._needsOutputUpdate = true;
  31433. this._output.value = null;
  31434. this._outputs = {};
  31435. }
  31436. setup() {
  31437. return this.getDefaultOutputNode();
  31438. }
  31439. set needsUpdate( value ) {
  31440. if ( value === true ) this.dispose();
  31441. }
  31442. get needsUpdate() {
  31443. return this.source !== this._source;
  31444. }
  31445. _exec() {
  31446. if ( this.codeNode === null ) return this;
  31447. if ( this._needsOutputUpdate === true ) {
  31448. this._value = this.call( 'main' );
  31449. this._needsOutputUpdate = false;
  31450. }
  31451. this._output.value = this._value;
  31452. return this;
  31453. }
  31454. _refresh() {
  31455. this.needsUpdate = true;
  31456. this._exec();
  31457. this._output.refresh();
  31458. }
  31459. }
  31460. const scriptable = nodeProxy( ScriptableNode );
  31461. addNodeElement( 'scriptable', scriptable );
  31462. addNodeClass( 'ScriptableNode', ScriptableNode );
  31463. class FogNode extends Node {
  31464. constructor( colorNode, factorNode ) {
  31465. super( 'float' );
  31466. this.isFogNode = true;
  31467. this.colorNode = colorNode;
  31468. this.factorNode = factorNode;
  31469. }
  31470. getViewZNode( builder ) {
  31471. let viewZ;
  31472. const getViewZ = builder.context.getViewZ;
  31473. if ( getViewZ !== undefined ) {
  31474. viewZ = getViewZ( this );
  31475. }
  31476. return ( viewZ || positionView.z ).negate();
  31477. }
  31478. setup() {
  31479. return this.factorNode;
  31480. }
  31481. }
  31482. const fog = nodeProxy( FogNode );
  31483. addNodeElement( 'fog', fog );
  31484. addNodeClass( 'FogNode', FogNode );
  31485. class FogRangeNode extends FogNode {
  31486. constructor( colorNode, nearNode, farNode ) {
  31487. super( colorNode );
  31488. this.isFogRangeNode = true;
  31489. this.nearNode = nearNode;
  31490. this.farNode = farNode;
  31491. }
  31492. setup( builder ) {
  31493. const viewZ = this.getViewZNode( builder );
  31494. return smoothstep( this.nearNode, this.farNode, viewZ );
  31495. }
  31496. }
  31497. const rangeFog = nodeProxy( FogRangeNode );
  31498. addNodeElement( 'rangeFog', rangeFog );
  31499. addNodeClass( 'FogRangeNode', FogRangeNode );
  31500. class FogExp2Node extends FogNode {
  31501. constructor( colorNode, densityNode ) {
  31502. super( colorNode );
  31503. this.isFogExp2Node = true;
  31504. this.densityNode = densityNode;
  31505. }
  31506. setup( builder ) {
  31507. const viewZ = this.getViewZNode( builder );
  31508. const density = this.densityNode;
  31509. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  31510. }
  31511. }
  31512. const densityFog = nodeProxy( FogExp2Node );
  31513. addNodeElement( 'densityFog', densityFog );
  31514. addNodeClass( 'FogExp2Node', FogExp2Node );
  31515. let min = null;
  31516. let max = null;
  31517. class RangeNode extends Node {
  31518. constructor( minNode = float(), maxNode = float() ) {
  31519. super();
  31520. this.minNode = minNode;
  31521. this.maxNode = maxNode;
  31522. }
  31523. getVectorLength( builder ) {
  31524. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  31525. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  31526. return minLength > maxLength ? minLength : maxLength;
  31527. }
  31528. getNodeType( builder ) {
  31529. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  31530. }
  31531. setup( builder ) {
  31532. const object = builder.object;
  31533. let output = null;
  31534. if ( object.count > 1 ) {
  31535. const minValue = this.minNode.value;
  31536. const maxValue = this.maxNode.value;
  31537. const minLength = builder.getTypeLength( getValueType( minValue ) );
  31538. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  31539. min = min || new Vector4();
  31540. max = max || new Vector4();
  31541. min.setScalar( 0 );
  31542. max.setScalar( 0 );
  31543. if ( minLength === 1 ) min.setScalar( minValue );
  31544. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  31545. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  31546. if ( maxLength === 1 ) max.setScalar( maxValue );
  31547. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  31548. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  31549. const stride = 4;
  31550. const length = stride * object.count;
  31551. const array = new Float32Array( length );
  31552. for ( let i = 0; i < length; i ++ ) {
  31553. const index = i % stride;
  31554. const minElementValue = min.getComponent( index );
  31555. const maxElementValue = max.getComponent( index );
  31556. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  31557. }
  31558. const nodeType = this.getNodeType( builder );
  31559. if ( object.count <= 4096 ) {
  31560. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  31561. } else {
  31562. // TODO: Improve anonymous buffer attribute creation removing this part
  31563. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  31564. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  31565. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  31566. }
  31567. } else {
  31568. output = float( 0 );
  31569. }
  31570. return output;
  31571. }
  31572. }
  31573. const range = nodeProxy( RangeNode );
  31574. addNodeClass( 'RangeNode', RangeNode );
  31575. class ComputeNode extends Node {
  31576. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  31577. super( 'void' );
  31578. this.isComputeNode = true;
  31579. this.computeNode = computeNode;
  31580. this.count = count;
  31581. this.workgroupSize = workgroupSize;
  31582. this.dispatchCount = 0;
  31583. this.version = 1;
  31584. this.updateBeforeType = NodeUpdateType.OBJECT;
  31585. this.updateDispatchCount();
  31586. }
  31587. dispose() {
  31588. this.dispatchEvent( { type: 'dispose' } );
  31589. }
  31590. set needsUpdate( value ) {
  31591. if ( value === true ) this.version ++;
  31592. }
  31593. updateDispatchCount() {
  31594. const { count, workgroupSize } = this;
  31595. let size = workgroupSize[ 0 ];
  31596. for ( let i = 1; i < workgroupSize.length; i ++ )
  31597. size *= workgroupSize[ i ];
  31598. this.dispatchCount = Math.ceil( count / size );
  31599. }
  31600. onInit() { }
  31601. updateBefore( { renderer } ) {
  31602. renderer.compute( this );
  31603. }
  31604. generate( builder ) {
  31605. const { shaderStage } = builder;
  31606. if ( shaderStage === 'compute' ) {
  31607. const snippet = this.computeNode.build( builder, 'void' );
  31608. if ( snippet !== '' ) {
  31609. builder.addLineFlowCode( snippet );
  31610. }
  31611. }
  31612. }
  31613. }
  31614. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  31615. addNodeElement( 'compute', compute );
  31616. addNodeClass( 'ComputeNode', ComputeNode );
  31617. class LightNode extends Node {
  31618. constructor( scope = LightNode.TARGET_DIRECTION, light = null ) {
  31619. super();
  31620. this.scope = scope;
  31621. this.light = light;
  31622. }
  31623. setup() {
  31624. const { scope, light } = this;
  31625. let output = null;
  31626. if ( scope === LightNode.TARGET_DIRECTION ) {
  31627. output = cameraViewMatrix.transformDirection( objectPosition( light ).sub( objectPosition( light.target ) ) );
  31628. }
  31629. return output;
  31630. }
  31631. serialize( data ) {
  31632. super.serialize( data );
  31633. data.scope = this.scope;
  31634. }
  31635. deserialize( data ) {
  31636. super.deserialize( data );
  31637. this.scope = data.scope;
  31638. }
  31639. }
  31640. LightNode.TARGET_DIRECTION = 'targetDirection';
  31641. const lightTargetDirection = nodeProxy( LightNode, LightNode.TARGET_DIRECTION );
  31642. addNodeClass( 'LightNode', LightNode );
  31643. const getDistanceAttenuation = tslFn( ( inputs ) => {
  31644. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  31645. // based upon Frostbite 3 Moving to Physically-based Rendering
  31646. // page 32, equation 26: E[window1]
  31647. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31648. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31649. return cutoffDistance.greaterThan( 0 ).cond(
  31650. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31651. distanceFalloff
  31652. );
  31653. } ); // validated
  31654. class PointLightNode extends AnalyticLightNode {
  31655. constructor( light = null ) {
  31656. super( light );
  31657. this.cutoffDistanceNode = uniform( 0 );
  31658. this.decayExponentNode = uniform( 0 );
  31659. }
  31660. update( frame ) {
  31661. const { light } = this;
  31662. super.update( frame );
  31663. this.cutoffDistanceNode.value = light.distance;
  31664. this.decayExponentNode.value = light.decay;
  31665. }
  31666. setup( builder ) {
  31667. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31668. const lightingModel = builder.context.lightingModel;
  31669. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31670. const lightDirection = lVector.normalize();
  31671. const lightDistance = lVector.length();
  31672. const lightAttenuation = getDistanceAttenuation( {
  31673. lightDistance,
  31674. cutoffDistance: cutoffDistanceNode,
  31675. decayExponent: decayExponentNode
  31676. } );
  31677. const lightColor = colorNode.mul( lightAttenuation );
  31678. const reflectedLight = builder.context.reflectedLight;
  31679. lightingModel.direct( {
  31680. lightDirection,
  31681. lightColor,
  31682. reflectedLight,
  31683. shadowMask: this.shadowMaskNode
  31684. }, builder.stack, builder );
  31685. }
  31686. }
  31687. addNodeClass( 'PointLightNode', PointLightNode );
  31688. addLightNode( PointLight, PointLightNode );
  31689. class DirectionalLightNode extends AnalyticLightNode {
  31690. constructor( light = null ) {
  31691. super( light );
  31692. }
  31693. setup( builder ) {
  31694. super.setup( builder );
  31695. const lightingModel = builder.context.lightingModel;
  31696. const lightColor = this.colorNode;
  31697. const lightDirection = lightTargetDirection( this.light );
  31698. const reflectedLight = builder.context.reflectedLight;
  31699. lightingModel.direct( {
  31700. lightDirection,
  31701. lightColor,
  31702. reflectedLight,
  31703. shadowMask: this.shadowMaskNode
  31704. }, builder.stack, builder );
  31705. }
  31706. }
  31707. addNodeClass( 'DirectionalLightNode', DirectionalLightNode );
  31708. addLightNode( DirectionalLight, DirectionalLightNode );
  31709. const _matrix41 = new Matrix4();
  31710. const _matrix42 = new Matrix4();
  31711. let ltcLib = null;
  31712. class RectAreaLightNode extends AnalyticLightNode {
  31713. constructor( light = null ) {
  31714. super( light );
  31715. this.halfHeight = uniform( new Vector3() );
  31716. this.halfWidth = uniform( new Vector3() );
  31717. }
  31718. update( frame ) {
  31719. super.update( frame );
  31720. const { light } = this;
  31721. const viewMatrix = frame.camera.matrixWorldInverse;
  31722. _matrix42.identity();
  31723. _matrix41.copy( light.matrixWorld );
  31724. _matrix41.premultiply( viewMatrix );
  31725. _matrix42.extractRotation( _matrix41 );
  31726. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31727. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31728. this.halfWidth.value.applyMatrix4( _matrix42 );
  31729. this.halfHeight.value.applyMatrix4( _matrix42 );
  31730. }
  31731. setup( builder ) {
  31732. super.setup( builder );
  31733. let ltc_1, ltc_2;
  31734. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31735. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  31736. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  31737. } else {
  31738. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  31739. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  31740. }
  31741. const { colorNode, light } = this;
  31742. const lightingModel = builder.context.lightingModel;
  31743. const lightPosition = objectViewPosition( light );
  31744. const reflectedLight = builder.context.reflectedLight;
  31745. lightingModel.directRectArea( {
  31746. lightColor: colorNode,
  31747. lightPosition,
  31748. halfWidth: this.halfWidth,
  31749. halfHeight: this.halfHeight,
  31750. reflectedLight,
  31751. ltc_1,
  31752. ltc_2
  31753. }, builder.stack, builder );
  31754. }
  31755. static setLTC( ltc ) {
  31756. ltcLib = ltc;
  31757. }
  31758. }
  31759. addNodeClass( 'RectAreaLightNode', RectAreaLightNode );
  31760. addLightNode( RectAreaLight, RectAreaLightNode );
  31761. class SpotLightNode extends AnalyticLightNode {
  31762. constructor( light = null ) {
  31763. super( light );
  31764. this.coneCosNode = uniform( 0 );
  31765. this.penumbraCosNode = uniform( 0 );
  31766. this.cutoffDistanceNode = uniform( 0 );
  31767. this.decayExponentNode = uniform( 0 );
  31768. }
  31769. update( frame ) {
  31770. super.update( frame );
  31771. const { light } = this;
  31772. this.coneCosNode.value = Math.cos( light.angle );
  31773. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31774. this.cutoffDistanceNode.value = light.distance;
  31775. this.decayExponentNode.value = light.decay;
  31776. }
  31777. getSpotAttenuation( angleCosine ) {
  31778. const { coneCosNode, penumbraCosNode } = this;
  31779. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31780. }
  31781. setup( builder ) {
  31782. super.setup( builder );
  31783. const lightingModel = builder.context.lightingModel;
  31784. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31785. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31786. const lightDirection = lVector.normalize();
  31787. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31788. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31789. const lightDistance = lVector.length();
  31790. const lightAttenuation = getDistanceAttenuation( {
  31791. lightDistance,
  31792. cutoffDistance: cutoffDistanceNode,
  31793. decayExponent: decayExponentNode
  31794. } );
  31795. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31796. const reflectedLight = builder.context.reflectedLight;
  31797. lightingModel.direct( {
  31798. lightDirection,
  31799. lightColor,
  31800. reflectedLight,
  31801. shadowMask: this.shadowMaskNode
  31802. }, builder.stack, builder );
  31803. }
  31804. }
  31805. addNodeClass( 'SpotLightNode', SpotLightNode );
  31806. addLightNode( SpotLight, SpotLightNode );
  31807. class IESSpotLight extends SpotLight {
  31808. constructor( color, intensity, distance, angle, penumbra, decay ) {
  31809. super( color, intensity, distance, angle, penumbra, decay );
  31810. this.iesMap = null;
  31811. }
  31812. copy( source, recursive ) {
  31813. super.copy( source, recursive );
  31814. this.iesMap = source.iesMap;
  31815. return this;
  31816. }
  31817. }
  31818. class IESSpotLightNode extends SpotLightNode {
  31819. getSpotAttenuation( angleCosine ) {
  31820. const iesMap = this.light.iesMap;
  31821. let spotAttenuation = null;
  31822. if ( iesMap && iesMap.isTexture === true ) {
  31823. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31824. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31825. } else {
  31826. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31827. }
  31828. return spotAttenuation;
  31829. }
  31830. }
  31831. addNodeClass( 'IESSpotLightNode', IESSpotLightNode );
  31832. addLightNode( IESSpotLight, IESSpotLightNode );
  31833. class AmbientLightNode extends AnalyticLightNode {
  31834. constructor( light = null ) {
  31835. super( light );
  31836. }
  31837. setup( { context } ) {
  31838. context.irradiance.addAssign( this.colorNode );
  31839. }
  31840. }
  31841. addNodeClass( 'AmbientLightNode', AmbientLightNode );
  31842. addLightNode( AmbientLight, AmbientLightNode );
  31843. class HemisphereLightNode extends AnalyticLightNode {
  31844. constructor( light = null ) {
  31845. super( light );
  31846. this.lightPositionNode = objectPosition( light );
  31847. this.lightDirectionNode = this.lightPositionNode.normalize();
  31848. this.groundColorNode = uniform( new Color() );
  31849. }
  31850. update( frame ) {
  31851. const { light } = this;
  31852. super.update( frame );
  31853. this.lightPositionNode.object3d = light;
  31854. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31855. }
  31856. setup( builder ) {
  31857. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31858. const dotNL = normalView.dot( lightDirectionNode );
  31859. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31860. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31861. builder.context.irradiance.addAssign( irradiance );
  31862. }
  31863. }
  31864. addNodeClass( 'HemisphereLightNode', HemisphereLightNode );
  31865. addLightNode( HemisphereLight, HemisphereLightNode );
  31866. let _generator = null;
  31867. const _cache = new WeakMap();
  31868. function _generateCubeUVSize( imageHeight ) {
  31869. const maxMip = Math.log2( imageHeight ) - 2;
  31870. const texelHeight = 1.0 / imageHeight;
  31871. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  31872. return { texelWidth, texelHeight, maxMip };
  31873. }
  31874. function _getPMREMFromTexture( texture ) {
  31875. let cacheTexture = _cache.get( texture );
  31876. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  31877. if ( pmremVersion !== texture.pmremVersion ) {
  31878. if ( texture.isCubeTexture ) {
  31879. if ( texture.source.data.some( ( texture ) => texture === undefined ) ) {
  31880. throw new Error( 'PMREMNode: Undefined texture in CubeTexture. Use onLoad callback or async loader' );
  31881. }
  31882. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  31883. } else {
  31884. if ( texture.image === undefined ) {
  31885. throw new Error( 'PMREMNode: Undefined image in Texture. Use onLoad callback or async loader' );
  31886. }
  31887. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  31888. }
  31889. cacheTexture.pmremVersion = texture.pmremVersion;
  31890. _cache.set( texture, cacheTexture );
  31891. }
  31892. return cacheTexture.texture;
  31893. }
  31894. class PMREMNode extends TempNode {
  31895. constructor( value, uvNode = null, levelNode = null ) {
  31896. super( 'vec3' );
  31897. this._value = value;
  31898. this._pmrem = null;
  31899. this.uvNode = uvNode;
  31900. this.levelNode = levelNode;
  31901. this._generator = null;
  31902. this._texture = texture( null );
  31903. this._width = uniform( 0 );
  31904. this._height = uniform( 0 );
  31905. this._maxMip = uniform( 0 );
  31906. this.updateBeforeType = NodeUpdateType.RENDER;
  31907. }
  31908. set value( value ) {
  31909. this._value = value;
  31910. this._pmrem = null;
  31911. }
  31912. get value() {
  31913. return this._value;
  31914. }
  31915. updateFromTexture( texture ) {
  31916. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  31917. this._texture.value = texture;
  31918. this._width.value = cubeUVSize.texelWidth;
  31919. this._height.value = cubeUVSize.texelHeight;
  31920. this._maxMip.value = cubeUVSize.maxMip;
  31921. }
  31922. updateBefore() {
  31923. let pmrem = this._pmrem;
  31924. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  31925. const texture = this._value;
  31926. if ( pmremVersion !== texture.pmremVersion ) {
  31927. if ( texture.isPMREMTexture === true ) {
  31928. pmrem = texture;
  31929. } else {
  31930. pmrem = _getPMREMFromTexture( texture );
  31931. }
  31932. this._pmrem = pmrem;
  31933. this.updateFromTexture( pmrem );
  31934. }
  31935. }
  31936. setup( builder ) {
  31937. if ( _generator === null ) {
  31938. _generator = builder.createPMREMGenerator();
  31939. }
  31940. //
  31941. this.updateBefore( builder );
  31942. //
  31943. let uvNode = this.uvNode;
  31944. if ( uvNode === null && builder.context.getUV ) {
  31945. uvNode = builder.context.getUV( this );
  31946. }
  31947. //
  31948. const texture = this.value;
  31949. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  31950. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  31951. }
  31952. //
  31953. let levelNode = this.levelNode;
  31954. if ( levelNode === null && builder.context.getTextureLevel ) {
  31955. levelNode = builder.context.getTextureLevel( this );
  31956. }
  31957. //
  31958. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  31959. }
  31960. }
  31961. const pmremTexture = nodeProxy( PMREMNode );
  31962. addNodeClass( 'PMREMNode', PMREMNode );
  31963. const envNodeCache = new WeakMap();
  31964. class EnvironmentNode extends LightingNode {
  31965. constructor( envNode = null ) {
  31966. super();
  31967. this.envNode = envNode;
  31968. }
  31969. setup( builder ) {
  31970. let envNode = this.envNode;
  31971. if ( envNode.isTextureNode ) {
  31972. let cacheEnvNode = envNodeCache.get( envNode.value );
  31973. if ( cacheEnvNode === undefined ) {
  31974. cacheEnvNode = pmremTexture( envNode.value );
  31975. envNodeCache.set( envNode.value, cacheEnvNode );
  31976. }
  31977. envNode = cacheEnvNode;
  31978. }
  31979. //
  31980. const { material } = builder;
  31981. const envMap = material.envMap;
  31982. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  31983. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  31984. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  31985. const radiance = context( envNode, createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  31986. const irradiance = context( envNode, createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  31987. const isolateRadiance = cache( radiance );
  31988. const isolateIrradiance = cache( irradiance );
  31989. //
  31990. builder.context.radiance.addAssign( isolateRadiance );
  31991. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  31992. //
  31993. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  31994. if ( clearcoatRadiance ) {
  31995. const clearcoatRadianceContext = context( envNode, createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  31996. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  31997. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  31998. }
  31999. }
  32000. }
  32001. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  32002. let reflectVec = null;
  32003. return {
  32004. getUV: () => {
  32005. if ( reflectVec === null ) {
  32006. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  32007. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  32008. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  32009. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  32010. }
  32011. return reflectVec;
  32012. },
  32013. getTextureLevel: () => {
  32014. return roughnessNode;
  32015. }
  32016. };
  32017. };
  32018. const createIrradianceContext = ( normalWorldNode ) => {
  32019. return {
  32020. getUV: () => {
  32021. return normalWorldNode;
  32022. },
  32023. getTextureLevel: () => {
  32024. return float( 1.0 );
  32025. }
  32026. };
  32027. };
  32028. addNodeClass( 'EnvironmentNode', EnvironmentNode );
  32029. class BasicEnvironmentNode extends LightingNode {
  32030. constructor( envNode = null ) {
  32031. super();
  32032. this.envNode = envNode;
  32033. }
  32034. setup( builder ) {
  32035. // environment property is used in the finish() method of BasicLightingModel
  32036. builder.context.environment = this.envNode;
  32037. }
  32038. }
  32039. addNodeClass( 'BasicEnvironmentNode', BasicEnvironmentNode );
  32040. const checkerShaderNode = tslFn( ( inputs ) => {
  32041. const uv = inputs.uv.mul( 2.0 );
  32042. const cx = uv.x.floor();
  32043. const cy = uv.y.floor();
  32044. const result = cx.add( cy ).mod( 2.0 );
  32045. return result.sign();
  32046. } );
  32047. class CheckerNode extends TempNode {
  32048. constructor( uvNode = uv() ) {
  32049. super( 'float' );
  32050. this.uvNode = uvNode;
  32051. }
  32052. setup() {
  32053. return checkerShaderNode( { uv: this.uvNode } );
  32054. }
  32055. }
  32056. const checker = nodeProxy( CheckerNode );
  32057. addNodeElement( 'checker', checker );
  32058. addNodeClass( 'CheckerNode', CheckerNode );
  32059. class NodeLoader extends Loader {
  32060. constructor( manager ) {
  32061. super( manager );
  32062. this.textures = {};
  32063. }
  32064. load( url, onLoad, onProgress, onError ) {
  32065. const loader = new FileLoader( this.manager );
  32066. loader.setPath( this.path );
  32067. loader.setRequestHeader( this.requestHeader );
  32068. loader.setWithCredentials( this.withCredentials );
  32069. loader.load( url, ( text ) => {
  32070. try {
  32071. onLoad( this.parse( JSON.parse( text ) ) );
  32072. } catch ( e ) {
  32073. if ( onError ) {
  32074. onError( e );
  32075. } else {
  32076. console.error( e );
  32077. }
  32078. this.manager.itemError( url );
  32079. }
  32080. }, onProgress, onError );
  32081. }
  32082. parseNodes( json ) {
  32083. const nodes = {};
  32084. if ( json !== undefined ) {
  32085. for ( const nodeJSON of json ) {
  32086. const { uuid, type } = nodeJSON;
  32087. nodes[ uuid ] = nodeObject( createNodeFromType( type ) ); // @TODO: Maybe nodeObjectify the node in createNodeFromType?
  32088. nodes[ uuid ].uuid = uuid;
  32089. }
  32090. const meta = { nodes, textures: this.textures };
  32091. for ( const nodeJSON of json ) {
  32092. nodeJSON.meta = meta;
  32093. const node = nodes[ nodeJSON.uuid ];
  32094. node.deserialize( nodeJSON );
  32095. delete nodeJSON.meta;
  32096. }
  32097. }
  32098. return nodes;
  32099. }
  32100. parse( json ) {
  32101. const node = nodeObject( createNodeFromType( json.type ) );
  32102. node.uuid = json.uuid;
  32103. const nodes = this.parseNodes( json.nodes );
  32104. const meta = { nodes, textures: this.textures };
  32105. json.meta = meta;
  32106. node.deserialize( json );
  32107. delete json.meta;
  32108. return node;
  32109. }
  32110. setTextures( value ) {
  32111. this.textures = value;
  32112. return this;
  32113. }
  32114. }
  32115. const defaultValues$e = new PointsMaterial();
  32116. class InstancedPointsNodeMaterial extends NodeMaterial {
  32117. constructor( params = {} ) {
  32118. super();
  32119. this.normals = false;
  32120. this.lights = false;
  32121. this.useAlphaToCoverage = true;
  32122. this.useColor = params.vertexColors;
  32123. this.pointWidth = 1;
  32124. this.pointColorNode = null;
  32125. this.setDefaultValues( defaultValues$e );
  32126. this.setupShaders();
  32127. this.setValues( params );
  32128. }
  32129. setupShaders() {
  32130. const useAlphaToCoverage = this.alphaToCoverage;
  32131. const useColor = this.useColor;
  32132. this.vertexNode = tslFn( () => {
  32133. //vUv = uv;
  32134. varying( vec2(), 'vUv' ).assign( uv() ); // @TODO: Analyze other way to do this
  32135. const instancePosition = attribute( 'instancePosition' );
  32136. // camera space
  32137. const mvPos = property( 'vec4', 'mvPos' );
  32138. mvPos.assign( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  32139. const aspect = viewport.z.div( viewport.w );
  32140. // clip space
  32141. const clipPos = cameraProjectionMatrix.mul( mvPos );
  32142. // offset in ndc space
  32143. const offset = property( 'vec2', 'offset' );
  32144. offset.assign( positionGeometry.xy );
  32145. offset.assign( offset.mul( materialPointWidth ) );
  32146. offset.assign( offset.div( viewport.z ) );
  32147. offset.y.assign( offset.y.mul( aspect ) );
  32148. // back to clip space
  32149. offset.assign( offset.mul( clipPos.w ) );
  32150. //clipPos.xy += offset;
  32151. clipPos.assign( clipPos.add( vec4( offset, 0, 0 ) ) );
  32152. return clipPos;
  32153. //vec4 mvPosition = mvPos; // this was used for somethihng...
  32154. } )();
  32155. this.fragmentNode = tslFn( () => {
  32156. const vUv = varying( vec2(), 'vUv' );
  32157. // force assignment into correct place in flow
  32158. const alpha = property( 'float', 'alpha' );
  32159. alpha.assign( 1 );
  32160. const a = vUv.x;
  32161. const b = vUv.y;
  32162. const len2 = a.mul( a ).add( b.mul( b ) );
  32163. if ( useAlphaToCoverage ) {
  32164. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  32165. const dlen = property( 'float', 'dlen' );
  32166. dlen.assign( len2.fwidth() );
  32167. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  32168. } else {
  32169. len2.greaterThan( 1.0 ).discard();
  32170. }
  32171. let pointColorNode;
  32172. if ( this.pointColorNode ) {
  32173. pointColorNode = this.pointColorNode;
  32174. } else {
  32175. if ( useColor ) {
  32176. const instanceColor = attribute( 'instanceColor' );
  32177. pointColorNode = instanceColor.mul( materialColor );
  32178. } else {
  32179. pointColorNode = materialColor;
  32180. }
  32181. }
  32182. return vec4( pointColorNode, alpha );
  32183. } )();
  32184. this.needsUpdate = true;
  32185. }
  32186. get alphaToCoverage() {
  32187. return this.useAlphaToCoverage;
  32188. }
  32189. set alphaToCoverage( value ) {
  32190. if ( this.useAlphaToCoverage !== value ) {
  32191. this.useAlphaToCoverage = value;
  32192. this.setupShaders();
  32193. }
  32194. }
  32195. }
  32196. addNodeMaterial( 'InstancedPointsNodeMaterial', InstancedPointsNodeMaterial );
  32197. const defaultValues$d = new LineBasicMaterial();
  32198. class LineBasicNodeMaterial extends NodeMaterial {
  32199. constructor( parameters ) {
  32200. super();
  32201. this.isLineBasicNodeMaterial = true;
  32202. this.lights = false;
  32203. this.normals = false;
  32204. this.setDefaultValues( defaultValues$d );
  32205. this.setValues( parameters );
  32206. }
  32207. }
  32208. addNodeMaterial( 'LineBasicNodeMaterial', LineBasicNodeMaterial );
  32209. const defaultValues$c = new LineDashedMaterial();
  32210. class LineDashedNodeMaterial extends NodeMaterial {
  32211. constructor( parameters ) {
  32212. super();
  32213. this.isLineDashedNodeMaterial = true;
  32214. this.lights = false;
  32215. this.normals = false;
  32216. this.setDefaultValues( defaultValues$c );
  32217. this.offsetNode = null;
  32218. this.dashScaleNode = null;
  32219. this.dashSizeNode = null;
  32220. this.gapSizeNode = null;
  32221. this.setValues( parameters );
  32222. }
  32223. setupVariants() {
  32224. const offsetNode = this.offsetNode;
  32225. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  32226. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  32227. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  32228. dashSize.assign( dashSizeNode );
  32229. gapSize.assign( gapSizeNode );
  32230. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  32231. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  32232. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  32233. }
  32234. }
  32235. addNodeMaterial( 'LineDashedNodeMaterial', LineDashedNodeMaterial );
  32236. const defaultValues$b = new LineDashedMaterial();
  32237. class Line2NodeMaterial extends NodeMaterial {
  32238. constructor( params = {} ) {
  32239. super();
  32240. this.normals = false;
  32241. this.lights = false;
  32242. this.setDefaultValues( defaultValues$b );
  32243. this.useAlphaToCoverage = true;
  32244. this.useColor = params.vertexColors;
  32245. this.useDash = params.dashed;
  32246. this.useWorldUnits = false;
  32247. this.dashOffset = 0;
  32248. this.lineWidth = 1;
  32249. this.lineColorNode = null;
  32250. this.offsetNode = null;
  32251. this.dashScaleNode = null;
  32252. this.dashSizeNode = null;
  32253. this.gapSizeNode = null;
  32254. this.setValues( params );
  32255. }
  32256. setup( builder ) {
  32257. this.setupShaders();
  32258. super.setup( builder );
  32259. }
  32260. setupShaders() {
  32261. const useAlphaToCoverage = this.alphaToCoverage;
  32262. const useColor = this.useColor;
  32263. const useDash = this.dashed;
  32264. const useWorldUnits = this.worldUnits;
  32265. const trimSegment = tslFn( ( { start, end } ) => {
  32266. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  32267. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  32268. const nearEstimate = b.mul( - 0.5 ).div( a );
  32269. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  32270. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  32271. } );
  32272. this.vertexNode = tslFn( () => {
  32273. varyingProperty( 'vec2', 'vUv' ).assign( uv() );
  32274. const instanceStart = attribute( 'instanceStart' );
  32275. const instanceEnd = attribute( 'instanceEnd' );
  32276. // camera space
  32277. const start = property( 'vec4', 'start' );
  32278. const end = property( 'vec4', 'end' );
  32279. start.assign( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ); // force assignment into correct place in flow
  32280. end.assign( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) );
  32281. if ( useWorldUnits ) {
  32282. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  32283. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  32284. }
  32285. const aspect = viewport.z.div( viewport.w );
  32286. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  32287. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  32288. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  32289. // perhaps there is a more elegant solution -- WestLangley
  32290. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  32291. If( perspective, () => {
  32292. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  32293. end.assign( trimSegment( { start: start, end: end } ) );
  32294. } ).elseif( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  32295. start.assign( trimSegment( { start: end, end: start } ) );
  32296. } );
  32297. } );
  32298. // clip space
  32299. const clipStart = cameraProjectionMatrix.mul( start );
  32300. const clipEnd = cameraProjectionMatrix.mul( end );
  32301. // ndc space
  32302. const ndcStart = clipStart.xyz.div( clipStart.w );
  32303. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  32304. // direction
  32305. const dir = ndcEnd.xy.sub( ndcStart.xy ).temp();
  32306. // account for clip-space aspect ratio
  32307. dir.x.assign( dir.x.mul( aspect ) );
  32308. dir.assign( dir.normalize() );
  32309. const clip = temp( vec4() );
  32310. if ( useWorldUnits ) {
  32311. // get the offset direction as perpendicular to the view vector
  32312. const worldDir = end.xyz.sub( start.xyz ).normalize();
  32313. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  32314. const worldUp = worldDir.cross( tmpFwd ).normalize();
  32315. const worldFwd = worldDir.cross( worldUp );
  32316. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  32317. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).cond( start, end ) );
  32318. // height offset
  32319. const hw = materialLineWidth.mul( 0.5 );
  32320. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).cond( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  32321. // don't extend the line if we're rendering dashes because we
  32322. // won't be rendering the endcaps
  32323. if ( ! useDash ) {
  32324. // cap extension
  32325. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).cond( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  32326. // add width to the box
  32327. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  32328. // endcaps
  32329. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  32330. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  32331. } );
  32332. }
  32333. // project the worldpos
  32334. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  32335. // shift the depth of the projected points so the line
  32336. // segments overlap neatly
  32337. const clipPose = temp( vec3() );
  32338. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).cond( ndcStart, ndcEnd ) );
  32339. clip.z.assign( clipPose.z.mul( clip.w ) );
  32340. } else {
  32341. const offset = property( 'vec2', 'offset' );
  32342. offset.assign( vec2( dir.y, dir.x.negate() ) );
  32343. // undo aspect ratio adjustment
  32344. dir.x.assign( dir.x.div( aspect ) );
  32345. offset.x.assign( offset.x.div( aspect ) );
  32346. // sign flip
  32347. offset.assign( positionGeometry.x.lessThan( 0.0 ).cond( offset.negate(), offset ) );
  32348. // endcaps
  32349. If( positionGeometry.y.lessThan( 0.0 ), () => {
  32350. offset.assign( offset.sub( dir ) );
  32351. } ).elseif( positionGeometry.y.greaterThan( 1.0 ), () => {
  32352. offset.assign( offset.add( dir ) );
  32353. } );
  32354. // adjust for linewidth
  32355. offset.assign( offset.mul( materialLineWidth ) );
  32356. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  32357. offset.assign( offset.div( viewport.w ) );
  32358. // select end
  32359. clip.assign( positionGeometry.y.lessThan( 0.5 ).cond( clipStart, clipEnd ) );
  32360. // back to clip space
  32361. offset.assign( offset.mul( clip.w ) );
  32362. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  32363. }
  32364. return clip;
  32365. } )();
  32366. const closestLineToLine = tslFn( ( { p1, p2, p3, p4 } ) => {
  32367. const p13 = p1.sub( p3 );
  32368. const p43 = p4.sub( p3 );
  32369. const p21 = p2.sub( p1 );
  32370. const d1343 = p13.dot( p43 );
  32371. const d4321 = p43.dot( p21 );
  32372. const d1321 = p13.dot( p21 );
  32373. const d4343 = p43.dot( p43 );
  32374. const d2121 = p21.dot( p21 );
  32375. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  32376. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  32377. const mua = numer.div( denom ).clamp();
  32378. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  32379. return vec2( mua, mub );
  32380. } );
  32381. this.fragmentNode = tslFn( () => {
  32382. const vUv = varyingProperty( 'vec2', 'vUv' );
  32383. if ( useDash ) {
  32384. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  32385. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  32386. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  32387. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  32388. dashSize.assign( dashSizeNode );
  32389. gapSize.assign( gapSizeNode );
  32390. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  32391. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  32392. const lineDistance = positionGeometry.y.lessThan( 0.5 ).cond( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  32393. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  32394. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  32395. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  32396. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  32397. }
  32398. // force assignment into correct place in flow
  32399. const alpha = property( 'float', 'alpha' );
  32400. alpha.assign( 1 );
  32401. if ( useWorldUnits ) {
  32402. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  32403. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  32404. // Find the closest points on the view ray and the line segment
  32405. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  32406. const lineDir = worldEnd.sub( worldStart );
  32407. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  32408. const p1 = worldStart.add( lineDir.mul( params.x ) );
  32409. const p2 = rayEnd.mul( params.y );
  32410. const delta = p1.sub( p2 );
  32411. const len = delta.length();
  32412. const norm = len.div( materialLineWidth );
  32413. if ( ! useDash ) {
  32414. if ( useAlphaToCoverage ) {
  32415. const dnorm = norm.fwidth();
  32416. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  32417. } else {
  32418. norm.greaterThan( 0.5 ).discard();
  32419. }
  32420. }
  32421. } else {
  32422. // round endcaps
  32423. if ( useAlphaToCoverage ) {
  32424. const a = vUv.x;
  32425. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32426. const len2 = a.mul( a ).add( b.mul( b ) );
  32427. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  32428. const dlen = property( 'float', 'dlen' );
  32429. dlen.assign( len2.fwidth() );
  32430. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32431. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  32432. } );
  32433. } else {
  32434. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  32435. const a = vUv.x;
  32436. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  32437. const len2 = a.mul( a ).add( b.mul( b ) );
  32438. len2.greaterThan( 1.0 ).discard();
  32439. } );
  32440. }
  32441. }
  32442. let lineColorNode;
  32443. if ( this.lineColorNode ) {
  32444. lineColorNode = this.lineColorNode;
  32445. } else {
  32446. if ( useColor ) {
  32447. const instanceColorStart = attribute( 'instanceColorStart' );
  32448. const instanceColorEnd = attribute( 'instanceColorEnd' );
  32449. const instanceColor = positionGeometry.y.lessThan( 0.5 ).cond( instanceColorStart, instanceColorEnd );
  32450. lineColorNode = instanceColor.mul( materialColor );
  32451. } else {
  32452. lineColorNode = materialColor;
  32453. }
  32454. }
  32455. return vec4( lineColorNode, alpha );
  32456. } )();
  32457. }
  32458. get worldUnits() {
  32459. return this.useWorldUnits;
  32460. }
  32461. set worldUnits( value ) {
  32462. if ( this.useWorldUnits !== value ) {
  32463. this.useWorldUnits = value;
  32464. this.needsUpdate = true;
  32465. }
  32466. }
  32467. get dashed() {
  32468. return this.useDash;
  32469. }
  32470. set dashed( value ) {
  32471. if ( this.useDash !== value ) {
  32472. this.useDash = value;
  32473. this.needsUpdate = true;
  32474. }
  32475. }
  32476. get alphaToCoverage() {
  32477. return this.useAlphaToCoverage;
  32478. }
  32479. set alphaToCoverage( value ) {
  32480. if ( this.useAlphaToCoverage !== value ) {
  32481. this.useAlphaToCoverage = value;
  32482. this.needsUpdate = true;
  32483. }
  32484. }
  32485. }
  32486. addNodeMaterial( 'Line2NodeMaterial', Line2NodeMaterial );
  32487. const defaultValues$a = new MeshNormalMaterial();
  32488. class MeshNormalNodeMaterial extends NodeMaterial {
  32489. constructor( parameters ) {
  32490. super();
  32491. this.lights = false;
  32492. this.isMeshNormalNodeMaterial = true;
  32493. this.setDefaultValues( defaultValues$a );
  32494. this.setValues( parameters );
  32495. }
  32496. setupDiffuseColor() {
  32497. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  32498. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  32499. }
  32500. }
  32501. addNodeMaterial( 'MeshNormalNodeMaterial', MeshNormalNodeMaterial );
  32502. class BasicLightMapNode extends LightingNode {
  32503. constructor( lightMapNode = null ) {
  32504. super();
  32505. this.lightMapNode = lightMapNode;
  32506. }
  32507. setup( builder ) {
  32508. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  32509. const RECIPROCAL_PI = float( 1 / Math.PI );
  32510. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  32511. }
  32512. }
  32513. addNodeClass( 'BasicLightMapNode', BasicLightMapNode );
  32514. class BasicLightingModel extends LightingModel {
  32515. constructor() {
  32516. super();
  32517. }
  32518. indirect( context, stack, builder ) {
  32519. const ambientOcclusion = context.ambientOcclusion;
  32520. const reflectedLight = context.reflectedLight;
  32521. const irradianceLightMap = builder.context.irradianceLightMap;
  32522. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  32523. // accumulation (baked indirect lighting only)
  32524. if ( irradianceLightMap ) {
  32525. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  32526. } else {
  32527. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  32528. }
  32529. // modulation
  32530. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  32531. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  32532. }
  32533. finish( context, stack, builder ) {
  32534. const material = builder.material;
  32535. const outgoingLight = context.outgoingLight;
  32536. const envNode = builder.context.environment;
  32537. if ( envNode ) {
  32538. switch ( material.combine ) {
  32539. case MultiplyOperation:
  32540. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  32541. break;
  32542. case MixOperation:
  32543. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  32544. break;
  32545. case AddOperation:
  32546. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  32547. break;
  32548. default:
  32549. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  32550. break;
  32551. }
  32552. }
  32553. }
  32554. }
  32555. const defaultValues$9 = new MeshBasicMaterial();
  32556. class MeshBasicNodeMaterial extends NodeMaterial {
  32557. constructor( parameters ) {
  32558. super();
  32559. this.isMeshBasicNodeMaterial = true;
  32560. this.lights = true;
  32561. //this.normals = false; @TODO: normals usage by context
  32562. this.setDefaultValues( defaultValues$9 );
  32563. this.setValues( parameters );
  32564. }
  32565. setupNormal() {
  32566. transformedNormalView.assign( normalView ); // see #28839
  32567. }
  32568. setupEnvironment( builder ) {
  32569. const envNode = super.setupEnvironment( builder );
  32570. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  32571. }
  32572. setupLightMap( builder ) {
  32573. let node = null;
  32574. if ( builder.material.lightMap ) {
  32575. node = new BasicLightMapNode( materialLightMap );
  32576. }
  32577. return node;
  32578. }
  32579. setupLightingModel() {
  32580. return new BasicLightingModel();
  32581. }
  32582. }
  32583. addNodeMaterial( 'MeshBasicNodeMaterial', MeshBasicNodeMaterial );
  32584. const F_Schlick = tslFn( ( { f0, f90, dotVH } ) => {
  32585. // Original approximation by Christophe Schlick '94
  32586. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  32587. // Optimized variant (presented by Epic at SIGGRAPH '13)
  32588. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  32589. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  32590. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  32591. } ); // validated
  32592. const BRDF_Lambert = tslFn( ( inputs ) => {
  32593. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  32594. } ); // validated
  32595. const G_BlinnPhong_Implicit = () => float( 0.25 );
  32596. const D_BlinnPhong = tslFn( ( { dotNH } ) => {
  32597. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  32598. } );
  32599. const BRDF_BlinnPhong = tslFn( ( { lightDirection } ) => {
  32600. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32601. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32602. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32603. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  32604. const G = G_BlinnPhong_Implicit();
  32605. const D = D_BlinnPhong( { dotNH } );
  32606. return F.mul( G ).mul( D );
  32607. } );
  32608. class PhongLightingModel extends BasicLightingModel {
  32609. constructor( specular = true ) {
  32610. super();
  32611. this.specular = specular;
  32612. }
  32613. direct( { lightDirection, lightColor, reflectedLight } ) {
  32614. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32615. const irradiance = dotNL.mul( lightColor );
  32616. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  32617. if ( this.specular === true ) {
  32618. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  32619. }
  32620. }
  32621. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  32622. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  32623. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  32624. }
  32625. }
  32626. const defaultValues$8 = new MeshLambertMaterial();
  32627. class MeshLambertNodeMaterial extends NodeMaterial {
  32628. constructor( parameters ) {
  32629. super();
  32630. this.isMeshLambertNodeMaterial = true;
  32631. this.lights = true;
  32632. this.setDefaultValues( defaultValues$8 );
  32633. this.setValues( parameters );
  32634. }
  32635. setupEnvironment( builder ) {
  32636. const envNode = super.setupEnvironment( builder );
  32637. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  32638. }
  32639. setupLightingModel( /*builder*/ ) {
  32640. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  32641. }
  32642. }
  32643. addNodeMaterial( 'MeshLambertNodeMaterial', MeshLambertNodeMaterial );
  32644. const defaultValues$7 = new MeshPhongMaterial();
  32645. class MeshPhongNodeMaterial extends NodeMaterial {
  32646. constructor( parameters ) {
  32647. super();
  32648. this.isMeshPhongNodeMaterial = true;
  32649. this.lights = true;
  32650. this.shininessNode = null;
  32651. this.specularNode = null;
  32652. this.setDefaultValues( defaultValues$7 );
  32653. this.setValues( parameters );
  32654. }
  32655. setupEnvironment( builder ) {
  32656. const envNode = super.setupEnvironment( builder );
  32657. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  32658. }
  32659. setupLightingModel( /*builder*/ ) {
  32660. return new PhongLightingModel();
  32661. }
  32662. setupVariants() {
  32663. // SHININESS
  32664. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  32665. shininess.assign( shininessNode );
  32666. // SPECULAR COLOR
  32667. const specularNode = this.specularNode || materialSpecular;
  32668. specularColor.assign( specularNode );
  32669. }
  32670. copy( source ) {
  32671. this.shininessNode = source.shininessNode;
  32672. this.specularNode = source.specularNode;
  32673. return super.copy( source );
  32674. }
  32675. }
  32676. addNodeMaterial( 'MeshPhongNodeMaterial', MeshPhongNodeMaterial );
  32677. const getGeometryRoughness = tslFn( () => {
  32678. const dxy = normalGeometry.dFdx().abs().max( normalGeometry.dFdy().abs() );
  32679. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  32680. return geometryRoughness;
  32681. } );
  32682. const getRoughness = tslFn( ( inputs ) => {
  32683. const { roughness } = inputs;
  32684. const geometryRoughness = getGeometryRoughness();
  32685. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  32686. roughnessFactor = roughnessFactor.add( geometryRoughness );
  32687. roughnessFactor = roughnessFactor.min( 1.0 );
  32688. return roughnessFactor;
  32689. } );
  32690. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  32691. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32692. const V_GGX_SmithCorrelated = tslFn( ( { alpha, dotNL, dotNV } ) => {
  32693. const a2 = alpha.pow2();
  32694. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  32695. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  32696. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  32697. } ).setLayout( {
  32698. name: 'V_GGX_SmithCorrelated',
  32699. type: 'float',
  32700. inputs: [
  32701. { name: 'alpha', type: 'float' },
  32702. { name: 'dotNL', type: 'float' },
  32703. { name: 'dotNV', type: 'float' }
  32704. ]
  32705. } ); // validated
  32706. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32707. const V_GGX_SmithCorrelated_Anisotropic = tslFn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  32708. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  32709. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  32710. const v = div( 0.5, gv.add( gl ) );
  32711. return v.saturate();
  32712. } ).setLayout( {
  32713. name: 'V_GGX_SmithCorrelated_Anisotropic',
  32714. type: 'float',
  32715. inputs: [
  32716. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32717. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32718. { name: 'dotTV', type: 'float', qualifier: 'in' },
  32719. { name: 'dotBV', type: 'float', qualifier: 'in' },
  32720. { name: 'dotTL', type: 'float', qualifier: 'in' },
  32721. { name: 'dotBL', type: 'float', qualifier: 'in' },
  32722. { name: 'dotNV', type: 'float', qualifier: 'in' },
  32723. { name: 'dotNL', type: 'float', qualifier: 'in' }
  32724. ]
  32725. } );
  32726. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  32727. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  32728. // alpha is "roughness squared" in Disney’s reparameterization
  32729. const D_GGX = tslFn( ( { alpha, dotNH } ) => {
  32730. const a2 = alpha.pow2();
  32731. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  32732. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  32733. } ).setLayout( {
  32734. name: 'D_GGX',
  32735. type: 'float',
  32736. inputs: [
  32737. { name: 'alpha', type: 'float' },
  32738. { name: 'dotNH', type: 'float' }
  32739. ]
  32740. } ); // validated
  32741. const RECIPROCAL_PI = float( 1 / Math.PI );
  32742. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  32743. const D_GGX_Anisotropic = tslFn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  32744. const a2 = alphaT.mul( alphaB );
  32745. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  32746. const v2 = v.dot( v );
  32747. const w2 = a2.div( v2 );
  32748. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  32749. } ).setLayout( {
  32750. name: 'D_GGX_Anisotropic',
  32751. type: 'float',
  32752. inputs: [
  32753. { name: 'alphaT', type: 'float', qualifier: 'in' },
  32754. { name: 'alphaB', type: 'float', qualifier: 'in' },
  32755. { name: 'dotNH', type: 'float', qualifier: 'in' },
  32756. { name: 'dotTH', type: 'float', qualifier: 'in' },
  32757. { name: 'dotBH', type: 'float', qualifier: 'in' }
  32758. ]
  32759. } );
  32760. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  32761. const BRDF_GGX = tslFn( ( inputs ) => {
  32762. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  32763. const normalView = inputs.normalView || transformedNormalView;
  32764. const alpha = roughness.pow2(); // UE4's roughness
  32765. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32766. const dotNL = normalView.dot( lightDirection ).clamp();
  32767. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  32768. const dotNH = normalView.dot( halfDir ).clamp();
  32769. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  32770. let F = F_Schlick( { f0, f90, dotVH } );
  32771. let V, D;
  32772. if ( defined( USE_IRIDESCENCE ) ) {
  32773. F = iridescence.mix( F, f );
  32774. }
  32775. if ( defined( USE_ANISOTROPY ) ) {
  32776. const dotTL = anisotropyT.dot( lightDirection );
  32777. const dotTV = anisotropyT.dot( positionViewDirection );
  32778. const dotTH = anisotropyT.dot( halfDir );
  32779. const dotBL = anisotropyB.dot( lightDirection );
  32780. const dotBV = anisotropyB.dot( positionViewDirection );
  32781. const dotBH = anisotropyB.dot( halfDir );
  32782. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  32783. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  32784. } else {
  32785. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  32786. D = D_GGX( { alpha, dotNH } );
  32787. }
  32788. return F.mul( V ).mul( D );
  32789. } ); // validated
  32790. // Analytical approximation of the DFG LUT, one half of the
  32791. // split-sum approximation used in indirect specular lighting.
  32792. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  32793. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  32794. const DFGApprox = tslFn( ( { roughness, dotNV } ) => {
  32795. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  32796. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  32797. const r = roughness.mul( c0 ).add( c1 );
  32798. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  32799. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  32800. return fab;
  32801. } ).setLayout( {
  32802. name: 'DFGApprox',
  32803. type: 'vec2',
  32804. inputs: [
  32805. { name: 'roughness', type: 'float' },
  32806. { name: 'dotNV', type: 'vec3' }
  32807. ]
  32808. } );
  32809. const EnvironmentBRDF = tslFn( ( inputs ) => {
  32810. const { dotNV, specularColor, specularF90, roughness } = inputs;
  32811. const fab = DFGApprox( { dotNV, roughness } );
  32812. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  32813. } );
  32814. const Schlick_to_F0 = tslFn( ( { f, f90, dotVH } ) => {
  32815. const x = dotVH.oneMinus().saturate();
  32816. const x2 = x.mul( x );
  32817. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  32818. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  32819. } ).setLayout( {
  32820. name: 'Schlick_to_F0',
  32821. type: 'vec3',
  32822. inputs: [
  32823. { name: 'f', type: 'vec3' },
  32824. { name: 'f90', type: 'float' },
  32825. { name: 'dotVH', type: 'float' }
  32826. ]
  32827. } );
  32828. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32829. const D_Charlie = tslFn( ( { roughness, dotNH } ) => {
  32830. const alpha = roughness.pow2();
  32831. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  32832. const invAlpha = float( 1.0 ).div( alpha );
  32833. const cos2h = dotNH.pow2();
  32834. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  32835. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  32836. } ).setLayout( {
  32837. name: 'D_Charlie',
  32838. type: 'float',
  32839. inputs: [
  32840. { name: 'roughness', type: 'float' },
  32841. { name: 'dotNH', type: 'float' }
  32842. ]
  32843. } );
  32844. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  32845. const V_Neubelt = tslFn( ( { dotNV, dotNL } ) => {
  32846. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  32847. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  32848. } ).setLayout( {
  32849. name: 'V_Neubelt',
  32850. type: 'float',
  32851. inputs: [
  32852. { name: 'dotNV', type: 'float' },
  32853. { name: 'dotNL', type: 'float' }
  32854. ]
  32855. } );
  32856. const BRDF_Sheen = tslFn( ( { lightDirection } ) => {
  32857. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  32858. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  32859. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  32860. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  32861. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  32862. const V = V_Neubelt( { dotNV, dotNL } );
  32863. return sheen.mul( D ).mul( V );
  32864. } );
  32865. // Rect Area Light
  32866. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  32867. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  32868. // code: https://github.com/selfshadow/ltc_code/
  32869. const LTC_Uv = tslFn( ( { N, V, roughness } ) => {
  32870. const LUT_SIZE = 64.0;
  32871. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  32872. const LUT_BIAS = 0.5 / LUT_SIZE;
  32873. const dotNV = N.dot( V ).saturate();
  32874. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  32875. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  32876. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  32877. return uv;
  32878. } ).setLayout( {
  32879. name: 'LTC_Uv',
  32880. type: 'vec2',
  32881. inputs: [
  32882. { name: 'N', type: 'vec3' },
  32883. { name: 'V', type: 'vec3' },
  32884. { name: 'roughness', type: 'float' }
  32885. ]
  32886. } );
  32887. const LTC_ClippedSphereFormFactor = tslFn( ( { f } ) => {
  32888. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  32889. // An approximation of the form factor of a horizon-clipped rectangle.
  32890. const l = f.length();
  32891. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  32892. } ).setLayout( {
  32893. name: 'LTC_ClippedSphereFormFactor',
  32894. type: 'float',
  32895. inputs: [
  32896. { name: 'f', type: 'vec3' }
  32897. ]
  32898. } );
  32899. const LTC_EdgeVectorFormFactor = tslFn( ( { v1, v2 } ) => {
  32900. const x = v1.dot( v2 );
  32901. const y = x.abs().toVar();
  32902. // rational polynomial approximation to theta / sin( theta ) / 2PI
  32903. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  32904. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  32905. const v = a.div( b );
  32906. const theta_sintheta = x.greaterThan( 0.0 ).cond( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  32907. return v1.cross( v2 ).mul( theta_sintheta );
  32908. } ).setLayout( {
  32909. name: 'LTC_EdgeVectorFormFactor',
  32910. type: 'vec3',
  32911. inputs: [
  32912. { name: 'v1', type: 'vec3' },
  32913. { name: 'v2', type: 'vec3' }
  32914. ]
  32915. } );
  32916. const LTC_Evaluate = tslFn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  32917. // bail if point is on back side of plane of light
  32918. // assumes ccw winding order of light vertices
  32919. const v1 = p1.sub( p0 ).toVar();
  32920. const v2 = p3.sub( p0 ).toVar();
  32921. const lightNormal = v1.cross( v2 );
  32922. const result = vec3().toVar();
  32923. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  32924. // construct orthonormal basis around N
  32925. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  32926. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  32927. // compute transform
  32928. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  32929. // transform rect
  32930. // & project rect onto sphere
  32931. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  32932. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  32933. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  32934. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  32935. // calculate vector form factor
  32936. const vectorFormFactor = vec3( 0 ).toVar();
  32937. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  32938. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  32939. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  32940. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  32941. // adjust for horizon clipping
  32942. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  32943. } );
  32944. return result;
  32945. } ).setLayout( {
  32946. name: 'LTC_Evaluate',
  32947. type: 'vec3',
  32948. inputs: [
  32949. { name: 'N', type: 'vec3' },
  32950. { name: 'V', type: 'vec3' },
  32951. { name: 'P', type: 'vec3' },
  32952. { name: 'mInv', type: 'mat3' },
  32953. { name: 'p0', type: 'vec3' },
  32954. { name: 'p1', type: 'vec3' },
  32955. { name: 'p2', type: 'vec3' },
  32956. { name: 'p3', type: 'vec3' }
  32957. ]
  32958. } );
  32959. //
  32960. // Transmission
  32961. //
  32962. const getVolumeTransmissionRay = tslFn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  32963. // Direction of refracted light.
  32964. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  32965. // Compute rotation-independant scaling of the model matrix.
  32966. const modelScale = vec3(
  32967. length( modelMatrix[ 0 ].xyz ),
  32968. length( modelMatrix[ 1 ].xyz ),
  32969. length( modelMatrix[ 2 ].xyz )
  32970. );
  32971. // The thickness is specified in local space.
  32972. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  32973. } ).setLayout( {
  32974. name: 'getVolumeTransmissionRay',
  32975. type: 'vec3',
  32976. inputs: [
  32977. { name: 'n', type: 'vec3' },
  32978. { name: 'v', type: 'vec3' },
  32979. { name: 'thickness', type: 'float' },
  32980. { name: 'ior', type: 'float' },
  32981. { name: 'modelMatrix', type: 'mat4' }
  32982. ]
  32983. } );
  32984. const applyIorToRoughness = tslFn( ( [ roughness, ior ] ) => {
  32985. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  32986. // an IOR of 1.5 results in the default amount of microfacet refraction.
  32987. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  32988. } ).setLayout( {
  32989. name: 'applyIorToRoughness',
  32990. type: 'float',
  32991. inputs: [
  32992. { name: 'roughness', type: 'float' },
  32993. { name: 'ior', type: 'float' }
  32994. ]
  32995. } );
  32996. const singleViewportMipTexture = viewportMipTexture();
  32997. const getTransmissionSample = tslFn( ( [ fragCoord, roughness, ior ] ) => {
  32998. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  32999. //const transmissionSample = viewportMipTexture( fragCoord );
  33000. const lod = log2( float( viewportResolution.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  33001. return transmissionSample.bicubic( lod );
  33002. } );
  33003. const volumeAttenuation = tslFn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  33004. If( attenuationDistance.notEqual( 0 ), () => {
  33005. // Compute light attenuation using Beer's law.
  33006. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  33007. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  33008. return transmittance;
  33009. } );
  33010. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  33011. return vec3( 1.0 );
  33012. } ).setLayout( {
  33013. name: 'volumeAttenuation',
  33014. type: 'vec3',
  33015. inputs: [
  33016. { name: 'transmissionDistance', type: 'float' },
  33017. { name: 'attenuationColor', type: 'vec3' },
  33018. { name: 'attenuationDistance', type: 'float' }
  33019. ]
  33020. } );
  33021. const getIBLVolumeRefraction = tslFn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  33022. let transmittedLight, transmittance;
  33023. if ( dispersion ) {
  33024. transmittedLight = vec4().toVar();
  33025. transmittance = vec3().toVar();
  33026. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  33027. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  33028. loop( { start: 0, end: 3 }, ( { i } ) => {
  33029. const ior = iors.element( i );
  33030. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  33031. const refractedRayExit = position.add( transmissionRay );
  33032. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  33033. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  33034. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  33035. refractionCoords.addAssign( 1.0 );
  33036. refractionCoords.divAssign( 2.0 );
  33037. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  33038. // Sample framebuffer to get pixel the refracted ray hits.
  33039. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  33040. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  33041. transmittedLight.a.addAssign( transmissionSample.a );
  33042. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  33043. } );
  33044. transmittedLight.a.divAssign( 3.0 );
  33045. } else {
  33046. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  33047. const refractedRayExit = position.add( transmissionRay );
  33048. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  33049. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  33050. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  33051. refractionCoords.addAssign( 1.0 );
  33052. refractionCoords.divAssign( 2.0 );
  33053. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  33054. // Sample framebuffer to get pixel the refracted ray hits.
  33055. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  33056. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  33057. }
  33058. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  33059. const dotNV = n.dot( v ).clamp();
  33060. // Get the specular component.
  33061. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  33062. dotNV,
  33063. specularColor,
  33064. specularF90,
  33065. roughness
  33066. } ) );
  33067. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  33068. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  33069. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  33070. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  33071. } );
  33072. //
  33073. // Iridescence
  33074. //
  33075. // XYZ to linear-sRGB color space
  33076. const XYZ_TO_REC709 = mat3(
  33077. 3.2404542, - 0.9692660, 0.0556434,
  33078. - 1.5371385, 1.8760108, - 0.2040259,
  33079. - 0.4985314, 0.0415560, 1.0572252
  33080. );
  33081. // Assume air interface for top
  33082. // Note: We don't handle the case fresnel0 == 1
  33083. const Fresnel0ToIor = ( fresnel0 ) => {
  33084. const sqrtF0 = fresnel0.sqrt();
  33085. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  33086. };
  33087. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  33088. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  33089. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  33090. };
  33091. // Fresnel equations for dielectric/dielectric interfaces.
  33092. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  33093. // Evaluation XYZ sensitivity curves in Fourier space
  33094. const evalSensitivity = ( OPD, shift ) => {
  33095. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  33096. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  33097. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  33098. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  33099. 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() );
  33100. 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() );
  33101. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  33102. const rgb = XYZ_TO_REC709.mul( xyz );
  33103. return rgb;
  33104. };
  33105. const evalIridescence = tslFn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  33106. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  33107. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  33108. // Evaluate the cosTheta on the base layer (Snell law)
  33109. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  33110. // Handle TIR:
  33111. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  33112. /*if ( cosTheta2Sq < 0.0 ) {
  33113. return vec3( 1.0 );
  33114. }*/
  33115. const cosTheta2 = cosTheta2Sq.sqrt();
  33116. // First interface
  33117. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  33118. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  33119. //const R21 = R12;
  33120. const T121 = R12.oneMinus();
  33121. const phi12 = iridescenceIOR.lessThan( outsideIOR ).cond( Math.PI, 0.0 );
  33122. const phi21 = float( Math.PI ).sub( phi12 );
  33123. // Second interface
  33124. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  33125. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  33126. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  33127. const phi23 = vec3(
  33128. baseIOR.x.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  33129. baseIOR.y.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  33130. baseIOR.z.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 )
  33131. );
  33132. // Phase shift
  33133. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  33134. const phi = vec3( phi21 ).add( phi23 );
  33135. // Compound terms
  33136. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  33137. const r123 = R123.sqrt();
  33138. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  33139. // Reflectance term for m = 0 (DC term amplitude)
  33140. const C0 = R12.add( Rs );
  33141. let I = C0;
  33142. // Reflectance term for m > 0 (pairs of diracs)
  33143. let Cm = Rs.sub( T121 );
  33144. for ( let m = 1; m <= 2; ++ m ) {
  33145. Cm = Cm.mul( r123 );
  33146. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  33147. I = I.add( Cm.mul( Sm ) );
  33148. }
  33149. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  33150. return I.max( vec3( 0.0 ) );
  33151. } ).setLayout( {
  33152. name: 'evalIridescence',
  33153. type: 'vec3',
  33154. inputs: [
  33155. { name: 'outsideIOR', type: 'float' },
  33156. { name: 'eta2', type: 'float' },
  33157. { name: 'cosTheta1', type: 'float' },
  33158. { name: 'thinFilmThickness', type: 'float' },
  33159. { name: 'baseF0', type: 'vec3' }
  33160. ]
  33161. } );
  33162. //
  33163. // Sheen
  33164. //
  33165. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  33166. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  33167. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  33168. const IBLSheenBRDF = tslFn( ( { normal, viewDir, roughness } ) => {
  33169. const dotNV = normal.dot( viewDir ).saturate();
  33170. const r2 = roughness.pow2();
  33171. const a = cond(
  33172. roughness.lessThan( 0.25 ),
  33173. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  33174. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  33175. );
  33176. const b = cond(
  33177. roughness.lessThan( 0.25 ),
  33178. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  33179. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  33180. );
  33181. const DG = cond( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  33182. return DG.mul( 1.0 / Math.PI ).saturate();
  33183. } );
  33184. const clearcoatF0 = vec3( 0.04 );
  33185. const clearcoatF90 = float( 1 );
  33186. //
  33187. class PhysicalLightingModel extends LightingModel {
  33188. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  33189. super();
  33190. this.clearcoat = clearcoat;
  33191. this.sheen = sheen;
  33192. this.iridescence = iridescence;
  33193. this.anisotropy = anisotropy;
  33194. this.transmission = transmission;
  33195. this.dispersion = dispersion;
  33196. this.clearcoatRadiance = null;
  33197. this.clearcoatSpecularDirect = null;
  33198. this.clearcoatSpecularIndirect = null;
  33199. this.sheenSpecularDirect = null;
  33200. this.sheenSpecularIndirect = null;
  33201. this.iridescenceFresnel = null;
  33202. this.iridescenceF0 = null;
  33203. }
  33204. start( context ) {
  33205. if ( this.clearcoat === true ) {
  33206. this.clearcoatRadiance = vec3().temp( 'clearcoatRadiance' );
  33207. this.clearcoatSpecularDirect = vec3().temp( 'clearcoatSpecularDirect' );
  33208. this.clearcoatSpecularIndirect = vec3().temp( 'clearcoatSpecularIndirect' );
  33209. }
  33210. if ( this.sheen === true ) {
  33211. this.sheenSpecularDirect = vec3().temp( 'sheenSpecularDirect' );
  33212. this.sheenSpecularIndirect = vec3().temp( 'sheenSpecularIndirect' );
  33213. }
  33214. if ( this.iridescence === true ) {
  33215. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  33216. this.iridescenceFresnel = evalIridescence( {
  33217. outsideIOR: float( 1.0 ),
  33218. eta2: iridescenceIOR,
  33219. cosTheta1: dotNVi,
  33220. thinFilmThickness: iridescenceThickness,
  33221. baseF0: specularColor
  33222. } );
  33223. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  33224. }
  33225. if ( this.transmission === true ) {
  33226. const position = positionWorld;
  33227. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  33228. const n = transformedNormalWorld;
  33229. context.backdrop = getIBLVolumeRefraction(
  33230. n,
  33231. v,
  33232. roughness,
  33233. diffuseColor,
  33234. specularColor,
  33235. specularF90, // specularF90
  33236. position, // positionWorld
  33237. modelWorldMatrix, // modelMatrix
  33238. cameraViewMatrix, // viewMatrix
  33239. cameraProjectionMatrix, // projMatrix
  33240. ior,
  33241. thickness,
  33242. attenuationColor,
  33243. attenuationDistance,
  33244. this.dispersion ? dispersion : null
  33245. );
  33246. context.backdropAlpha = transmission;
  33247. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  33248. }
  33249. }
  33250. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  33251. // Approximates multiscattering in order to preserve energy.
  33252. // http://www.jcgt.org/published/0008/01/03/
  33253. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  33254. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  33255. const fab = DFGApprox( { roughness, dotNV } );
  33256. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  33257. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  33258. const Ess = fab.x.add( fab.y );
  33259. const Ems = Ess.oneMinus();
  33260. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  33261. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  33262. singleScatter.addAssign( FssEss );
  33263. multiScatter.addAssign( Fms.mul( Ems ) );
  33264. }
  33265. direct( { lightDirection, lightColor, reflectedLight } ) {
  33266. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  33267. const irradiance = dotNL.mul( lightColor );
  33268. if ( this.sheen === true ) {
  33269. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  33270. }
  33271. if ( this.clearcoat === true ) {
  33272. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  33273. const ccIrradiance = dotNLcc.mul( lightColor );
  33274. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  33275. }
  33276. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33277. 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 } ) ) );
  33278. }
  33279. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  33280. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  33281. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  33282. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  33283. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  33284. const N = transformedNormalView;
  33285. const V = positionViewDirection;
  33286. const P = positionView.toVar();
  33287. const uv = LTC_Uv( { N, V, roughness } );
  33288. const t1 = ltc_1.uv( uv ).toVar();
  33289. const t2 = ltc_2.uv( uv ).toVar();
  33290. const mInv = mat3(
  33291. vec3( t1.x, 0, t1.y ),
  33292. vec3( 0, 1, 0 ),
  33293. vec3( t1.z, 0, t1.w )
  33294. ).toVar();
  33295. // LTC Fresnel Approximation by Stephen Hill
  33296. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  33297. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  33298. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  33299. 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 } ) ) );
  33300. }
  33301. indirect( context, stack, builder ) {
  33302. this.indirectDiffuse( context, stack, builder );
  33303. this.indirectSpecular( context, stack, builder );
  33304. this.ambientOcclusion( context, stack, builder );
  33305. }
  33306. indirectDiffuse( { irradiance, reflectedLight } ) {
  33307. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33308. }
  33309. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  33310. if ( this.sheen === true ) {
  33311. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  33312. sheen,
  33313. IBLSheenBRDF( {
  33314. normal: transformedNormalView,
  33315. viewDir: positionViewDirection,
  33316. roughness: sheenRoughness
  33317. } )
  33318. ) );
  33319. }
  33320. if ( this.clearcoat === true ) {
  33321. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  33322. const clearcoatEnv = EnvironmentBRDF( {
  33323. dotNV: dotNVcc,
  33324. specularColor: clearcoatF0,
  33325. specularF90: clearcoatF90,
  33326. roughness: clearcoatRoughness
  33327. } );
  33328. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  33329. }
  33330. // Both indirect specular and indirect diffuse light accumulate here
  33331. const singleScattering = vec3().temp( 'singleScattering' );
  33332. const multiScattering = vec3().temp( 'multiScattering' );
  33333. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  33334. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  33335. const totalScattering = singleScattering.add( multiScattering );
  33336. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  33337. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  33338. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  33339. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  33340. }
  33341. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  33342. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  33343. const aoNV = dotNV.add( ambientOcclusion );
  33344. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  33345. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  33346. if ( this.clearcoat === true ) {
  33347. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  33348. }
  33349. if ( this.sheen === true ) {
  33350. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  33351. }
  33352. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33353. reflectedLight.indirectSpecular.mulAssign( aoNode );
  33354. }
  33355. finish( context ) {
  33356. const { outgoingLight } = context;
  33357. if ( this.clearcoat === true ) {
  33358. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  33359. const Fcc = F_Schlick( {
  33360. dotVH: dotNVcc,
  33361. f0: clearcoatF0,
  33362. f90: clearcoatF90
  33363. } );
  33364. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  33365. outgoingLight.assign( clearcoatLight );
  33366. }
  33367. if ( this.sheen === true ) {
  33368. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  33369. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  33370. outgoingLight.assign( sheenLight );
  33371. }
  33372. }
  33373. }
  33374. const defaultValues$6 = new MeshStandardMaterial();
  33375. class MeshStandardNodeMaterial extends NodeMaterial {
  33376. constructor( parameters ) {
  33377. super();
  33378. this.isMeshStandardNodeMaterial = true;
  33379. this.emissiveNode = null;
  33380. this.metalnessNode = null;
  33381. this.roughnessNode = null;
  33382. this.setDefaultValues( defaultValues$6 );
  33383. this.setValues( parameters );
  33384. }
  33385. setupEnvironment( builder ) {
  33386. const envNode = super.setupEnvironment( builder );
  33387. return envNode ? new EnvironmentNode( envNode ) : null;
  33388. }
  33389. setupLightingModel( /*builder*/ ) {
  33390. return new PhysicalLightingModel();
  33391. }
  33392. setupSpecular() {
  33393. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  33394. specularColor.assign( specularColorNode );
  33395. specularF90.assign( 1.0 );
  33396. }
  33397. setupVariants() {
  33398. // METALNESS
  33399. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  33400. metalness.assign( metalnessNode );
  33401. // ROUGHNESS
  33402. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  33403. roughnessNode = getRoughness( { roughness: roughnessNode } );
  33404. roughness.assign( roughnessNode );
  33405. // SPECULAR COLOR
  33406. this.setupSpecular();
  33407. // DIFFUSE COLOR
  33408. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  33409. }
  33410. copy( source ) {
  33411. this.emissiveNode = source.emissiveNode;
  33412. this.metalnessNode = source.metalnessNode;
  33413. this.roughnessNode = source.roughnessNode;
  33414. return super.copy( source );
  33415. }
  33416. }
  33417. addNodeMaterial( 'MeshStandardNodeMaterial', MeshStandardNodeMaterial );
  33418. const defaultValues$5 = new MeshPhysicalMaterial();
  33419. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  33420. constructor( parameters ) {
  33421. super();
  33422. this.isMeshPhysicalNodeMaterial = true;
  33423. this.clearcoatNode = null;
  33424. this.clearcoatRoughnessNode = null;
  33425. this.clearcoatNormalNode = null;
  33426. this.sheenNode = null;
  33427. this.sheenRoughnessNode = null;
  33428. this.iridescenceNode = null;
  33429. this.iridescenceIORNode = null;
  33430. this.iridescenceThicknessNode = null;
  33431. this.specularIntensityNode = null;
  33432. this.specularColorNode = null;
  33433. this.iorNode = null;
  33434. this.transmissionNode = null;
  33435. this.thicknessNode = null;
  33436. this.attenuationDistanceNode = null;
  33437. this.attenuationColorNode = null;
  33438. this.dispersionNode = null;
  33439. this.anisotropyNode = null;
  33440. this.setDefaultValues( defaultValues$5 );
  33441. this.setValues( parameters );
  33442. }
  33443. get useClearcoat() {
  33444. return this.clearcoat > 0 || this.clearcoatNode !== null;
  33445. }
  33446. get useIridescence() {
  33447. return this.iridescence > 0 || this.iridescenceNode !== null;
  33448. }
  33449. get useSheen() {
  33450. return this.sheen > 0 || this.sheenNode !== null;
  33451. }
  33452. get useAnisotropy() {
  33453. return this.anisotropy > 0 || this.anisotropyNode !== null;
  33454. }
  33455. get useTransmission() {
  33456. return this.transmission > 0 || this.transmissionNode !== null;
  33457. }
  33458. get useDispersion() {
  33459. return this.dispersion > 0 || this.dispersionNode !== null;
  33460. }
  33461. setupSpecular() {
  33462. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  33463. ior.assign( iorNode );
  33464. 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 ) );
  33465. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  33466. }
  33467. setupLightingModel( /*builder*/ ) {
  33468. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  33469. }
  33470. setupVariants( builder ) {
  33471. super.setupVariants( builder );
  33472. // CLEARCOAT
  33473. if ( this.useClearcoat ) {
  33474. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  33475. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  33476. clearcoat.assign( clearcoatNode );
  33477. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  33478. }
  33479. // SHEEN
  33480. if ( this.useSheen ) {
  33481. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  33482. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  33483. sheen.assign( sheenNode );
  33484. sheenRoughness.assign( sheenRoughnessNode );
  33485. }
  33486. // IRIDESCENCE
  33487. if ( this.useIridescence ) {
  33488. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  33489. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  33490. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  33491. iridescence.assign( iridescenceNode );
  33492. iridescenceIOR.assign( iridescenceIORNode );
  33493. iridescenceThickness.assign( iridescenceThicknessNode );
  33494. }
  33495. // ANISOTROPY
  33496. if ( this.useAnisotropy ) {
  33497. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  33498. anisotropy.assign( anisotropyV.length() );
  33499. If( anisotropy.equal( 0.0 ), () => {
  33500. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  33501. } ).else( () => {
  33502. anisotropyV.divAssign( vec2( anisotropy ) );
  33503. anisotropy.assign( anisotropy.saturate() );
  33504. } );
  33505. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  33506. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  33507. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  33508. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  33509. }
  33510. // TRANSMISSION
  33511. if ( this.useTransmission ) {
  33512. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  33513. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  33514. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  33515. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  33516. transmission.assign( transmissionNode );
  33517. thickness.assign( thicknessNode );
  33518. attenuationDistance.assign( attenuationDistanceNode );
  33519. attenuationColor.assign( attenuationColorNode );
  33520. if ( this.useDispersion ) {
  33521. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  33522. dispersion.assign( dispersionNode );
  33523. }
  33524. }
  33525. }
  33526. setupNormal( builder ) {
  33527. super.setupNormal( builder );
  33528. // CLEARCOAT NORMAL
  33529. const clearcoatNormalNode = this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  33530. transformedClearcoatNormalView.assign( clearcoatNormalNode );
  33531. }
  33532. copy( source ) {
  33533. this.clearcoatNode = source.clearcoatNode;
  33534. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  33535. this.clearcoatNormalNode = source.clearcoatNormalNode;
  33536. this.sheenNode = source.sheenNode;
  33537. this.sheenRoughnessNode = source.sheenRoughnessNode;
  33538. this.iridescenceNode = source.iridescenceNode;
  33539. this.iridescenceIORNode = source.iridescenceIORNode;
  33540. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  33541. this.specularIntensityNode = source.specularIntensityNode;
  33542. this.specularColorNode = source.specularColorNode;
  33543. this.transmissionNode = source.transmissionNode;
  33544. this.thicknessNode = source.thicknessNode;
  33545. this.attenuationDistanceNode = source.attenuationDistanceNode;
  33546. this.attenuationColorNode = source.attenuationColorNode;
  33547. this.dispersionNode = source.dispersionNode;
  33548. this.anisotropyNode = source.anisotropyNode;
  33549. return super.copy( source );
  33550. }
  33551. }
  33552. addNodeMaterial( 'MeshPhysicalNodeMaterial', MeshPhysicalNodeMaterial );
  33553. class SSSLightingModel extends PhysicalLightingModel {
  33554. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  33555. super( useClearcoat, useSheen, useIridescence );
  33556. this.useSSS = useSSS;
  33557. }
  33558. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33559. if ( this.useSSS === true ) {
  33560. const material = builder.material;
  33561. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  33562. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  33563. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  33564. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  33565. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  33566. }
  33567. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  33568. }
  33569. }
  33570. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  33571. constructor( parameters ) {
  33572. super( parameters );
  33573. this.thicknessColorNode = null;
  33574. this.thicknessDistortionNode = float( 0.1 );
  33575. this.thicknessAmbientNode = float( 0.0 );
  33576. this.thicknessAttenuationNode = float( .1 );
  33577. this.thicknessPowerNode = float( 2.0 );
  33578. this.thicknessScaleNode = float( 10.0 );
  33579. }
  33580. get useSSS() {
  33581. return this.thicknessColorNode !== null;
  33582. }
  33583. setupLightingModel( /*builder*/ ) {
  33584. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  33585. }
  33586. copy( source ) {
  33587. this.thicknessColorNode = source.thicknessColorNode;
  33588. this.thicknessDistortionNode = source.thicknessDistortionNode;
  33589. this.thicknessAmbientNode = source.thicknessAmbientNode;
  33590. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  33591. this.thicknessPowerNode = source.thicknessPowerNode;
  33592. this.thicknessScaleNode = source.thicknessScaleNode;
  33593. return super.copy( source );
  33594. }
  33595. }
  33596. addNodeMaterial( 'MeshSSSNodeMaterial', MeshSSSNodeMaterial );
  33597. const getGradientIrradiance = tslFn( ( { normal, lightDirection, builder } ) => {
  33598. // dotNL will be from -1.0 to 1.0
  33599. const dotNL = normal.dot( lightDirection );
  33600. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  33601. if ( builder.material.gradientMap ) {
  33602. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  33603. return vec3( gradientMap.r );
  33604. } else {
  33605. const fw = coord.fwidth().mul( 0.5 );
  33606. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  33607. }
  33608. } );
  33609. class ToonLightingModel extends LightingModel {
  33610. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  33611. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  33612. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33613. }
  33614. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  33615. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33616. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33617. }
  33618. }
  33619. const defaultValues$4 = new MeshToonMaterial();
  33620. class MeshToonNodeMaterial extends NodeMaterial {
  33621. constructor( parameters ) {
  33622. super();
  33623. this.isMeshToonNodeMaterial = true;
  33624. this.lights = true;
  33625. this.setDefaultValues( defaultValues$4 );
  33626. this.setValues( parameters );
  33627. }
  33628. setupLightingModel( /*builder*/ ) {
  33629. return new ToonLightingModel();
  33630. }
  33631. }
  33632. addNodeMaterial( 'MeshToonNodeMaterial', MeshToonNodeMaterial );
  33633. const defaultValues$3 = new MeshMatcapMaterial();
  33634. class MeshMatcapNodeMaterial extends NodeMaterial {
  33635. constructor( parameters ) {
  33636. super();
  33637. this.lights = false;
  33638. this.isMeshMatcapNodeMaterial = true;
  33639. this.setDefaultValues( defaultValues$3 );
  33640. this.setValues( parameters );
  33641. }
  33642. setupVariants( builder ) {
  33643. const uv = matcapUV;
  33644. let matcapColor;
  33645. if ( builder.material.matcap ) {
  33646. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  33647. } else {
  33648. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  33649. }
  33650. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  33651. }
  33652. }
  33653. addNodeMaterial( 'MeshMatcapNodeMaterial', MeshMatcapNodeMaterial );
  33654. const defaultValues$2 = new PointsMaterial();
  33655. class PointsNodeMaterial extends NodeMaterial {
  33656. constructor( parameters ) {
  33657. super();
  33658. this.isPointsNodeMaterial = true;
  33659. this.lights = false;
  33660. this.normals = false;
  33661. this.transparent = true;
  33662. this.sizeNode = null;
  33663. this.setDefaultValues( defaultValues$2 );
  33664. this.setValues( parameters );
  33665. }
  33666. copy( source ) {
  33667. this.sizeNode = source.sizeNode;
  33668. return super.copy( source );
  33669. }
  33670. }
  33671. addNodeMaterial( 'PointsNodeMaterial', PointsNodeMaterial );
  33672. const defaultValues$1 = new SpriteMaterial();
  33673. class SpriteNodeMaterial extends NodeMaterial {
  33674. constructor( parameters ) {
  33675. super();
  33676. this.isSpriteNodeMaterial = true;
  33677. this.lights = false;
  33678. this.normals = false;
  33679. this.positionNode = null;
  33680. this.rotationNode = null;
  33681. this.scaleNode = null;
  33682. this.setDefaultValues( defaultValues$1 );
  33683. this.setValues( parameters );
  33684. }
  33685. setupPosition( { object, context } ) {
  33686. // < VERTEX STAGE >
  33687. const { positionNode, rotationNode, scaleNode } = this;
  33688. const vertex = positionLocal;
  33689. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  33690. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  33691. if ( scaleNode !== null ) {
  33692. scale = scale.mul( scaleNode );
  33693. }
  33694. let alignedPosition = vertex.xy;
  33695. if ( object.center && object.center.isVector2 === true ) {
  33696. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  33697. }
  33698. alignedPosition = alignedPosition.mul( scale );
  33699. const rotation = float( rotationNode || materialRotation );
  33700. const rotatedPosition = alignedPosition.rotate( rotation );
  33701. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  33702. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  33703. context.vertex = vertex;
  33704. return modelViewProjection;
  33705. }
  33706. copy( source ) {
  33707. this.positionNode = source.positionNode;
  33708. this.rotationNode = source.rotationNode;
  33709. this.scaleNode = source.scaleNode;
  33710. return super.copy( source );
  33711. }
  33712. }
  33713. addNodeMaterial( 'SpriteNodeMaterial', SpriteNodeMaterial );
  33714. class ShadowMaskModel extends LightingModel {
  33715. constructor() {
  33716. super();
  33717. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  33718. }
  33719. direct( { shadowMask } ) {
  33720. this.shadowNode.mulAssign( shadowMask );
  33721. }
  33722. finish( context ) {
  33723. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  33724. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  33725. }
  33726. }
  33727. const defaultValues = new ShadowMaterial();
  33728. class ShadowNodeMaterial extends NodeMaterial {
  33729. constructor( parameters ) {
  33730. super();
  33731. this.isShadowNodeMaterial = true;
  33732. this.lights = true;
  33733. this.setDefaultValues( defaultValues );
  33734. this.setValues( parameters );
  33735. }
  33736. setupLightingModel( /*builder*/ ) {
  33737. return new ShadowMaskModel();
  33738. }
  33739. }
  33740. addNodeMaterial( 'ShadowNodeMaterial', ShadowNodeMaterial );
  33741. class VolumeNodeMaterial extends NodeMaterial {
  33742. constructor( params = {} ) {
  33743. super();
  33744. this.normals = false;
  33745. this.lights = false;
  33746. this.isVolumeNodeMaterial = true;
  33747. this.testNode = null;
  33748. this.setValues( params );
  33749. }
  33750. setup( builder ) {
  33751. const map = texture3D( this.map, null, 0 );
  33752. const hitBox = tslFn( ( { orig, dir } ) => {
  33753. const box_min = vec3( - 0.5 );
  33754. const box_max = vec3( 0.5 );
  33755. const inv_dir = dir.reciprocal();
  33756. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  33757. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  33758. const tmin = min$1( tmin_tmp, tmax_tmp );
  33759. const tmax = max$1( tmin_tmp, tmax_tmp );
  33760. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  33761. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  33762. return vec2( t0, t1 );
  33763. } );
  33764. this.fragmentNode = tslFn( () => {
  33765. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  33766. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  33767. const rayDir = vDirection.normalize();
  33768. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  33769. bounds.x.greaterThan( bounds.y ).discard();
  33770. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  33771. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  33772. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  33773. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  33774. delta.divAssign( materialReference( 'steps', 'float' ) );
  33775. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  33776. loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  33777. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  33778. if ( this.testNode !== null ) {
  33779. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  33780. } else {
  33781. // default to show surface of mesh
  33782. ac.a.assign( 1 );
  33783. Break();
  33784. }
  33785. p.addAssign( rayDir.mul( delta ) );
  33786. } );
  33787. ac.a.equal( 0 ).discard();
  33788. return vec4( ac );
  33789. } )();
  33790. super.setup( builder );
  33791. }
  33792. }
  33793. addNodeMaterial( 'VolumeNodeMaterial', VolumeNodeMaterial );
  33794. const superFromTypeFunction = MaterialLoader.createMaterialFromType;
  33795. MaterialLoader.createMaterialFromType = function ( type ) {
  33796. const material = createNodeMaterialFromType( type );
  33797. if ( material !== undefined ) {
  33798. return material;
  33799. }
  33800. return superFromTypeFunction.call( this, type );
  33801. };
  33802. class NodeMaterialLoader extends MaterialLoader {
  33803. constructor( manager ) {
  33804. super( manager );
  33805. this.nodes = {};
  33806. }
  33807. parse( json ) {
  33808. const material = super.parse( json );
  33809. const nodes = this.nodes;
  33810. const inputNodes = json.inputNodes;
  33811. for ( const property in inputNodes ) {
  33812. const uuid = inputNodes[ property ];
  33813. material[ property ] = nodes[ uuid ];
  33814. }
  33815. return material;
  33816. }
  33817. setNodes( value ) {
  33818. this.nodes = value;
  33819. return this;
  33820. }
  33821. }
  33822. class NodeObjectLoader extends ObjectLoader {
  33823. constructor( manager ) {
  33824. super( manager );
  33825. this._nodesJSON = null;
  33826. }
  33827. parse( json, onLoad ) {
  33828. this._nodesJSON = json.nodes;
  33829. const data = super.parse( json, onLoad );
  33830. this._nodesJSON = null; // dispose
  33831. return data;
  33832. }
  33833. parseNodes( json, textures ) {
  33834. if ( json !== undefined ) {
  33835. const loader = new NodeLoader();
  33836. loader.setTextures( textures );
  33837. return loader.parseNodes( json );
  33838. }
  33839. return {};
  33840. }
  33841. parseMaterials( json, textures ) {
  33842. const materials = {};
  33843. if ( json !== undefined ) {
  33844. const nodes = this.parseNodes( this._nodesJSON, textures );
  33845. const loader = new NodeMaterialLoader();
  33846. loader.setTextures( textures );
  33847. loader.setNodes( nodes );
  33848. for ( let i = 0, l = json.length; i < l; i ++ ) {
  33849. const data = json[ i ];
  33850. materials[ data.uuid ] = loader.parse( data );
  33851. }
  33852. }
  33853. return materials;
  33854. }
  33855. }
  33856. class NodeParser {
  33857. parseFunction( /*source*/ ) {
  33858. console.warn( 'Abstract function.' );
  33859. }
  33860. }
  33861. class NodeFunction {
  33862. constructor( type, inputs, name = '', precision = '' ) {
  33863. this.type = type;
  33864. this.inputs = inputs;
  33865. this.name = name;
  33866. this.precision = precision;
  33867. }
  33868. getCode( /*name = this.name*/ ) {
  33869. console.warn( 'Abstract function.' );
  33870. }
  33871. }
  33872. NodeFunction.isNodeFunction = true;
  33873. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  33874. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  33875. const pragmaMain = '#pragma main';
  33876. const parse$1 = ( source ) => {
  33877. source = source.trim();
  33878. const pragmaMainIndex = source.indexOf( pragmaMain );
  33879. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  33880. const declaration = mainCode.match( declarationRegexp$1 );
  33881. if ( declaration !== null && declaration.length === 5 ) {
  33882. // tokenizer
  33883. const inputsCode = declaration[ 4 ];
  33884. const propsMatches = [];
  33885. let nameMatch = null;
  33886. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  33887. propsMatches.push( nameMatch );
  33888. }
  33889. // parser
  33890. const inputs = [];
  33891. let i = 0;
  33892. while ( i < propsMatches.length ) {
  33893. const isConst = propsMatches[ i ][ 0 ] === 'const';
  33894. if ( isConst === true ) {
  33895. i ++;
  33896. }
  33897. let qualifier = propsMatches[ i ][ 0 ];
  33898. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  33899. i ++;
  33900. } else {
  33901. qualifier = '';
  33902. }
  33903. const type = propsMatches[ i ++ ][ 0 ];
  33904. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  33905. if ( Number.isNaN( count ) === false ) i ++;
  33906. else count = null;
  33907. const name = propsMatches[ i ++ ][ 0 ];
  33908. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  33909. }
  33910. //
  33911. const blockCode = mainCode.substring( declaration[ 0 ].length );
  33912. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  33913. const type = declaration[ 2 ];
  33914. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  33915. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  33916. return {
  33917. type,
  33918. inputs,
  33919. name,
  33920. precision,
  33921. inputsCode,
  33922. blockCode,
  33923. headerCode
  33924. };
  33925. } else {
  33926. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  33927. }
  33928. };
  33929. class GLSLNodeFunction extends NodeFunction {
  33930. constructor( source ) {
  33931. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  33932. super( type, inputs, name, precision );
  33933. this.inputsCode = inputsCode;
  33934. this.blockCode = blockCode;
  33935. this.headerCode = headerCode;
  33936. }
  33937. getCode( name = this.name ) {
  33938. let code;
  33939. const blockCode = this.blockCode;
  33940. if ( blockCode !== '' ) {
  33941. const { type, inputsCode, headerCode, precision } = this;
  33942. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  33943. if ( precision !== '' ) {
  33944. declarationCode = `${ precision } ${ declarationCode }`;
  33945. }
  33946. code = headerCode + declarationCode + blockCode;
  33947. } else {
  33948. // interface function
  33949. code = '';
  33950. }
  33951. return code;
  33952. }
  33953. }
  33954. class GLSLNodeParser extends NodeParser {
  33955. parseFunction( source ) {
  33956. return new GLSLNodeFunction( source );
  33957. }
  33958. }
  33959. // Three.js Transpiler
  33960. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33961. const mx_select = /*#__PURE__*/ tslFn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33962. const f = float( f_immutable ).toVar();
  33963. const t = float( t_immutable ).toVar();
  33964. const b = bool( b_immutable ).toVar();
  33965. return cond( b, t, f );
  33966. } ).setLayout( {
  33967. name: 'mx_select',
  33968. type: 'float',
  33969. inputs: [
  33970. { name: 'b', type: 'bool' },
  33971. { name: 't', type: 'float' },
  33972. { name: 'f', type: 'float' }
  33973. ]
  33974. } );
  33975. const mx_negate_if = /*#__PURE__*/ tslFn( ( [ val_immutable, b_immutable ] ) => {
  33976. const b = bool( b_immutable ).toVar();
  33977. const val = float( val_immutable ).toVar();
  33978. return cond( b, val.negate(), val );
  33979. } ).setLayout( {
  33980. name: 'mx_negate_if',
  33981. type: 'float',
  33982. inputs: [
  33983. { name: 'val', type: 'float' },
  33984. { name: 'b', type: 'bool' }
  33985. ]
  33986. } );
  33987. const mx_floor = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  33988. const x = float( x_immutable ).toVar();
  33989. return int( floor( x ) );
  33990. } ).setLayout( {
  33991. name: 'mx_floor',
  33992. type: 'int',
  33993. inputs: [
  33994. { name: 'x', type: 'float' }
  33995. ]
  33996. } );
  33997. const mx_floorfrac = /*#__PURE__*/ tslFn( ( [ x_immutable, i ] ) => {
  33998. const x = float( x_immutable ).toVar();
  33999. i.assign( mx_floor( x ) );
  34000. return x.sub( float( i ) );
  34001. } );
  34002. const mx_bilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  34003. const t = float( t_immutable ).toVar();
  34004. const s = float( s_immutable ).toVar();
  34005. const v3 = float( v3_immutable ).toVar();
  34006. const v2 = float( v2_immutable ).toVar();
  34007. const v1 = float( v1_immutable ).toVar();
  34008. const v0 = float( v0_immutable ).toVar();
  34009. const s1 = float( sub( 1.0, s ) ).toVar();
  34010. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  34011. } ).setLayout( {
  34012. name: 'mx_bilerp_0',
  34013. type: 'float',
  34014. inputs: [
  34015. { name: 'v0', type: 'float' },
  34016. { name: 'v1', type: 'float' },
  34017. { name: 'v2', type: 'float' },
  34018. { name: 'v3', type: 'float' },
  34019. { name: 's', type: 'float' },
  34020. { name: 't', type: 'float' }
  34021. ]
  34022. } );
  34023. const mx_bilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  34024. const t = float( t_immutable ).toVar();
  34025. const s = float( s_immutable ).toVar();
  34026. const v3 = vec3( v3_immutable ).toVar();
  34027. const v2 = vec3( v2_immutable ).toVar();
  34028. const v1 = vec3( v1_immutable ).toVar();
  34029. const v0 = vec3( v0_immutable ).toVar();
  34030. const s1 = float( sub( 1.0, s ) ).toVar();
  34031. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  34032. } ).setLayout( {
  34033. name: 'mx_bilerp_1',
  34034. type: 'vec3',
  34035. inputs: [
  34036. { name: 'v0', type: 'vec3' },
  34037. { name: 'v1', type: 'vec3' },
  34038. { name: 'v2', type: 'vec3' },
  34039. { name: 'v3', type: 'vec3' },
  34040. { name: 's', type: 'float' },
  34041. { name: 't', type: 'float' }
  34042. ]
  34043. } );
  34044. const mx_bilerp = /*#__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  34045. 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 ] ) => {
  34046. const r = float( r_immutable ).toVar();
  34047. const t = float( t_immutable ).toVar();
  34048. const s = float( s_immutable ).toVar();
  34049. const v7 = float( v7_immutable ).toVar();
  34050. const v6 = float( v6_immutable ).toVar();
  34051. const v5 = float( v5_immutable ).toVar();
  34052. const v4 = float( v4_immutable ).toVar();
  34053. const v3 = float( v3_immutable ).toVar();
  34054. const v2 = float( v2_immutable ).toVar();
  34055. const v1 = float( v1_immutable ).toVar();
  34056. const v0 = float( v0_immutable ).toVar();
  34057. const s1 = float( sub( 1.0, s ) ).toVar();
  34058. const t1 = float( sub( 1.0, t ) ).toVar();
  34059. const r1 = float( sub( 1.0, r ) ).toVar();
  34060. 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 ) ) ) ) ) );
  34061. } ).setLayout( {
  34062. name: 'mx_trilerp_0',
  34063. type: 'float',
  34064. inputs: [
  34065. { name: 'v0', type: 'float' },
  34066. { name: 'v1', type: 'float' },
  34067. { name: 'v2', type: 'float' },
  34068. { name: 'v3', type: 'float' },
  34069. { name: 'v4', type: 'float' },
  34070. { name: 'v5', type: 'float' },
  34071. { name: 'v6', type: 'float' },
  34072. { name: 'v7', type: 'float' },
  34073. { name: 's', type: 'float' },
  34074. { name: 't', type: 'float' },
  34075. { name: 'r', type: 'float' }
  34076. ]
  34077. } );
  34078. 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 ] ) => {
  34079. const r = float( r_immutable ).toVar();
  34080. const t = float( t_immutable ).toVar();
  34081. const s = float( s_immutable ).toVar();
  34082. const v7 = vec3( v7_immutable ).toVar();
  34083. const v6 = vec3( v6_immutable ).toVar();
  34084. const v5 = vec3( v5_immutable ).toVar();
  34085. const v4 = vec3( v4_immutable ).toVar();
  34086. const v3 = vec3( v3_immutable ).toVar();
  34087. const v2 = vec3( v2_immutable ).toVar();
  34088. const v1 = vec3( v1_immutable ).toVar();
  34089. const v0 = vec3( v0_immutable ).toVar();
  34090. const s1 = float( sub( 1.0, s ) ).toVar();
  34091. const t1 = float( sub( 1.0, t ) ).toVar();
  34092. const r1 = float( sub( 1.0, r ) ).toVar();
  34093. 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 ) ) ) ) ) );
  34094. } ).setLayout( {
  34095. name: 'mx_trilerp_1',
  34096. type: 'vec3',
  34097. inputs: [
  34098. { name: 'v0', type: 'vec3' },
  34099. { name: 'v1', type: 'vec3' },
  34100. { name: 'v2', type: 'vec3' },
  34101. { name: 'v3', type: 'vec3' },
  34102. { name: 'v4', type: 'vec3' },
  34103. { name: 'v5', type: 'vec3' },
  34104. { name: 'v6', type: 'vec3' },
  34105. { name: 'v7', type: 'vec3' },
  34106. { name: 's', type: 'float' },
  34107. { name: 't', type: 'float' },
  34108. { name: 'r', type: 'float' }
  34109. ]
  34110. } );
  34111. const mx_trilerp = /*#__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  34112. const mx_gradient_float_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  34113. const y = float( y_immutable ).toVar();
  34114. const x = float( x_immutable ).toVar();
  34115. const hash = uint( hash_immutable ).toVar();
  34116. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  34117. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  34118. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  34119. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  34120. } ).setLayout( {
  34121. name: 'mx_gradient_float_0',
  34122. type: 'float',
  34123. inputs: [
  34124. { name: 'hash', type: 'uint' },
  34125. { name: 'x', type: 'float' },
  34126. { name: 'y', type: 'float' }
  34127. ]
  34128. } );
  34129. const mx_gradient_float_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  34130. const z = float( z_immutable ).toVar();
  34131. const y = float( y_immutable ).toVar();
  34132. const x = float( x_immutable ).toVar();
  34133. const hash = uint( hash_immutable ).toVar();
  34134. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  34135. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  34136. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  34137. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  34138. } ).setLayout( {
  34139. name: 'mx_gradient_float_1',
  34140. type: 'float',
  34141. inputs: [
  34142. { name: 'hash', type: 'uint' },
  34143. { name: 'x', type: 'float' },
  34144. { name: 'y', type: 'float' },
  34145. { name: 'z', type: 'float' }
  34146. ]
  34147. } );
  34148. const mx_gradient_float = /*#__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  34149. const mx_gradient_vec3_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  34150. const y = float( y_immutable ).toVar();
  34151. const x = float( x_immutable ).toVar();
  34152. const hash = uvec3( hash_immutable ).toVar();
  34153. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  34154. } ).setLayout( {
  34155. name: 'mx_gradient_vec3_0',
  34156. type: 'vec3',
  34157. inputs: [
  34158. { name: 'hash', type: 'uvec3' },
  34159. { name: 'x', type: 'float' },
  34160. { name: 'y', type: 'float' }
  34161. ]
  34162. } );
  34163. const mx_gradient_vec3_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  34164. const z = float( z_immutable ).toVar();
  34165. const y = float( y_immutable ).toVar();
  34166. const x = float( x_immutable ).toVar();
  34167. const hash = uvec3( hash_immutable ).toVar();
  34168. 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 ) );
  34169. } ).setLayout( {
  34170. name: 'mx_gradient_vec3_1',
  34171. type: 'vec3',
  34172. inputs: [
  34173. { name: 'hash', type: 'uvec3' },
  34174. { name: 'x', type: 'float' },
  34175. { name: 'y', type: 'float' },
  34176. { name: 'z', type: 'float' }
  34177. ]
  34178. } );
  34179. const mx_gradient_vec3 = /*#__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  34180. const mx_gradient_scale2d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  34181. const v = float( v_immutable ).toVar();
  34182. return mul( 0.6616, v );
  34183. } ).setLayout( {
  34184. name: 'mx_gradient_scale2d_0',
  34185. type: 'float',
  34186. inputs: [
  34187. { name: 'v', type: 'float' }
  34188. ]
  34189. } );
  34190. const mx_gradient_scale3d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  34191. const v = float( v_immutable ).toVar();
  34192. return mul( 0.9820, v );
  34193. } ).setLayout( {
  34194. name: 'mx_gradient_scale3d_0',
  34195. type: 'float',
  34196. inputs: [
  34197. { name: 'v', type: 'float' }
  34198. ]
  34199. } );
  34200. const mx_gradient_scale2d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  34201. const v = vec3( v_immutable ).toVar();
  34202. return mul( 0.6616, v );
  34203. } ).setLayout( {
  34204. name: 'mx_gradient_scale2d_1',
  34205. type: 'vec3',
  34206. inputs: [
  34207. { name: 'v', type: 'vec3' }
  34208. ]
  34209. } );
  34210. const mx_gradient_scale2d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  34211. const mx_gradient_scale3d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  34212. const v = vec3( v_immutable ).toVar();
  34213. return mul( 0.9820, v );
  34214. } ).setLayout( {
  34215. name: 'mx_gradient_scale3d_1',
  34216. type: 'vec3',
  34217. inputs: [
  34218. { name: 'v', type: 'vec3' }
  34219. ]
  34220. } );
  34221. const mx_gradient_scale3d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  34222. const mx_rotl32 = /*#__PURE__*/ tslFn( ( [ x_immutable, k_immutable ] ) => {
  34223. const k = int( k_immutable ).toVar();
  34224. const x = uint( x_immutable ).toVar();
  34225. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  34226. } ).setLayout( {
  34227. name: 'mx_rotl32',
  34228. type: 'uint',
  34229. inputs: [
  34230. { name: 'x', type: 'uint' },
  34231. { name: 'k', type: 'int' }
  34232. ]
  34233. } );
  34234. const mx_bjmix = /*#__PURE__*/ tslFn( ( [ a, b, c ] ) => {
  34235. a.subAssign( c );
  34236. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  34237. c.addAssign( b );
  34238. b.subAssign( a );
  34239. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  34240. a.addAssign( c );
  34241. c.subAssign( b );
  34242. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  34243. b.addAssign( a );
  34244. a.subAssign( c );
  34245. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  34246. c.addAssign( b );
  34247. b.subAssign( a );
  34248. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  34249. a.addAssign( c );
  34250. c.subAssign( b );
  34251. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  34252. b.addAssign( a );
  34253. } );
  34254. const mx_bjfinal = /*#__PURE__*/ tslFn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  34255. const c = uint( c_immutable ).toVar();
  34256. const b = uint( b_immutable ).toVar();
  34257. const a = uint( a_immutable ).toVar();
  34258. c.bitXorAssign( b );
  34259. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  34260. a.bitXorAssign( c );
  34261. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  34262. b.bitXorAssign( a );
  34263. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  34264. c.bitXorAssign( b );
  34265. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  34266. a.bitXorAssign( c );
  34267. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  34268. b.bitXorAssign( a );
  34269. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  34270. c.bitXorAssign( b );
  34271. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  34272. return c;
  34273. } ).setLayout( {
  34274. name: 'mx_bjfinal',
  34275. type: 'uint',
  34276. inputs: [
  34277. { name: 'a', type: 'uint' },
  34278. { name: 'b', type: 'uint' },
  34279. { name: 'c', type: 'uint' }
  34280. ]
  34281. } );
  34282. const mx_bits_to_01 = /*#__PURE__*/ tslFn( ( [ bits_immutable ] ) => {
  34283. const bits = uint( bits_immutable ).toVar();
  34284. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  34285. } ).setLayout( {
  34286. name: 'mx_bits_to_01',
  34287. type: 'float',
  34288. inputs: [
  34289. { name: 'bits', type: 'uint' }
  34290. ]
  34291. } );
  34292. const mx_fade = /*#__PURE__*/ tslFn( ( [ t_immutable ] ) => {
  34293. const t = float( t_immutable ).toVar();
  34294. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  34295. } ).setLayout( {
  34296. name: 'mx_fade',
  34297. type: 'float',
  34298. inputs: [
  34299. { name: 't', type: 'float' }
  34300. ]
  34301. } );
  34302. const mx_hash_int_0 = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  34303. const x = int( x_immutable ).toVar();
  34304. const len = uint( uint( 1 ) ).toVar();
  34305. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  34306. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  34307. } ).setLayout( {
  34308. name: 'mx_hash_int_0',
  34309. type: 'uint',
  34310. inputs: [
  34311. { name: 'x', type: 'int' }
  34312. ]
  34313. } );
  34314. const mx_hash_int_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  34315. const y = int( y_immutable ).toVar();
  34316. const x = int( x_immutable ).toVar();
  34317. const len = uint( uint( 2 ) ).toVar();
  34318. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34319. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34320. a.addAssign( uint( x ) );
  34321. b.addAssign( uint( y ) );
  34322. return mx_bjfinal( a, b, c );
  34323. } ).setLayout( {
  34324. name: 'mx_hash_int_1',
  34325. type: 'uint',
  34326. inputs: [
  34327. { name: 'x', type: 'int' },
  34328. { name: 'y', type: 'int' }
  34329. ]
  34330. } );
  34331. const mx_hash_int_2 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34332. const z = int( z_immutable ).toVar();
  34333. const y = int( y_immutable ).toVar();
  34334. const x = int( x_immutable ).toVar();
  34335. const len = uint( uint( 3 ) ).toVar();
  34336. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34337. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34338. a.addAssign( uint( x ) );
  34339. b.addAssign( uint( y ) );
  34340. c.addAssign( uint( z ) );
  34341. return mx_bjfinal( a, b, c );
  34342. } ).setLayout( {
  34343. name: 'mx_hash_int_2',
  34344. type: 'uint',
  34345. inputs: [
  34346. { name: 'x', type: 'int' },
  34347. { name: 'y', type: 'int' },
  34348. { name: 'z', type: 'int' }
  34349. ]
  34350. } );
  34351. const mx_hash_int_3 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  34352. const xx = int( xx_immutable ).toVar();
  34353. const z = int( z_immutable ).toVar();
  34354. const y = int( y_immutable ).toVar();
  34355. const x = int( x_immutable ).toVar();
  34356. const len = uint( uint( 4 ) ).toVar();
  34357. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34358. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34359. a.addAssign( uint( x ) );
  34360. b.addAssign( uint( y ) );
  34361. c.addAssign( uint( z ) );
  34362. mx_bjmix( a, b, c );
  34363. a.addAssign( uint( xx ) );
  34364. return mx_bjfinal( a, b, c );
  34365. } ).setLayout( {
  34366. name: 'mx_hash_int_3',
  34367. type: 'uint',
  34368. inputs: [
  34369. { name: 'x', type: 'int' },
  34370. { name: 'y', type: 'int' },
  34371. { name: 'z', type: 'int' },
  34372. { name: 'xx', type: 'int' }
  34373. ]
  34374. } );
  34375. const mx_hash_int_4 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  34376. const yy = int( yy_immutable ).toVar();
  34377. const xx = int( xx_immutable ).toVar();
  34378. const z = int( z_immutable ).toVar();
  34379. const y = int( y_immutable ).toVar();
  34380. const x = int( x_immutable ).toVar();
  34381. const len = uint( uint( 5 ) ).toVar();
  34382. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34383. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34384. a.addAssign( uint( x ) );
  34385. b.addAssign( uint( y ) );
  34386. c.addAssign( uint( z ) );
  34387. mx_bjmix( a, b, c );
  34388. a.addAssign( uint( xx ) );
  34389. b.addAssign( uint( yy ) );
  34390. return mx_bjfinal( a, b, c );
  34391. } ).setLayout( {
  34392. name: 'mx_hash_int_4',
  34393. type: 'uint',
  34394. inputs: [
  34395. { name: 'x', type: 'int' },
  34396. { name: 'y', type: 'int' },
  34397. { name: 'z', type: 'int' },
  34398. { name: 'xx', type: 'int' },
  34399. { name: 'yy', type: 'int' }
  34400. ]
  34401. } );
  34402. 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 ] );
  34403. const mx_hash_vec3_0 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  34404. const y = int( y_immutable ).toVar();
  34405. const x = int( x_immutable ).toVar();
  34406. const h = uint( mx_hash_int( x, y ) ).toVar();
  34407. const result = uvec3().toVar();
  34408. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34409. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34410. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34411. return result;
  34412. } ).setLayout( {
  34413. name: 'mx_hash_vec3_0',
  34414. type: 'uvec3',
  34415. inputs: [
  34416. { name: 'x', type: 'int' },
  34417. { name: 'y', type: 'int' }
  34418. ]
  34419. } );
  34420. const mx_hash_vec3_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34421. const z = int( z_immutable ).toVar();
  34422. const y = int( y_immutable ).toVar();
  34423. const x = int( x_immutable ).toVar();
  34424. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  34425. const result = uvec3().toVar();
  34426. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34427. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34428. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34429. return result;
  34430. } ).setLayout( {
  34431. name: 'mx_hash_vec3_1',
  34432. type: 'uvec3',
  34433. inputs: [
  34434. { name: 'x', type: 'int' },
  34435. { name: 'y', type: 'int' },
  34436. { name: 'z', type: 'int' }
  34437. ]
  34438. } );
  34439. const mx_hash_vec3 = /*#__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  34440. const mx_perlin_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34441. const p = vec2( p_immutable ).toVar();
  34442. const X = int().toVar(), Y = int().toVar();
  34443. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34444. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34445. const u = float( mx_fade( fx ) ).toVar();
  34446. const v = float( mx_fade( fy ) ).toVar();
  34447. 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();
  34448. return mx_gradient_scale2d( result );
  34449. } ).setLayout( {
  34450. name: 'mx_perlin_noise_float_0',
  34451. type: 'float',
  34452. inputs: [
  34453. { name: 'p', type: 'vec2' }
  34454. ]
  34455. } );
  34456. const mx_perlin_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34457. const p = vec3( p_immutable ).toVar();
  34458. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34459. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34460. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34461. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34462. const u = float( mx_fade( fx ) ).toVar();
  34463. const v = float( mx_fade( fy ) ).toVar();
  34464. const w = float( mx_fade( fz ) ).toVar();
  34465. 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();
  34466. return mx_gradient_scale3d( result );
  34467. } ).setLayout( {
  34468. name: 'mx_perlin_noise_float_1',
  34469. type: 'float',
  34470. inputs: [
  34471. { name: 'p', type: 'vec3' }
  34472. ]
  34473. } );
  34474. const mx_perlin_noise_float = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  34475. const mx_perlin_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34476. const p = vec2( p_immutable ).toVar();
  34477. const X = int().toVar(), Y = int().toVar();
  34478. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34479. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34480. const u = float( mx_fade( fx ) ).toVar();
  34481. const v = float( mx_fade( fy ) ).toVar();
  34482. 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();
  34483. return mx_gradient_scale2d( result );
  34484. } ).setLayout( {
  34485. name: 'mx_perlin_noise_vec3_0',
  34486. type: 'vec3',
  34487. inputs: [
  34488. { name: 'p', type: 'vec2' }
  34489. ]
  34490. } );
  34491. const mx_perlin_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34492. const p = vec3( p_immutable ).toVar();
  34493. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34494. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34495. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34496. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34497. const u = float( mx_fade( fx ) ).toVar();
  34498. const v = float( mx_fade( fy ) ).toVar();
  34499. const w = float( mx_fade( fz ) ).toVar();
  34500. 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();
  34501. return mx_gradient_scale3d( result );
  34502. } ).setLayout( {
  34503. name: 'mx_perlin_noise_vec3_1',
  34504. type: 'vec3',
  34505. inputs: [
  34506. { name: 'p', type: 'vec3' }
  34507. ]
  34508. } );
  34509. const mx_perlin_noise_vec3 = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  34510. const mx_cell_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34511. const p = float( p_immutable ).toVar();
  34512. const ix = int( mx_floor( p ) ).toVar();
  34513. return mx_bits_to_01( mx_hash_int( ix ) );
  34514. } ).setLayout( {
  34515. name: 'mx_cell_noise_float_0',
  34516. type: 'float',
  34517. inputs: [
  34518. { name: 'p', type: 'float' }
  34519. ]
  34520. } );
  34521. const mx_cell_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34522. const p = vec2( p_immutable ).toVar();
  34523. const ix = int( mx_floor( p.x ) ).toVar();
  34524. const iy = int( mx_floor( p.y ) ).toVar();
  34525. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  34526. } ).setLayout( {
  34527. name: 'mx_cell_noise_float_1',
  34528. type: 'float',
  34529. inputs: [
  34530. { name: 'p', type: 'vec2' }
  34531. ]
  34532. } );
  34533. const mx_cell_noise_float_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34534. const p = vec3( p_immutable ).toVar();
  34535. const ix = int( mx_floor( p.x ) ).toVar();
  34536. const iy = int( mx_floor( p.y ) ).toVar();
  34537. const iz = int( mx_floor( p.z ) ).toVar();
  34538. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  34539. } ).setLayout( {
  34540. name: 'mx_cell_noise_float_2',
  34541. type: 'float',
  34542. inputs: [
  34543. { name: 'p', type: 'vec3' }
  34544. ]
  34545. } );
  34546. const mx_cell_noise_float_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34547. const p = vec4( p_immutable ).toVar();
  34548. const ix = int( mx_floor( p.x ) ).toVar();
  34549. const iy = int( mx_floor( p.y ) ).toVar();
  34550. const iz = int( mx_floor( p.z ) ).toVar();
  34551. const iw = int( mx_floor( p.w ) ).toVar();
  34552. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  34553. } ).setLayout( {
  34554. name: 'mx_cell_noise_float_3',
  34555. type: 'float',
  34556. inputs: [
  34557. { name: 'p', type: 'vec4' }
  34558. ]
  34559. } );
  34560. 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 ] );
  34561. const mx_cell_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34562. const p = float( p_immutable ).toVar();
  34563. const ix = int( mx_floor( p ) ).toVar();
  34564. 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 ) ) ) );
  34565. } ).setLayout( {
  34566. name: 'mx_cell_noise_vec3_0',
  34567. type: 'vec3',
  34568. inputs: [
  34569. { name: 'p', type: 'float' }
  34570. ]
  34571. } );
  34572. const mx_cell_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34573. const p = vec2( p_immutable ).toVar();
  34574. const ix = int( mx_floor( p.x ) ).toVar();
  34575. const iy = int( mx_floor( p.y ) ).toVar();
  34576. 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 ) ) ) );
  34577. } ).setLayout( {
  34578. name: 'mx_cell_noise_vec3_1',
  34579. type: 'vec3',
  34580. inputs: [
  34581. { name: 'p', type: 'vec2' }
  34582. ]
  34583. } );
  34584. const mx_cell_noise_vec3_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34585. const p = vec3( p_immutable ).toVar();
  34586. const ix = int( mx_floor( p.x ) ).toVar();
  34587. const iy = int( mx_floor( p.y ) ).toVar();
  34588. const iz = int( mx_floor( p.z ) ).toVar();
  34589. 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 ) ) ) );
  34590. } ).setLayout( {
  34591. name: 'mx_cell_noise_vec3_2',
  34592. type: 'vec3',
  34593. inputs: [
  34594. { name: 'p', type: 'vec3' }
  34595. ]
  34596. } );
  34597. const mx_cell_noise_vec3_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  34598. const p = vec4( p_immutable ).toVar();
  34599. const ix = int( mx_floor( p.x ) ).toVar();
  34600. const iy = int( mx_floor( p.y ) ).toVar();
  34601. const iz = int( mx_floor( p.z ) ).toVar();
  34602. const iw = int( mx_floor( p.w ) ).toVar();
  34603. 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 ) ) ) );
  34604. } ).setLayout( {
  34605. name: 'mx_cell_noise_vec3_3',
  34606. type: 'vec3',
  34607. inputs: [
  34608. { name: 'p', type: 'vec4' }
  34609. ]
  34610. } );
  34611. 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 ] );
  34612. const mx_fractal_noise_float$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34613. const diminish = float( diminish_immutable ).toVar();
  34614. const lacunarity = float( lacunarity_immutable ).toVar();
  34615. const octaves = int( octaves_immutable ).toVar();
  34616. const p = vec3( p_immutable ).toVar();
  34617. const result = float( 0.0 ).toVar();
  34618. const amplitude = float( 1.0 ).toVar();
  34619. loop( octaves, () => {
  34620. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  34621. amplitude.mulAssign( diminish );
  34622. p.mulAssign( lacunarity );
  34623. } );
  34624. return result;
  34625. } ).setLayout( {
  34626. name: 'mx_fractal_noise_float',
  34627. type: 'float',
  34628. inputs: [
  34629. { name: 'p', type: 'vec3' },
  34630. { name: 'octaves', type: 'int' },
  34631. { name: 'lacunarity', type: 'float' },
  34632. { name: 'diminish', type: 'float' }
  34633. ]
  34634. } );
  34635. const mx_fractal_noise_vec3$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34636. const diminish = float( diminish_immutable ).toVar();
  34637. const lacunarity = float( lacunarity_immutable ).toVar();
  34638. const octaves = int( octaves_immutable ).toVar();
  34639. const p = vec3( p_immutable ).toVar();
  34640. const result = vec3( 0.0 ).toVar();
  34641. const amplitude = float( 1.0 ).toVar();
  34642. loop( octaves, () => {
  34643. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  34644. amplitude.mulAssign( diminish );
  34645. p.mulAssign( lacunarity );
  34646. } );
  34647. return result;
  34648. } ).setLayout( {
  34649. name: 'mx_fractal_noise_vec3',
  34650. type: 'vec3',
  34651. inputs: [
  34652. { name: 'p', type: 'vec3' },
  34653. { name: 'octaves', type: 'int' },
  34654. { name: 'lacunarity', type: 'float' },
  34655. { name: 'diminish', type: 'float' }
  34656. ]
  34657. } );
  34658. const mx_fractal_noise_vec2$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34659. const diminish = float( diminish_immutable ).toVar();
  34660. const lacunarity = float( lacunarity_immutable ).toVar();
  34661. const octaves = int( octaves_immutable ).toVar();
  34662. const p = vec3( p_immutable ).toVar();
  34663. 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 ) );
  34664. } ).setLayout( {
  34665. name: 'mx_fractal_noise_vec2',
  34666. type: 'vec2',
  34667. inputs: [
  34668. { name: 'p', type: 'vec3' },
  34669. { name: 'octaves', type: 'int' },
  34670. { name: 'lacunarity', type: 'float' },
  34671. { name: 'diminish', type: 'float' }
  34672. ]
  34673. } );
  34674. const mx_fractal_noise_vec4$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34675. const diminish = float( diminish_immutable ).toVar();
  34676. const lacunarity = float( lacunarity_immutable ).toVar();
  34677. const octaves = int( octaves_immutable ).toVar();
  34678. const p = vec3( p_immutable ).toVar();
  34679. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  34680. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  34681. return vec4( c, f );
  34682. } ).setLayout( {
  34683. name: 'mx_fractal_noise_vec4',
  34684. type: 'vec4',
  34685. inputs: [
  34686. { name: 'p', type: 'vec3' },
  34687. { name: 'octaves', type: 'int' },
  34688. { name: 'lacunarity', type: 'float' },
  34689. { name: 'diminish', type: 'float' }
  34690. ]
  34691. } );
  34692. const mx_worley_distance_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34693. const metric = int( metric_immutable ).toVar();
  34694. const jitter = float( jitter_immutable ).toVar();
  34695. const yoff = int( yoff_immutable ).toVar();
  34696. const xoff = int( xoff_immutable ).toVar();
  34697. const y = int( y_immutable ).toVar();
  34698. const x = int( x_immutable ).toVar();
  34699. const p = vec2( p_immutable ).toVar();
  34700. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  34701. const off = vec2( tmp.x, tmp.y ).toVar();
  34702. off.subAssign( 0.5 );
  34703. off.mulAssign( jitter );
  34704. off.addAssign( 0.5 );
  34705. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  34706. const diff = vec2( cellpos.sub( p ) ).toVar();
  34707. If( metric.equal( int( 2 ) ), () => {
  34708. return abs( diff.x ).add( abs( diff.y ) );
  34709. } );
  34710. If( metric.equal( int( 3 ) ), () => {
  34711. return max$1( abs( diff.x ), abs( diff.y ) );
  34712. } );
  34713. return dot( diff, diff );
  34714. } ).setLayout( {
  34715. name: 'mx_worley_distance_0',
  34716. type: 'float',
  34717. inputs: [
  34718. { name: 'p', type: 'vec2' },
  34719. { name: 'x', type: 'int' },
  34720. { name: 'y', type: 'int' },
  34721. { name: 'xoff', type: 'int' },
  34722. { name: 'yoff', type: 'int' },
  34723. { name: 'jitter', type: 'float' },
  34724. { name: 'metric', type: 'int' }
  34725. ]
  34726. } );
  34727. 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 ] ) => {
  34728. const metric = int( metric_immutable ).toVar();
  34729. const jitter = float( jitter_immutable ).toVar();
  34730. const zoff = int( zoff_immutable ).toVar();
  34731. const yoff = int( yoff_immutable ).toVar();
  34732. const xoff = int( xoff_immutable ).toVar();
  34733. const z = int( z_immutable ).toVar();
  34734. const y = int( y_immutable ).toVar();
  34735. const x = int( x_immutable ).toVar();
  34736. const p = vec3( p_immutable ).toVar();
  34737. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  34738. off.subAssign( 0.5 );
  34739. off.mulAssign( jitter );
  34740. off.addAssign( 0.5 );
  34741. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  34742. const diff = vec3( cellpos.sub( p ) ).toVar();
  34743. If( metric.equal( int( 2 ) ), () => {
  34744. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  34745. } );
  34746. If( metric.equal( int( 3 ) ), () => {
  34747. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  34748. } );
  34749. return dot( diff, diff );
  34750. } ).setLayout( {
  34751. name: 'mx_worley_distance_1',
  34752. type: 'float',
  34753. inputs: [
  34754. { name: 'p', type: 'vec3' },
  34755. { name: 'x', type: 'int' },
  34756. { name: 'y', type: 'int' },
  34757. { name: 'z', type: 'int' },
  34758. { name: 'xoff', type: 'int' },
  34759. { name: 'yoff', type: 'int' },
  34760. { name: 'zoff', type: 'int' },
  34761. { name: 'jitter', type: 'float' },
  34762. { name: 'metric', type: 'int' }
  34763. ]
  34764. } );
  34765. const mx_worley_distance = /*#__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  34766. const mx_worley_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34767. const metric = int( metric_immutable ).toVar();
  34768. const jitter = float( jitter_immutable ).toVar();
  34769. const p = vec2( p_immutable ).toVar();
  34770. const X = int().toVar(), Y = int().toVar();
  34771. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34772. const sqdist = float( 1e6 ).toVar();
  34773. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34774. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34775. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34776. sqdist.assign( min$1( sqdist, dist ) );
  34777. } );
  34778. } );
  34779. If( metric.equal( int( 0 ) ), () => {
  34780. sqdist.assign( sqrt( sqdist ) );
  34781. } );
  34782. return sqdist;
  34783. } ).setLayout( {
  34784. name: 'mx_worley_noise_float_0',
  34785. type: 'float',
  34786. inputs: [
  34787. { name: 'p', type: 'vec2' },
  34788. { name: 'jitter', type: 'float' },
  34789. { name: 'metric', type: 'int' }
  34790. ]
  34791. } );
  34792. const mx_worley_noise_vec2_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34793. const metric = int( metric_immutable ).toVar();
  34794. const jitter = float( jitter_immutable ).toVar();
  34795. const p = vec2( p_immutable ).toVar();
  34796. const X = int().toVar(), Y = int().toVar();
  34797. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34798. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34799. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34800. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34801. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34802. If( dist.lessThan( sqdist.x ), () => {
  34803. sqdist.y.assign( sqdist.x );
  34804. sqdist.x.assign( dist );
  34805. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34806. sqdist.y.assign( dist );
  34807. } );
  34808. } );
  34809. } );
  34810. If( metric.equal( int( 0 ) ), () => {
  34811. sqdist.assign( sqrt( sqdist ) );
  34812. } );
  34813. return sqdist;
  34814. } ).setLayout( {
  34815. name: 'mx_worley_noise_vec2_0',
  34816. type: 'vec2',
  34817. inputs: [
  34818. { name: 'p', type: 'vec2' },
  34819. { name: 'jitter', type: 'float' },
  34820. { name: 'metric', type: 'int' }
  34821. ]
  34822. } );
  34823. const mx_worley_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34824. const metric = int( metric_immutable ).toVar();
  34825. const jitter = float( jitter_immutable ).toVar();
  34826. const p = vec2( p_immutable ).toVar();
  34827. const X = int().toVar(), Y = int().toVar();
  34828. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34829. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34830. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34831. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34832. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34833. If( dist.lessThan( sqdist.x ), () => {
  34834. sqdist.z.assign( sqdist.y );
  34835. sqdist.y.assign( sqdist.x );
  34836. sqdist.x.assign( dist );
  34837. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34838. sqdist.z.assign( sqdist.y );
  34839. sqdist.y.assign( dist );
  34840. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34841. sqdist.z.assign( dist );
  34842. } );
  34843. } );
  34844. } );
  34845. If( metric.equal( int( 0 ) ), () => {
  34846. sqdist.assign( sqrt( sqdist ) );
  34847. } );
  34848. return sqdist;
  34849. } ).setLayout( {
  34850. name: 'mx_worley_noise_vec3_0',
  34851. type: 'vec3',
  34852. inputs: [
  34853. { name: 'p', type: 'vec2' },
  34854. { name: 'jitter', type: 'float' },
  34855. { name: 'metric', type: 'int' }
  34856. ]
  34857. } );
  34858. const mx_worley_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34859. const metric = int( metric_immutable ).toVar();
  34860. const jitter = float( jitter_immutable ).toVar();
  34861. const p = vec3( p_immutable ).toVar();
  34862. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34863. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34864. const sqdist = float( 1e6 ).toVar();
  34865. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34866. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34867. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34868. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34869. sqdist.assign( min$1( sqdist, dist ) );
  34870. } );
  34871. } );
  34872. } );
  34873. If( metric.equal( int( 0 ) ), () => {
  34874. sqdist.assign( sqrt( sqdist ) );
  34875. } );
  34876. return sqdist;
  34877. } ).setLayout( {
  34878. name: 'mx_worley_noise_float_1',
  34879. type: 'float',
  34880. inputs: [
  34881. { name: 'p', type: 'vec3' },
  34882. { name: 'jitter', type: 'float' },
  34883. { name: 'metric', type: 'int' }
  34884. ]
  34885. } );
  34886. const mx_worley_noise_float$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  34887. const mx_worley_noise_vec2_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34888. const metric = int( metric_immutable ).toVar();
  34889. const jitter = float( jitter_immutable ).toVar();
  34890. const p = vec3( p_immutable ).toVar();
  34891. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34892. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34893. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34894. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34895. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34896. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34897. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34898. If( dist.lessThan( sqdist.x ), () => {
  34899. sqdist.y.assign( sqdist.x );
  34900. sqdist.x.assign( dist );
  34901. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34902. sqdist.y.assign( dist );
  34903. } );
  34904. } );
  34905. } );
  34906. } );
  34907. If( metric.equal( int( 0 ) ), () => {
  34908. sqdist.assign( sqrt( sqdist ) );
  34909. } );
  34910. return sqdist;
  34911. } ).setLayout( {
  34912. name: 'mx_worley_noise_vec2_1',
  34913. type: 'vec2',
  34914. inputs: [
  34915. { name: 'p', type: 'vec3' },
  34916. { name: 'jitter', type: 'float' },
  34917. { name: 'metric', type: 'int' }
  34918. ]
  34919. } );
  34920. const mx_worley_noise_vec2$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  34921. const mx_worley_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34922. const metric = int( metric_immutable ).toVar();
  34923. const jitter = float( jitter_immutable ).toVar();
  34924. const p = vec3( p_immutable ).toVar();
  34925. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34926. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34927. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34928. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34929. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34930. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34931. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34932. If( dist.lessThan( sqdist.x ), () => {
  34933. sqdist.z.assign( sqdist.y );
  34934. sqdist.y.assign( sqdist.x );
  34935. sqdist.x.assign( dist );
  34936. } ).elseif( dist.lessThan( sqdist.y ), () => {
  34937. sqdist.z.assign( sqdist.y );
  34938. sqdist.y.assign( dist );
  34939. } ).elseif( dist.lessThan( sqdist.z ), () => {
  34940. sqdist.z.assign( dist );
  34941. } );
  34942. } );
  34943. } );
  34944. } );
  34945. If( metric.equal( int( 0 ) ), () => {
  34946. sqdist.assign( sqrt( sqdist ) );
  34947. } );
  34948. return sqdist;
  34949. } ).setLayout( {
  34950. name: 'mx_worley_noise_vec3_1',
  34951. type: 'vec3',
  34952. inputs: [
  34953. { name: 'p', type: 'vec3' },
  34954. { name: 'jitter', type: 'float' },
  34955. { name: 'metric', type: 'int' }
  34956. ]
  34957. } );
  34958. const mx_worley_noise_vec3$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34959. // Three.js Transpiler
  34960. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34961. const mx_hsvtorgb = /*#__PURE__*/ tslFn( ( [ hsv_immutable ] ) => {
  34962. const hsv = vec3( hsv_immutable ).toVar();
  34963. const h = float( hsv.x ).toVar();
  34964. const s = float( hsv.y ).toVar();
  34965. const v = float( hsv.z ).toVar();
  34966. If( s.lessThan( 0.0001 ), () => {
  34967. return vec3( v, v, v );
  34968. } ).else( () => {
  34969. h.assign( mul( 6.0, h.sub( floor( h ) ) ) );
  34970. const hi = int( trunc( h ) ).toVar();
  34971. const f = float( h.sub( float( hi ) ) ).toVar();
  34972. const p = float( v.mul( sub( 1.0, s ) ) ).toVar();
  34973. const q = float( v.mul( sub( 1.0, s.mul( f ) ) ) ).toVar();
  34974. const t = float( v.mul( sub( 1.0, s.mul( sub( 1.0, f ) ) ) ) ).toVar();
  34975. If( hi.equal( int( 0 ) ), () => {
  34976. return vec3( v, t, p );
  34977. } ).elseif( hi.equal( int( 1 ) ), () => {
  34978. return vec3( q, v, p );
  34979. } ).elseif( hi.equal( int( 2 ) ), () => {
  34980. return vec3( p, v, t );
  34981. } ).elseif( hi.equal( int( 3 ) ), () => {
  34982. return vec3( p, q, v );
  34983. } ).elseif( hi.equal( int( 4 ) ), () => {
  34984. return vec3( t, p, v );
  34985. } );
  34986. return vec3( v, p, q );
  34987. } );
  34988. } ).setLayout( {
  34989. name: 'mx_hsvtorgb',
  34990. type: 'vec3',
  34991. inputs: [
  34992. { name: 'hsv', type: 'vec3' }
  34993. ]
  34994. } );
  34995. const mx_rgbtohsv = /*#__PURE__*/ tslFn( ( [ c_immutable ] ) => {
  34996. const c = vec3( c_immutable ).toVar();
  34997. const r = float( c.x ).toVar();
  34998. const g = float( c.y ).toVar();
  34999. const b = float( c.z ).toVar();
  35000. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  35001. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  35002. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  35003. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  35004. v.assign( maxcomp );
  35005. If( maxcomp.greaterThan( 0.0 ), () => {
  35006. s.assign( delta.div( maxcomp ) );
  35007. } ).else( () => {
  35008. s.assign( 0.0 );
  35009. } );
  35010. If( s.lessThanEqual( 0.0 ), () => {
  35011. h.assign( 0.0 );
  35012. } ).else( () => {
  35013. If( r.greaterThanEqual( maxcomp ), () => {
  35014. h.assign( g.sub( b ).div( delta ) );
  35015. } ).elseif( g.greaterThanEqual( maxcomp ), () => {
  35016. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  35017. } ).else( () => {
  35018. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  35019. } );
  35020. h.mulAssign( 1.0 / 6.0 );
  35021. If( h.lessThan( 0.0 ), () => {
  35022. h.addAssign( 1.0 );
  35023. } );
  35024. } );
  35025. return vec3( h, s, v );
  35026. } ).setLayout( {
  35027. name: 'mx_rgbtohsv',
  35028. type: 'vec3',
  35029. inputs: [
  35030. { name: 'c', type: 'vec3' }
  35031. ]
  35032. } );
  35033. // Three.js Transpiler
  35034. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  35035. const mx_srgb_texture_to_lin_rec709 = /*#__PURE__*/ tslFn( ( [ color_immutable ] ) => {
  35036. const color = vec3( color_immutable ).toVar();
  35037. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  35038. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  35039. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  35040. return mix( linSeg, powSeg, isAbove );
  35041. } ).setLayout( {
  35042. name: 'mx_srgb_texture_to_lin_rec709',
  35043. type: 'vec3',
  35044. inputs: [
  35045. { name: 'color', type: 'vec3' }
  35046. ]
  35047. } );
  35048. const mx_aastep = ( threshold, value ) => {
  35049. threshold = float( threshold );
  35050. value = float( value );
  35051. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  35052. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  35053. };
  35054. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  35055. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  35056. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  35057. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  35058. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  35059. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  35060. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  35061. const mx_safepower = ( in1, in2 = 1 ) => {
  35062. in1 = float( in1 );
  35063. return in1.abs().pow( in2 ).mul( in1.sign() );
  35064. };
  35065. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  35066. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35067. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35068. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35069. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  35070. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  35071. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  35072. return noise_vec4.mul( amplitude ).add( pivot );
  35073. };
  35074. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35075. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35076. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35077. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  35078. 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 );
  35079. 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 );
  35080. 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 );
  35081. 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 );
  35082. function painterSortStable( a, b ) {
  35083. if ( a.groupOrder !== b.groupOrder ) {
  35084. return a.groupOrder - b.groupOrder;
  35085. } else if ( a.renderOrder !== b.renderOrder ) {
  35086. return a.renderOrder - b.renderOrder;
  35087. } else if ( a.material.id !== b.material.id ) {
  35088. return a.material.id - b.material.id;
  35089. } else if ( a.z !== b.z ) {
  35090. return a.z - b.z;
  35091. } else {
  35092. return a.id - b.id;
  35093. }
  35094. }
  35095. function reversePainterSortStable( a, b ) {
  35096. if ( a.groupOrder !== b.groupOrder ) {
  35097. return a.groupOrder - b.groupOrder;
  35098. } else if ( a.renderOrder !== b.renderOrder ) {
  35099. return a.renderOrder - b.renderOrder;
  35100. } else if ( a.z !== b.z ) {
  35101. return b.z - a.z;
  35102. } else {
  35103. return a.id - b.id;
  35104. }
  35105. }
  35106. class RenderList {
  35107. constructor() {
  35108. this.renderItems = [];
  35109. this.renderItemsIndex = 0;
  35110. this.opaque = [];
  35111. this.transparent = [];
  35112. this.bundles = [];
  35113. this.lightsNode = new LightsNode( [] );
  35114. this.lightsArray = [];
  35115. this.occlusionQueryCount = 0;
  35116. }
  35117. begin() {
  35118. this.renderItemsIndex = 0;
  35119. this.opaque.length = 0;
  35120. this.transparent.length = 0;
  35121. this.bundles.length = 0;
  35122. this.lightsArray.length = 0;
  35123. this.occlusionQueryCount = 0;
  35124. return this;
  35125. }
  35126. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  35127. let renderItem = this.renderItems[ this.renderItemsIndex ];
  35128. if ( renderItem === undefined ) {
  35129. renderItem = {
  35130. id: object.id,
  35131. object: object,
  35132. geometry: geometry,
  35133. material: material,
  35134. groupOrder: groupOrder,
  35135. renderOrder: object.renderOrder,
  35136. z: z,
  35137. group: group
  35138. };
  35139. this.renderItems[ this.renderItemsIndex ] = renderItem;
  35140. } else {
  35141. renderItem.id = object.id;
  35142. renderItem.object = object;
  35143. renderItem.geometry = geometry;
  35144. renderItem.material = material;
  35145. renderItem.groupOrder = groupOrder;
  35146. renderItem.renderOrder = object.renderOrder;
  35147. renderItem.z = z;
  35148. renderItem.group = group;
  35149. }
  35150. this.renderItemsIndex ++;
  35151. return renderItem;
  35152. }
  35153. push( object, geometry, material, groupOrder, z, group ) {
  35154. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  35155. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  35156. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  35157. }
  35158. unshift( object, geometry, material, groupOrder, z, group ) {
  35159. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  35160. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  35161. }
  35162. pushBundle( group ) {
  35163. this.bundles.push( group );
  35164. }
  35165. pushLight( light ) {
  35166. this.lightsArray.push( light );
  35167. }
  35168. getLightsNode() {
  35169. return this.lightsNode.fromLights( this.lightsArray );
  35170. }
  35171. sort( customOpaqueSort, customTransparentSort ) {
  35172. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  35173. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  35174. }
  35175. finish() {
  35176. // update lights
  35177. this.lightsNode.fromLights( this.lightsArray );
  35178. // Clear references from inactive renderItems in the list
  35179. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  35180. const renderItem = this.renderItems[ i ];
  35181. if ( renderItem.id === null ) break;
  35182. renderItem.id = null;
  35183. renderItem.object = null;
  35184. renderItem.geometry = null;
  35185. renderItem.material = null;
  35186. renderItem.groupOrder = null;
  35187. renderItem.renderOrder = null;
  35188. renderItem.z = null;
  35189. renderItem.group = null;
  35190. }
  35191. }
  35192. }
  35193. class RenderLists {
  35194. constructor() {
  35195. this.lists = new ChainMap();
  35196. }
  35197. get( scene, camera ) {
  35198. const lists = this.lists;
  35199. const keys = [ scene, camera ];
  35200. let list = lists.get( keys );
  35201. if ( list === undefined ) {
  35202. list = new RenderList();
  35203. lists.set( keys, list );
  35204. }
  35205. return list;
  35206. }
  35207. dispose() {
  35208. this.lists = new ChainMap();
  35209. }
  35210. }
  35211. let id$2 = 0;
  35212. class RenderContext {
  35213. constructor() {
  35214. this.id = id$2 ++;
  35215. this.color = true;
  35216. this.clearColor = true;
  35217. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  35218. this.depth = true;
  35219. this.clearDepth = true;
  35220. this.clearDepthValue = 1;
  35221. this.stencil = false;
  35222. this.clearStencil = true;
  35223. this.clearStencilValue = 1;
  35224. this.viewport = false;
  35225. this.viewportValue = new Vector4();
  35226. this.scissor = false;
  35227. this.scissorValue = new Vector4();
  35228. this.textures = null;
  35229. this.depthTexture = null;
  35230. this.activeCubeFace = 0;
  35231. this.sampleCount = 1;
  35232. this.width = 0;
  35233. this.height = 0;
  35234. this.isRenderContext = true;
  35235. }
  35236. }
  35237. class RenderContexts {
  35238. constructor() {
  35239. this.chainMaps = {};
  35240. }
  35241. get( scene, camera, renderTarget = null ) {
  35242. const chainKey = [ scene, camera ];
  35243. let attachmentState;
  35244. if ( renderTarget === null ) {
  35245. attachmentState = 'default';
  35246. } else {
  35247. const format = renderTarget.texture.format;
  35248. const count = renderTarget.count;
  35249. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  35250. }
  35251. const chainMap = this.getChainMap( attachmentState );
  35252. let renderState = chainMap.get( chainKey );
  35253. if ( renderState === undefined ) {
  35254. renderState = new RenderContext();
  35255. chainMap.set( chainKey, renderState );
  35256. }
  35257. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  35258. return renderState;
  35259. }
  35260. getChainMap( attachmentState ) {
  35261. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  35262. }
  35263. dispose() {
  35264. this.chainMaps = {};
  35265. }
  35266. }
  35267. const _size = new Vector3();
  35268. class Textures extends DataMap {
  35269. constructor( renderer, backend, info ) {
  35270. super();
  35271. this.renderer = renderer;
  35272. this.backend = backend;
  35273. this.info = info;
  35274. }
  35275. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  35276. const renderTargetData = this.get( renderTarget );
  35277. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  35278. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  35279. const texture = renderTarget.texture;
  35280. const textures = renderTarget.textures;
  35281. const size = this.getSize( texture );
  35282. const mipWidth = size.width >> activeMipmapLevel;
  35283. const mipHeight = size.height >> activeMipmapLevel;
  35284. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  35285. let textureNeedsUpdate = false;
  35286. if ( depthTexture === undefined ) {
  35287. depthTexture = new DepthTexture();
  35288. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  35289. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  35290. depthTexture.image.width = mipWidth;
  35291. depthTexture.image.height = mipHeight;
  35292. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  35293. }
  35294. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  35295. textureNeedsUpdate = true;
  35296. depthTexture.needsUpdate = true;
  35297. depthTexture.image.width = mipWidth;
  35298. depthTexture.image.height = mipHeight;
  35299. }
  35300. renderTargetData.width = size.width;
  35301. renderTargetData.height = size.height;
  35302. renderTargetData.textures = textures;
  35303. renderTargetData.depthTexture = depthTexture;
  35304. renderTargetData.depth = renderTarget.depthBuffer;
  35305. renderTargetData.stencil = renderTarget.stencilBuffer;
  35306. renderTargetData.renderTarget = renderTarget;
  35307. if ( renderTargetData.sampleCount !== sampleCount ) {
  35308. textureNeedsUpdate = true;
  35309. depthTexture.needsUpdate = true;
  35310. renderTargetData.sampleCount = sampleCount;
  35311. }
  35312. //
  35313. const options = { sampleCount };
  35314. for ( let i = 0; i < textures.length; i ++ ) {
  35315. const texture = textures[ i ];
  35316. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  35317. this.updateTexture( texture, options );
  35318. }
  35319. this.updateTexture( depthTexture, options );
  35320. // dispose handler
  35321. if ( renderTargetData.initialized !== true ) {
  35322. renderTargetData.initialized = true;
  35323. // dispose
  35324. const onDispose = () => {
  35325. renderTarget.removeEventListener( 'dispose', onDispose );
  35326. if ( textures !== undefined ) {
  35327. for ( let i = 0; i < textures.length; i ++ ) {
  35328. this._destroyTexture( textures[ i ] );
  35329. }
  35330. } else {
  35331. this._destroyTexture( texture );
  35332. }
  35333. this._destroyTexture( depthTexture );
  35334. };
  35335. renderTarget.addEventListener( 'dispose', onDispose );
  35336. }
  35337. }
  35338. updateTexture( texture, options = {} ) {
  35339. const textureData = this.get( texture );
  35340. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  35341. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  35342. const backend = this.backend;
  35343. if ( isRenderTarget && textureData.initialized === true ) {
  35344. // it's an update
  35345. backend.destroySampler( texture );
  35346. backend.destroyTexture( texture );
  35347. }
  35348. //
  35349. if ( texture.isFramebufferTexture ) {
  35350. const renderer = this.renderer;
  35351. const renderTarget = renderer.getRenderTarget();
  35352. if ( renderTarget ) {
  35353. texture.type = renderTarget.texture.type;
  35354. } else {
  35355. texture.type = UnsignedByteType;
  35356. }
  35357. }
  35358. //
  35359. const { width, height, depth } = this.getSize( texture );
  35360. options.width = width;
  35361. options.height = height;
  35362. options.depth = depth;
  35363. options.needsMipmaps = this.needsMipmaps( texture );
  35364. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  35365. //
  35366. if ( isRenderTarget || texture.isStorageTexture === true ) {
  35367. backend.createSampler( texture );
  35368. backend.createTexture( texture, options );
  35369. } else {
  35370. const needsCreate = textureData.initialized !== true;
  35371. if ( needsCreate ) backend.createSampler( texture );
  35372. if ( texture.version > 0 ) {
  35373. const image = texture.image;
  35374. if ( image === undefined ) {
  35375. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  35376. } else if ( image.complete === false ) {
  35377. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  35378. } else {
  35379. if ( texture.images ) {
  35380. const images = [];
  35381. for ( const image of texture.images ) {
  35382. images.push( image );
  35383. }
  35384. options.images = images;
  35385. } else {
  35386. options.image = image;
  35387. }
  35388. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  35389. backend.createTexture( texture, options );
  35390. textureData.isDefaultTexture = false;
  35391. }
  35392. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  35393. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  35394. }
  35395. } else {
  35396. // async update
  35397. backend.createDefaultTexture( texture );
  35398. textureData.isDefaultTexture = true;
  35399. }
  35400. }
  35401. // dispose handler
  35402. if ( textureData.initialized !== true ) {
  35403. textureData.initialized = true;
  35404. //
  35405. this.info.memory.textures ++;
  35406. // dispose
  35407. const onDispose = () => {
  35408. texture.removeEventListener( 'dispose', onDispose );
  35409. this._destroyTexture( texture );
  35410. this.info.memory.textures --;
  35411. };
  35412. texture.addEventListener( 'dispose', onDispose );
  35413. }
  35414. //
  35415. textureData.version = texture.version;
  35416. }
  35417. getSize( texture, target = _size ) {
  35418. let image = texture.images ? texture.images[ 0 ] : texture.image;
  35419. if ( image ) {
  35420. if ( image.image !== undefined ) image = image.image;
  35421. target.width = image.width;
  35422. target.height = image.height;
  35423. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  35424. } else {
  35425. target.width = target.height = target.depth = 1;
  35426. }
  35427. return target;
  35428. }
  35429. getMipLevels( texture, width, height ) {
  35430. let mipLevelCount;
  35431. if ( texture.isCompressedTexture ) {
  35432. mipLevelCount = texture.mipmaps.length;
  35433. } else {
  35434. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  35435. }
  35436. return mipLevelCount;
  35437. }
  35438. needsMipmaps( texture ) {
  35439. if ( this.isEnvironmentTexture( texture ) ) return true;
  35440. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  35441. }
  35442. isEnvironmentTexture( texture ) {
  35443. const mapping = texture.mapping;
  35444. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  35445. }
  35446. _destroyTexture( texture ) {
  35447. this.backend.destroySampler( texture );
  35448. this.backend.destroyTexture( texture );
  35449. this.delete( texture );
  35450. }
  35451. }
  35452. class Color4 extends Color {
  35453. constructor( r, g, b, a = 1 ) {
  35454. super( r, g, b );
  35455. this.a = a;
  35456. }
  35457. set( r, g, b, a = 1 ) {
  35458. this.a = a;
  35459. return super.set( r, g, b );
  35460. }
  35461. copy( color ) {
  35462. if ( color.a !== undefined ) this.a = color.a;
  35463. return super.copy( color );
  35464. }
  35465. clone() {
  35466. return new this.constructor( this.r, this.g, this.b, this.a );
  35467. }
  35468. }
  35469. const _clearColor = new Color4();
  35470. class Background extends DataMap {
  35471. constructor( renderer, nodes ) {
  35472. super();
  35473. this.renderer = renderer;
  35474. this.nodes = nodes;
  35475. }
  35476. update( scene, renderList, renderContext ) {
  35477. const renderer = this.renderer;
  35478. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  35479. let forceClear = false;
  35480. if ( background === null ) {
  35481. // no background settings, use clear color configuration from the renderer
  35482. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  35483. _clearColor.a = renderer._clearColor.a;
  35484. } else if ( background.isColor === true ) {
  35485. // background is an opaque color
  35486. background.getRGB( _clearColor, LinearSRGBColorSpace );
  35487. _clearColor.a = 1;
  35488. forceClear = true;
  35489. } else if ( background.isNode === true ) {
  35490. const sceneData = this.get( scene );
  35491. const backgroundNode = background;
  35492. _clearColor.copy( renderer._clearColor );
  35493. let backgroundMesh = sceneData.backgroundMesh;
  35494. if ( backgroundMesh === undefined ) {
  35495. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  35496. // @TODO: Add Texture2D support using node context
  35497. getUV: () => normalWorld,
  35498. getTextureLevel: () => backgroundBlurriness
  35499. } );
  35500. let viewProj = modelViewProjection();
  35501. viewProj = viewProj.setZ( viewProj.w );
  35502. const nodeMaterial = new NodeMaterial();
  35503. nodeMaterial.side = BackSide;
  35504. nodeMaterial.depthTest = false;
  35505. nodeMaterial.depthWrite = false;
  35506. nodeMaterial.fog = false;
  35507. nodeMaterial.lights = false;
  35508. nodeMaterial.vertexNode = viewProj;
  35509. nodeMaterial.colorNode = backgroundMeshNode;
  35510. sceneData.backgroundMeshNode = backgroundMeshNode;
  35511. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  35512. backgroundMesh.frustumCulled = false;
  35513. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  35514. this.matrixWorld.copyPosition( camera.matrixWorld );
  35515. };
  35516. }
  35517. const backgroundCacheKey = backgroundNode.getCacheKey();
  35518. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  35519. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  35520. backgroundMesh.material.needsUpdate = true;
  35521. sceneData.backgroundCacheKey = backgroundCacheKey;
  35522. }
  35523. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  35524. } else {
  35525. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  35526. }
  35527. //
  35528. if ( renderer.autoClear === true || forceClear === true ) {
  35529. _clearColor.multiplyScalar( _clearColor.a );
  35530. const clearColorValue = renderContext.clearColorValue;
  35531. clearColorValue.r = _clearColor.r;
  35532. clearColorValue.g = _clearColor.g;
  35533. clearColorValue.b = _clearColor.b;
  35534. clearColorValue.a = _clearColor.a;
  35535. renderContext.depthClearValue = renderer._clearDepth;
  35536. renderContext.stencilClearValue = renderer._clearStencil;
  35537. renderContext.clearColor = renderer.autoClearColor === true;
  35538. renderContext.clearDepth = renderer.autoClearDepth === true;
  35539. renderContext.clearStencil = renderer.autoClearStencil === true;
  35540. } else {
  35541. renderContext.clearColor = false;
  35542. renderContext.clearDepth = false;
  35543. renderContext.clearStencil = false;
  35544. }
  35545. }
  35546. }
  35547. class NodeBuilderState {
  35548. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, instanceBindGroups = true, transforms = [] ) {
  35549. this.vertexShader = vertexShader;
  35550. this.fragmentShader = fragmentShader;
  35551. this.computeShader = computeShader;
  35552. this.transforms = transforms;
  35553. this.nodeAttributes = nodeAttributes;
  35554. this.bindings = bindings;
  35555. this.updateNodes = updateNodes;
  35556. this.updateBeforeNodes = updateBeforeNodes;
  35557. this.updateAfterNodes = updateAfterNodes;
  35558. this.instanceBindGroups = instanceBindGroups;
  35559. this.usedTimes = 0;
  35560. }
  35561. createBindings() {
  35562. const bindings = [];
  35563. for ( const instanceGroup of this.bindings ) {
  35564. const shared = this.instanceBindGroups && instanceGroup.bindings[ 0 ].groupNode.shared;
  35565. if ( shared !== true ) {
  35566. const bindingsGroup = new BindGroup( instanceGroup.name );
  35567. bindings.push( bindingsGroup );
  35568. for ( const instanceBinding of instanceGroup.bindings ) {
  35569. bindingsGroup.bindings.push( instanceBinding.clone() );
  35570. }
  35571. } else {
  35572. bindings.push( instanceGroup );
  35573. }
  35574. }
  35575. return bindings;
  35576. }
  35577. }
  35578. const outputNodeMap = new WeakMap();
  35579. class Nodes extends DataMap {
  35580. constructor( renderer, backend ) {
  35581. super();
  35582. this.renderer = renderer;
  35583. this.backend = backend;
  35584. this.nodeFrame = new NodeFrame();
  35585. this.nodeBuilderCache = new Map();
  35586. this.callHashCache = new ChainMap();
  35587. this.groupsData = new ChainMap();
  35588. }
  35589. updateGroup( nodeUniformsGroup ) {
  35590. const groupNode = nodeUniformsGroup.groupNode;
  35591. const name = groupNode.name;
  35592. // objectGroup is every updated
  35593. if ( name === objectGroup.name ) return true;
  35594. // renderGroup is updated once per render/compute call
  35595. if ( name === renderGroup.name ) {
  35596. const uniformsGroupData = this.get( nodeUniformsGroup );
  35597. const renderId = this.nodeFrame.renderId;
  35598. if ( uniformsGroupData.renderId !== renderId ) {
  35599. uniformsGroupData.renderId = renderId;
  35600. return true;
  35601. }
  35602. return false;
  35603. }
  35604. // frameGroup is updated once per frame
  35605. if ( name === frameGroup.name ) {
  35606. const uniformsGroupData = this.get( nodeUniformsGroup );
  35607. const frameId = this.nodeFrame.frameId;
  35608. if ( uniformsGroupData.frameId !== frameId ) {
  35609. uniformsGroupData.frameId = frameId;
  35610. return true;
  35611. }
  35612. return false;
  35613. }
  35614. // other groups are updated just when groupNode.needsUpdate is true
  35615. const groupChain = [ groupNode, nodeUniformsGroup ];
  35616. let groupData = this.groupsData.get( groupChain );
  35617. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  35618. if ( groupData.version !== groupNode.version ) {
  35619. groupData.version = groupNode.version;
  35620. return true;
  35621. }
  35622. return false;
  35623. }
  35624. getForRenderCacheKey( renderObject ) {
  35625. return renderObject.initialCacheKey;
  35626. }
  35627. getForRender( renderObject ) {
  35628. const renderObjectData = this.get( renderObject );
  35629. let nodeBuilderState = renderObjectData.nodeBuilderState;
  35630. if ( nodeBuilderState === undefined ) {
  35631. const { nodeBuilderCache } = this;
  35632. const cacheKey = this.getForRenderCacheKey( renderObject );
  35633. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  35634. if ( nodeBuilderState === undefined ) {
  35635. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  35636. nodeBuilder.scene = renderObject.scene;
  35637. nodeBuilder.material = renderObject.material;
  35638. nodeBuilder.camera = renderObject.camera;
  35639. nodeBuilder.context.material = renderObject.material;
  35640. nodeBuilder.lightsNode = renderObject.lightsNode;
  35641. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  35642. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  35643. nodeBuilder.clippingContext = renderObject.clippingContext;
  35644. nodeBuilder.build();
  35645. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35646. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  35647. }
  35648. nodeBuilderState.usedTimes ++;
  35649. renderObjectData.nodeBuilderState = nodeBuilderState;
  35650. }
  35651. return nodeBuilderState;
  35652. }
  35653. delete( object ) {
  35654. if ( object.isRenderObject ) {
  35655. const nodeBuilderState = this.get( object ).nodeBuilderState;
  35656. nodeBuilderState.usedTimes --;
  35657. if ( nodeBuilderState.usedTimes === 0 ) {
  35658. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  35659. }
  35660. }
  35661. return super.delete( object );
  35662. }
  35663. getForCompute( computeNode ) {
  35664. const computeData = this.get( computeNode );
  35665. let nodeBuilderState = computeData.nodeBuilderState;
  35666. if ( nodeBuilderState === undefined ) {
  35667. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  35668. nodeBuilder.build();
  35669. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35670. computeData.nodeBuilderState = nodeBuilderState;
  35671. }
  35672. return nodeBuilderState;
  35673. }
  35674. _createNodeBuilderState( nodeBuilder ) {
  35675. return new NodeBuilderState(
  35676. nodeBuilder.vertexShader,
  35677. nodeBuilder.fragmentShader,
  35678. nodeBuilder.computeShader,
  35679. nodeBuilder.getAttributesArray(),
  35680. nodeBuilder.getBindings(),
  35681. nodeBuilder.updateNodes,
  35682. nodeBuilder.updateBeforeNodes,
  35683. nodeBuilder.updateAfterNodes,
  35684. nodeBuilder.instanceBindGroups,
  35685. nodeBuilder.transforms
  35686. );
  35687. }
  35688. getEnvironmentNode( scene ) {
  35689. return scene.environmentNode || this.get( scene ).environmentNode || null;
  35690. }
  35691. getBackgroundNode( scene ) {
  35692. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  35693. }
  35694. getFogNode( scene ) {
  35695. return scene.fogNode || this.get( scene ).fogNode || null;
  35696. }
  35697. getCacheKey( scene, lightsNode ) {
  35698. const chain = [ scene, lightsNode ];
  35699. const callId = this.renderer.info.calls;
  35700. let cacheKeyData = this.callHashCache.get( chain );
  35701. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  35702. const environmentNode = this.getEnvironmentNode( scene );
  35703. const fogNode = this.getFogNode( scene );
  35704. const cacheKey = [];
  35705. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey() );
  35706. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  35707. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  35708. cacheKeyData = {
  35709. callId,
  35710. cacheKey: cacheKey.join( ',' )
  35711. };
  35712. this.callHashCache.set( chain, cacheKeyData );
  35713. }
  35714. return cacheKeyData.cacheKey;
  35715. }
  35716. updateScene( scene ) {
  35717. this.updateEnvironment( scene );
  35718. this.updateFog( scene );
  35719. this.updateBackground( scene );
  35720. }
  35721. get isToneMappingState() {
  35722. return this.renderer.getRenderTarget() ? false : true;
  35723. }
  35724. updateBackground( scene ) {
  35725. const sceneData = this.get( scene );
  35726. const background = scene.background;
  35727. if ( background ) {
  35728. if ( sceneData.background !== background ) {
  35729. let backgroundNode = null;
  35730. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping ) ) {
  35731. backgroundNode = pmremTexture( background, normalWorld );
  35732. } else if ( background.isTexture === true ) {
  35733. backgroundNode = texture( background, viewportBottomLeft ).setUpdateMatrix( true );
  35734. } else if ( background.isColor !== true ) {
  35735. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  35736. }
  35737. sceneData.backgroundNode = backgroundNode;
  35738. sceneData.background = background;
  35739. }
  35740. } else if ( sceneData.backgroundNode ) {
  35741. delete sceneData.backgroundNode;
  35742. delete sceneData.background;
  35743. }
  35744. }
  35745. updateFog( scene ) {
  35746. const sceneData = this.get( scene );
  35747. const fog = scene.fog;
  35748. if ( fog ) {
  35749. if ( sceneData.fog !== fog ) {
  35750. let fogNode = null;
  35751. if ( fog.isFogExp2 ) {
  35752. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  35753. } else if ( fog.isFog ) {
  35754. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  35755. } else {
  35756. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  35757. }
  35758. sceneData.fogNode = fogNode;
  35759. sceneData.fog = fog;
  35760. }
  35761. } else {
  35762. delete sceneData.fogNode;
  35763. delete sceneData.fog;
  35764. }
  35765. }
  35766. updateEnvironment( scene ) {
  35767. const sceneData = this.get( scene );
  35768. const environment = scene.environment;
  35769. if ( environment ) {
  35770. if ( sceneData.environment !== environment ) {
  35771. let environmentNode = null;
  35772. if ( environment.isCubeTexture === true ) {
  35773. environmentNode = cubeTexture( environment );
  35774. } else if ( environment.isTexture === true ) {
  35775. environmentNode = texture( environment );
  35776. } else {
  35777. console.error( 'Nodes: Unsupported environment configuration.', environment );
  35778. }
  35779. sceneData.environmentNode = environmentNode;
  35780. sceneData.environment = environment;
  35781. }
  35782. } else if ( sceneData.environmentNode ) {
  35783. delete sceneData.environmentNode;
  35784. delete sceneData.environment;
  35785. }
  35786. }
  35787. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  35788. const nodeFrame = this.nodeFrame;
  35789. nodeFrame.renderer = renderer;
  35790. nodeFrame.scene = scene;
  35791. nodeFrame.object = object;
  35792. nodeFrame.camera = camera;
  35793. nodeFrame.material = material;
  35794. return nodeFrame;
  35795. }
  35796. getNodeFrameForRender( renderObject ) {
  35797. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  35798. }
  35799. getOutputCacheKey() {
  35800. const renderer = this.renderer;
  35801. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  35802. }
  35803. hasOutputChange( outputTarget ) {
  35804. const cacheKey = outputNodeMap.get( outputTarget );
  35805. return cacheKey !== this.getOutputCacheKey();
  35806. }
  35807. getOutputNode( outputTexture ) {
  35808. const renderer = this.renderer;
  35809. const cacheKey = this.getOutputCacheKey();
  35810. const output = texture( outputTexture, viewportTopLeft ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  35811. outputNodeMap.set( outputTexture, cacheKey );
  35812. return output;
  35813. }
  35814. updateBefore( renderObject ) {
  35815. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35816. const nodeBuilder = renderObject.getNodeBuilderState();
  35817. for ( const node of nodeBuilder.updateBeforeNodes ) {
  35818. nodeFrame.updateBeforeNode( node );
  35819. }
  35820. }
  35821. updateAfter( renderObject ) {
  35822. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35823. const nodeBuilder = renderObject.getNodeBuilderState();
  35824. for ( const node of nodeBuilder.updateAfterNodes ) {
  35825. nodeFrame.updateAfterNode( node );
  35826. }
  35827. }
  35828. updateForCompute( computeNode ) {
  35829. const nodeFrame = this.getNodeFrame();
  35830. const nodeBuilder = this.getForCompute( computeNode );
  35831. for ( const node of nodeBuilder.updateNodes ) {
  35832. nodeFrame.updateNode( node );
  35833. }
  35834. }
  35835. updateForRender( renderObject ) {
  35836. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35837. const nodeBuilder = renderObject.getNodeBuilderState();
  35838. for ( const node of nodeBuilder.updateNodes ) {
  35839. nodeFrame.updateNode( node );
  35840. }
  35841. }
  35842. dispose() {
  35843. super.dispose();
  35844. this.nodeFrame = new NodeFrame();
  35845. this.nodeBuilderCache = new Map();
  35846. }
  35847. }
  35848. class RenderBundle {
  35849. constructor( scene, camera ) {
  35850. this.scene = scene;
  35851. this.camera = camera;
  35852. }
  35853. clone() {
  35854. return Object.assign( new this.constructor(), this );
  35855. }
  35856. }
  35857. class RenderBundles {
  35858. constructor() {
  35859. this.lists = new ChainMap();
  35860. }
  35861. get( scene, camera ) {
  35862. const lists = this.lists;
  35863. const keys = [ scene, camera ];
  35864. let list = lists.get( keys );
  35865. if ( list === undefined ) {
  35866. list = new RenderBundle( scene, camera );
  35867. lists.set( keys, list );
  35868. }
  35869. return list;
  35870. }
  35871. dispose() {
  35872. this.lists = new ChainMap();
  35873. }
  35874. }
  35875. const _scene = new Scene();
  35876. const _drawingBufferSize = new Vector2();
  35877. const _screen = new Vector4();
  35878. const _frustum = new Frustum();
  35879. const _projScreenMatrix = new Matrix4();
  35880. const _vector3 = new Vector3();
  35881. class Renderer {
  35882. constructor( backend, parameters = {} ) {
  35883. this.isRenderer = true;
  35884. //
  35885. const {
  35886. logarithmicDepthBuffer = false,
  35887. alpha = true,
  35888. antialias = false,
  35889. samples = 0
  35890. } = parameters;
  35891. // public
  35892. this.domElement = backend.getDomElement();
  35893. this.backend = backend;
  35894. this.samples = samples || ( antialias === true ) ? 4 : 0;
  35895. this.autoClear = true;
  35896. this.autoClearColor = true;
  35897. this.autoClearDepth = true;
  35898. this.autoClearStencil = true;
  35899. this.alpha = alpha;
  35900. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  35901. this.outputColorSpace = SRGBColorSpace;
  35902. this.toneMapping = NoToneMapping;
  35903. this.toneMappingExposure = 1.0;
  35904. this.sortObjects = true;
  35905. this.depth = true;
  35906. this.stencil = false;
  35907. this.clippingPlanes = [];
  35908. this.info = new Info();
  35909. // internals
  35910. this._pixelRatio = 1;
  35911. this._width = this.domElement.width;
  35912. this._height = this.domElement.height;
  35913. this._viewport = new Vector4( 0, 0, this._width, this._height );
  35914. this._scissor = new Vector4( 0, 0, this._width, this._height );
  35915. this._scissorTest = false;
  35916. this._attributes = null;
  35917. this._geometries = null;
  35918. this._nodes = null;
  35919. this._animation = null;
  35920. this._bindings = null;
  35921. this._objects = null;
  35922. this._pipelines = null;
  35923. this._bundles = null;
  35924. this._renderLists = null;
  35925. this._renderContexts = null;
  35926. this._textures = null;
  35927. this._background = null;
  35928. this._quad = new QuadMesh( new NodeMaterial() );
  35929. this._currentRenderContext = null;
  35930. this._opaqueSort = null;
  35931. this._transparentSort = null;
  35932. this._frameBufferTarget = null;
  35933. const alphaClear = this.alpha === true ? 0 : 1;
  35934. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  35935. this._clearDepth = 1;
  35936. this._clearStencil = 0;
  35937. this._renderTarget = null;
  35938. this._activeCubeFace = 0;
  35939. this._activeMipmapLevel = 0;
  35940. this._mrt = null;
  35941. this._renderObjectFunction = null;
  35942. this._currentRenderObjectFunction = null;
  35943. this._currentRenderBundle = null;
  35944. this._handleObjectFunction = this._renderObjectDirect;
  35945. this._initialized = false;
  35946. this._initPromise = null;
  35947. this._compilationPromises = null;
  35948. // backwards compatibility
  35949. this.shadowMap = {
  35950. enabled: false,
  35951. type: null
  35952. };
  35953. this.xr = {
  35954. enabled: false
  35955. };
  35956. this.debug = {
  35957. checkShaderErrors: true,
  35958. onShaderError: null
  35959. };
  35960. }
  35961. async init() {
  35962. if ( this._initialized ) {
  35963. throw new Error( 'Renderer: Backend has already been initialized.' );
  35964. }
  35965. if ( this._initPromise !== null ) {
  35966. return this._initPromise;
  35967. }
  35968. this._initPromise = new Promise( async ( resolve, reject ) => {
  35969. const backend = this.backend;
  35970. try {
  35971. await backend.init( this );
  35972. } catch ( error ) {
  35973. reject( error );
  35974. return;
  35975. }
  35976. this._nodes = new Nodes( this, backend );
  35977. this._animation = new Animation( this._nodes, this.info );
  35978. this._attributes = new Attributes( backend );
  35979. this._background = new Background( this, this._nodes );
  35980. this._geometries = new Geometries( this._attributes, this.info );
  35981. this._textures = new Textures( this, backend, this.info );
  35982. this._pipelines = new Pipelines( backend, this._nodes );
  35983. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35984. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35985. this._renderLists = new RenderLists();
  35986. this._bundles = new RenderBundles();
  35987. this._renderContexts = new RenderContexts();
  35988. //
  35989. this._initialized = true;
  35990. resolve();
  35991. } );
  35992. return this._initPromise;
  35993. }
  35994. get coordinateSystem() {
  35995. return this.backend.coordinateSystem;
  35996. }
  35997. async compileAsync( scene, camera, targetScene = null ) {
  35998. if ( this._initialized === false ) await this.init();
  35999. // preserve render tree
  36000. const nodeFrame = this._nodes.nodeFrame;
  36001. const previousRenderId = nodeFrame.renderId;
  36002. const previousRenderContext = this._currentRenderContext;
  36003. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  36004. const previousCompilationPromises = this._compilationPromises;
  36005. //
  36006. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  36007. if ( targetScene === null ) targetScene = scene;
  36008. const renderTarget = this._renderTarget;
  36009. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  36010. const activeMipmapLevel = this._activeMipmapLevel;
  36011. const compilationPromises = [];
  36012. this._currentRenderContext = renderContext;
  36013. this._currentRenderObjectFunction = this.renderObject;
  36014. this._handleObjectFunction = this._createObjectPipeline;
  36015. this._compilationPromises = compilationPromises;
  36016. nodeFrame.renderId ++;
  36017. //
  36018. nodeFrame.update();
  36019. //
  36020. renderContext.depth = this.depth;
  36021. renderContext.stencil = this.stencil;
  36022. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36023. renderContext.clippingContext.updateGlobal( this, camera );
  36024. //
  36025. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36026. //
  36027. const renderList = this._renderLists.get( scene, camera );
  36028. renderList.begin();
  36029. this._projectObject( scene, camera, 0, renderList );
  36030. // include lights from target scene
  36031. if ( targetScene !== scene ) {
  36032. targetScene.traverseVisible( function ( object ) {
  36033. if ( object.isLight && object.layers.test( camera.layers ) ) {
  36034. renderList.pushLight( object );
  36035. }
  36036. } );
  36037. }
  36038. renderList.finish();
  36039. //
  36040. if ( renderTarget !== null ) {
  36041. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36042. const renderTargetData = this._textures.get( renderTarget );
  36043. renderContext.textures = renderTargetData.textures;
  36044. renderContext.depthTexture = renderTargetData.depthTexture;
  36045. } else {
  36046. renderContext.textures = null;
  36047. renderContext.depthTexture = null;
  36048. }
  36049. //
  36050. this._nodes.updateScene( sceneRef );
  36051. //
  36052. this._background.update( sceneRef, renderList, renderContext );
  36053. // process render lists
  36054. const opaqueObjects = renderList.opaque;
  36055. const transparentObjects = renderList.transparent;
  36056. const lightsNode = renderList.lightsNode;
  36057. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36058. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  36059. // restore render tree
  36060. nodeFrame.renderId = previousRenderId;
  36061. this._currentRenderContext = previousRenderContext;
  36062. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36063. this._compilationPromises = previousCompilationPromises;
  36064. this._handleObjectFunction = this._renderObjectDirect;
  36065. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  36066. await Promise.all( compilationPromises );
  36067. }
  36068. async renderAsync( scene, camera ) {
  36069. if ( this._initialized === false ) await this.init();
  36070. const renderContext = this._renderScene( scene, camera );
  36071. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  36072. }
  36073. setMRT( mrt ) {
  36074. this._mrt = mrt;
  36075. return this;
  36076. }
  36077. getMRT() {
  36078. return this._mrt;
  36079. }
  36080. _renderBundle( bundle, sceneRef, lightsNode ) {
  36081. const { object, camera, renderList } = bundle;
  36082. const renderContext = this._currentRenderContext;
  36083. const renderContextData = this.backend.get( renderContext );
  36084. //
  36085. const renderBundle = this._bundles.get( object, camera );
  36086. const renderBundleData = this.backend.get( renderBundle );
  36087. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  36088. //
  36089. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || object.needsUpdate === true;
  36090. renderBundleData.renderContexts.add( renderContext );
  36091. if ( renderBundleNeedsUpdate ) {
  36092. if ( renderContextData.renderObjects === undefined || object.needsUpdate === true ) {
  36093. const nodeFrame = this._nodes.nodeFrame;
  36094. renderContextData.renderObjects = [];
  36095. renderContextData.renderBundles = [];
  36096. renderContextData.scene = sceneRef;
  36097. renderContextData.camera = camera;
  36098. renderContextData.renderId = nodeFrame.renderId;
  36099. renderContextData.registerBundlesPhase = true;
  36100. }
  36101. this._currentRenderBundle = renderBundle;
  36102. const opaqueObjects = renderList.opaque;
  36103. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36104. this._currentRenderBundle = null;
  36105. //
  36106. object.needsUpdate = false;
  36107. } else {
  36108. const renderContext = this._currentRenderContext;
  36109. const renderContextData = this.backend.get( renderContext );
  36110. for ( let i = 0, l = renderContextData.renderObjects.length; i < l; i ++ ) {
  36111. const renderObject = renderContextData.renderObjects[ i ];
  36112. this._nodes.updateBefore( renderObject );
  36113. //
  36114. renderObject.object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, renderObject.object.matrixWorld );
  36115. renderObject.object.normalMatrix.getNormalMatrix( renderObject.object.modelViewMatrix );
  36116. this._nodes.updateForRender( renderObject );
  36117. this._bindings.updateForRender( renderObject );
  36118. this.backend.draw( renderObject, this.info );
  36119. this._nodes.updateAfter( renderObject );
  36120. }
  36121. }
  36122. }
  36123. render( scene, camera ) {
  36124. if ( this._initialized === false ) {
  36125. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  36126. return this.renderAsync( scene, camera );
  36127. }
  36128. this._renderScene( scene, camera );
  36129. }
  36130. _getFrameBufferTarget() {
  36131. const { currentColorSpace } = this;
  36132. const useToneMapping = this._renderTarget === null && ( this.toneMapping !== NoToneMapping );
  36133. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace && currentColorSpace !== NoColorSpace;
  36134. if ( useToneMapping === false && useColorSpace === false ) return null;
  36135. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  36136. const { depth, stencil } = this;
  36137. let frameBufferTarget = this._frameBufferTarget;
  36138. if ( frameBufferTarget === null ) {
  36139. frameBufferTarget = new RenderTarget( width, height, {
  36140. depthBuffer: depth,
  36141. stencilBuffer: stencil,
  36142. type: HalfFloatType, // FloatType
  36143. format: RGBAFormat,
  36144. colorSpace: LinearSRGBColorSpace,
  36145. generateMipmaps: false,
  36146. minFilter: LinearFilter,
  36147. magFilter: LinearFilter,
  36148. samples: this.samples
  36149. } );
  36150. frameBufferTarget.isPostProcessingRenderTarget = true;
  36151. this._frameBufferTarget = frameBufferTarget;
  36152. }
  36153. frameBufferTarget.depthBuffer = depth;
  36154. frameBufferTarget.stencilBuffer = stencil;
  36155. frameBufferTarget.setSize( width, height );
  36156. frameBufferTarget.viewport.copy( this._viewport );
  36157. frameBufferTarget.scissor.copy( this._scissor );
  36158. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  36159. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  36160. frameBufferTarget.scissorTest = this._scissorTest;
  36161. return frameBufferTarget;
  36162. }
  36163. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  36164. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  36165. // preserve render tree
  36166. const nodeFrame = this._nodes.nodeFrame;
  36167. const previousRenderId = nodeFrame.renderId;
  36168. const previousRenderContext = this._currentRenderContext;
  36169. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  36170. //
  36171. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  36172. const outputRenderTarget = this._renderTarget;
  36173. const activeCubeFace = this._activeCubeFace;
  36174. const activeMipmapLevel = this._activeMipmapLevel;
  36175. //
  36176. let renderTarget;
  36177. if ( frameBufferTarget !== null ) {
  36178. renderTarget = frameBufferTarget;
  36179. this.setRenderTarget( renderTarget );
  36180. } else {
  36181. renderTarget = outputRenderTarget;
  36182. }
  36183. //
  36184. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  36185. this._currentRenderContext = renderContext;
  36186. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  36187. //
  36188. this.info.calls ++;
  36189. this.info.render.calls ++;
  36190. this.info.render.frameCalls ++;
  36191. nodeFrame.renderId = this.info.calls;
  36192. //
  36193. const coordinateSystem = this.coordinateSystem;
  36194. if ( camera.coordinateSystem !== coordinateSystem ) {
  36195. camera.coordinateSystem = coordinateSystem;
  36196. camera.updateProjectionMatrix();
  36197. }
  36198. //
  36199. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  36200. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  36201. //
  36202. let viewport = this._viewport;
  36203. let scissor = this._scissor;
  36204. let pixelRatio = this._pixelRatio;
  36205. if ( renderTarget !== null ) {
  36206. viewport = renderTarget.viewport;
  36207. scissor = renderTarget.scissor;
  36208. pixelRatio = 1;
  36209. }
  36210. this.getDrawingBufferSize( _drawingBufferSize );
  36211. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  36212. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  36213. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  36214. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  36215. renderContext.viewportValue.width >>= activeMipmapLevel;
  36216. renderContext.viewportValue.height >>= activeMipmapLevel;
  36217. renderContext.viewportValue.minDepth = minDepth;
  36218. renderContext.viewportValue.maxDepth = maxDepth;
  36219. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  36220. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  36221. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  36222. renderContext.scissorValue.width >>= activeMipmapLevel;
  36223. renderContext.scissorValue.height >>= activeMipmapLevel;
  36224. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36225. renderContext.clippingContext.updateGlobal( this, camera );
  36226. //
  36227. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36228. //
  36229. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  36230. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  36231. const renderList = this._renderLists.get( scene, camera );
  36232. renderList.begin();
  36233. this._projectObject( scene, camera, 0, renderList );
  36234. renderList.finish();
  36235. if ( this.sortObjects === true ) {
  36236. renderList.sort( this._opaqueSort, this._transparentSort );
  36237. }
  36238. //
  36239. if ( renderTarget !== null ) {
  36240. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36241. const renderTargetData = this._textures.get( renderTarget );
  36242. renderContext.textures = renderTargetData.textures;
  36243. renderContext.depthTexture = renderTargetData.depthTexture;
  36244. renderContext.width = renderTargetData.width;
  36245. renderContext.height = renderTargetData.height;
  36246. renderContext.renderTarget = renderTarget;
  36247. renderContext.depth = renderTarget.depthBuffer;
  36248. renderContext.stencil = renderTarget.stencilBuffer;
  36249. } else {
  36250. renderContext.textures = null;
  36251. renderContext.depthTexture = null;
  36252. renderContext.width = this.domElement.width;
  36253. renderContext.height = this.domElement.height;
  36254. renderContext.depth = this.depth;
  36255. renderContext.stencil = this.stencil;
  36256. }
  36257. renderContext.width >>= activeMipmapLevel;
  36258. renderContext.height >>= activeMipmapLevel;
  36259. renderContext.activeCubeFace = activeCubeFace;
  36260. renderContext.activeMipmapLevel = activeMipmapLevel;
  36261. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  36262. //
  36263. this._nodes.updateScene( sceneRef );
  36264. //
  36265. this._background.update( sceneRef, renderList, renderContext );
  36266. //
  36267. this.backend.beginRender( renderContext );
  36268. // process render lists
  36269. const opaqueObjects = renderList.opaque;
  36270. const transparentObjects = renderList.transparent;
  36271. const bundles = renderList.bundles;
  36272. const lightsNode = renderList.lightsNode;
  36273. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  36274. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36275. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  36276. // finish render pass
  36277. this.backend.finishRender( renderContext );
  36278. // restore render tree
  36279. nodeFrame.renderId = previousRenderId;
  36280. this._currentRenderContext = previousRenderContext;
  36281. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36282. //
  36283. if ( frameBufferTarget !== null ) {
  36284. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  36285. const quad = this._quad;
  36286. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  36287. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36288. quad.material.needsUpdate = true;
  36289. }
  36290. this._renderScene( quad, quad.camera, false );
  36291. }
  36292. //
  36293. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  36294. //
  36295. return renderContext;
  36296. }
  36297. getMaxAnisotropy() {
  36298. return this.backend.getMaxAnisotropy();
  36299. }
  36300. getActiveCubeFace() {
  36301. return this._activeCubeFace;
  36302. }
  36303. getActiveMipmapLevel() {
  36304. return this._activeMipmapLevel;
  36305. }
  36306. async setAnimationLoop( callback ) {
  36307. if ( this._initialized === false ) await this.init();
  36308. this._animation.setAnimationLoop( callback );
  36309. }
  36310. async getArrayBufferAsync( attribute ) {
  36311. return await this.backend.getArrayBufferAsync( attribute );
  36312. }
  36313. getContext() {
  36314. return this.backend.getContext();
  36315. }
  36316. getPixelRatio() {
  36317. return this._pixelRatio;
  36318. }
  36319. getDrawingBufferSize( target ) {
  36320. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  36321. }
  36322. getSize( target ) {
  36323. return target.set( this._width, this._height );
  36324. }
  36325. setPixelRatio( value = 1 ) {
  36326. this._pixelRatio = value;
  36327. this.setSize( this._width, this._height, false );
  36328. }
  36329. setDrawingBufferSize( width, height, pixelRatio ) {
  36330. this._width = width;
  36331. this._height = height;
  36332. this._pixelRatio = pixelRatio;
  36333. this.domElement.width = Math.floor( width * pixelRatio );
  36334. this.domElement.height = Math.floor( height * pixelRatio );
  36335. this.setViewport( 0, 0, width, height );
  36336. if ( this._initialized ) this.backend.updateSize();
  36337. }
  36338. setSize( width, height, updateStyle = true ) {
  36339. this._width = width;
  36340. this._height = height;
  36341. this.domElement.width = Math.floor( width * this._pixelRatio );
  36342. this.domElement.height = Math.floor( height * this._pixelRatio );
  36343. if ( updateStyle === true ) {
  36344. this.domElement.style.width = width + 'px';
  36345. this.domElement.style.height = height + 'px';
  36346. }
  36347. this.setViewport( 0, 0, width, height );
  36348. if ( this._initialized ) this.backend.updateSize();
  36349. }
  36350. setOpaqueSort( method ) {
  36351. this._opaqueSort = method;
  36352. }
  36353. setTransparentSort( method ) {
  36354. this._transparentSort = method;
  36355. }
  36356. getScissor( target ) {
  36357. const scissor = this._scissor;
  36358. target.x = scissor.x;
  36359. target.y = scissor.y;
  36360. target.width = scissor.width;
  36361. target.height = scissor.height;
  36362. return target;
  36363. }
  36364. setScissor( x, y, width, height ) {
  36365. const scissor = this._scissor;
  36366. if ( x.isVector4 ) {
  36367. scissor.copy( x );
  36368. } else {
  36369. scissor.set( x, y, width, height );
  36370. }
  36371. }
  36372. getScissorTest() {
  36373. return this._scissorTest;
  36374. }
  36375. setScissorTest( boolean ) {
  36376. this._scissorTest = boolean;
  36377. this.backend.setScissorTest( boolean );
  36378. }
  36379. getViewport( target ) {
  36380. return target.copy( this._viewport );
  36381. }
  36382. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  36383. const viewport = this._viewport;
  36384. if ( x.isVector4 ) {
  36385. viewport.copy( x );
  36386. } else {
  36387. viewport.set( x, y, width, height );
  36388. }
  36389. viewport.minDepth = minDepth;
  36390. viewport.maxDepth = maxDepth;
  36391. }
  36392. getClearColor( target ) {
  36393. return target.copy( this._clearColor );
  36394. }
  36395. setClearColor( color, alpha = 1 ) {
  36396. this._clearColor.set( color );
  36397. this._clearColor.a = alpha;
  36398. }
  36399. getClearAlpha() {
  36400. return this._clearColor.a;
  36401. }
  36402. setClearAlpha( alpha ) {
  36403. this._clearColor.a = alpha;
  36404. }
  36405. getClearDepth() {
  36406. return this._clearDepth;
  36407. }
  36408. setClearDepth( depth ) {
  36409. this._clearDepth = depth;
  36410. }
  36411. getClearStencil() {
  36412. return this._clearStencil;
  36413. }
  36414. setClearStencil( stencil ) {
  36415. this._clearStencil = stencil;
  36416. }
  36417. isOccluded( object ) {
  36418. const renderContext = this._currentRenderContext;
  36419. return renderContext && this.backend.isOccluded( renderContext, object );
  36420. }
  36421. clear( color = true, depth = true, stencil = true ) {
  36422. if ( this._initialized === false ) {
  36423. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  36424. return this.clearAsync( color, depth, stencil );
  36425. }
  36426. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36427. let renderTargetData = null;
  36428. if ( renderTarget !== null ) {
  36429. this._textures.updateRenderTarget( renderTarget );
  36430. renderTargetData = this._textures.get( renderTarget );
  36431. }
  36432. this.backend.clear( color, depth, stencil, renderTargetData );
  36433. if ( renderTarget !== null && this._renderTarget === null ) {
  36434. // If a color space transform or tone mapping is required,
  36435. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  36436. const quad = this._quad;
  36437. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  36438. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36439. quad.material.needsUpdate = true;
  36440. }
  36441. this._renderScene( quad, quad.camera, false );
  36442. }
  36443. }
  36444. clearColor() {
  36445. return this.clear( true, false, false );
  36446. }
  36447. clearDepth() {
  36448. return this.clear( false, true, false );
  36449. }
  36450. clearStencil() {
  36451. return this.clear( false, false, true );
  36452. }
  36453. async clearAsync( color = true, depth = true, stencil = true ) {
  36454. if ( this._initialized === false ) await this.init();
  36455. this.clear( color, depth, stencil );
  36456. }
  36457. clearColorAsync() {
  36458. return this.clearAsync( true, false, false );
  36459. }
  36460. clearDepthAsync() {
  36461. return this.clearAsync( false, true, false );
  36462. }
  36463. clearStencilAsync() {
  36464. return this.clearAsync( false, false, true );
  36465. }
  36466. get currentColorSpace() {
  36467. const renderTarget = this._renderTarget;
  36468. if ( renderTarget !== null ) {
  36469. const texture = renderTarget.texture;
  36470. return ( Array.isArray( texture ) ? texture[ 0 ] : texture ).colorSpace;
  36471. }
  36472. return this.outputColorSpace;
  36473. }
  36474. dispose() {
  36475. this.info.dispose();
  36476. this._animation.dispose();
  36477. this._objects.dispose();
  36478. this._pipelines.dispose();
  36479. this._nodes.dispose();
  36480. this._bindings.dispose();
  36481. this._renderLists.dispose();
  36482. this._renderContexts.dispose();
  36483. this._textures.dispose();
  36484. this.setRenderTarget( null );
  36485. this.setAnimationLoop( null );
  36486. }
  36487. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  36488. this._renderTarget = renderTarget;
  36489. this._activeCubeFace = activeCubeFace;
  36490. this._activeMipmapLevel = activeMipmapLevel;
  36491. }
  36492. getRenderTarget() {
  36493. return this._renderTarget;
  36494. }
  36495. setRenderObjectFunction( renderObjectFunction ) {
  36496. this._renderObjectFunction = renderObjectFunction;
  36497. }
  36498. getRenderObjectFunction() {
  36499. return this._renderObjectFunction;
  36500. }
  36501. async computeAsync( computeNodes ) {
  36502. if ( this._initialized === false ) await this.init();
  36503. const nodeFrame = this._nodes.nodeFrame;
  36504. const previousRenderId = nodeFrame.renderId;
  36505. //
  36506. this.info.calls ++;
  36507. this.info.compute.calls ++;
  36508. this.info.compute.frameCalls ++;
  36509. nodeFrame.renderId = this.info.calls;
  36510. //
  36511. const backend = this.backend;
  36512. const pipelines = this._pipelines;
  36513. const bindings = this._bindings;
  36514. const nodes = this._nodes;
  36515. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36516. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36517. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36518. }
  36519. backend.beginCompute( computeNodes );
  36520. for ( const computeNode of computeList ) {
  36521. // onInit
  36522. if ( pipelines.has( computeNode ) === false ) {
  36523. const dispose = () => {
  36524. computeNode.removeEventListener( 'dispose', dispose );
  36525. pipelines.delete( computeNode );
  36526. bindings.delete( computeNode );
  36527. nodes.delete( computeNode );
  36528. };
  36529. computeNode.addEventListener( 'dispose', dispose );
  36530. //
  36531. computeNode.onInit( { renderer: this } );
  36532. }
  36533. nodes.updateForCompute( computeNode );
  36534. bindings.updateForCompute( computeNode );
  36535. const computeBindings = bindings.getForCompute( computeNode );
  36536. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  36537. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  36538. }
  36539. backend.finishCompute( computeNodes );
  36540. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  36541. //
  36542. nodeFrame.renderId = previousRenderId;
  36543. }
  36544. async hasFeatureAsync( name ) {
  36545. if ( this._initialized === false ) await this.init();
  36546. return this.backend.hasFeature( name );
  36547. }
  36548. hasFeature( name ) {
  36549. if ( this._initialized === false ) {
  36550. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  36551. return false;
  36552. }
  36553. return this.backend.hasFeature( name );
  36554. }
  36555. copyFramebufferToTexture( framebufferTexture ) {
  36556. const renderContext = this._currentRenderContext;
  36557. this._textures.updateTexture( framebufferTexture );
  36558. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  36559. }
  36560. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  36561. this._textures.updateTexture( srcTexture );
  36562. this._textures.updateTexture( dstTexture );
  36563. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  36564. }
  36565. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0 ) {
  36566. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height );
  36567. }
  36568. _projectObject( object, camera, groupOrder, renderList ) {
  36569. if ( object.visible === false ) return;
  36570. const visible = object.layers.test( camera.layers );
  36571. if ( visible ) {
  36572. if ( object.isGroup ) {
  36573. groupOrder = object.renderOrder;
  36574. } else if ( object.isLOD ) {
  36575. if ( object.autoUpdate === true ) object.update( camera );
  36576. } else if ( object.isLight ) {
  36577. renderList.pushLight( object );
  36578. } else if ( object.isSprite ) {
  36579. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  36580. if ( this.sortObjects === true ) {
  36581. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  36582. }
  36583. const geometry = object.geometry;
  36584. const material = object.material;
  36585. if ( material.visible ) {
  36586. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36587. }
  36588. }
  36589. } else if ( object.isLineLoop ) {
  36590. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  36591. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  36592. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  36593. const geometry = object.geometry;
  36594. const material = object.material;
  36595. if ( this.sortObjects === true ) {
  36596. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  36597. _vector3
  36598. .copy( geometry.boundingSphere.center )
  36599. .applyMatrix4( object.matrixWorld )
  36600. .applyMatrix4( _projScreenMatrix );
  36601. }
  36602. if ( Array.isArray( material ) ) {
  36603. const groups = geometry.groups;
  36604. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  36605. const group = groups[ i ];
  36606. const groupMaterial = material[ group.materialIndex ];
  36607. if ( groupMaterial && groupMaterial.visible ) {
  36608. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  36609. }
  36610. }
  36611. } else if ( material.visible ) {
  36612. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  36613. }
  36614. }
  36615. }
  36616. }
  36617. if ( object.static === true ) {
  36618. const baseRenderList = renderList;
  36619. // replace render list
  36620. renderList = this._renderLists.get( object, camera );
  36621. renderList.begin();
  36622. baseRenderList.pushBundle( {
  36623. object,
  36624. camera,
  36625. renderList,
  36626. } );
  36627. renderList.finish();
  36628. }
  36629. const children = object.children;
  36630. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36631. this._projectObject( children[ i ], camera, groupOrder, renderList );
  36632. }
  36633. }
  36634. _renderBundles( bundles, sceneRef, lightsNode ) {
  36635. for ( const bundle of bundles ) {
  36636. this._renderBundle( bundle, sceneRef, lightsNode );
  36637. }
  36638. }
  36639. _renderObjects( renderList, camera, scene, lightsNode ) {
  36640. // process renderable objects
  36641. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36642. const renderItem = renderList[ i ];
  36643. // @TODO: Add support for multiple materials per object. This will require to extract
  36644. // the material from the renderItem object and pass it with its group data to renderObject().
  36645. const { object, geometry, material, group } = renderItem;
  36646. if ( camera.isArrayCamera ) {
  36647. const cameras = camera.cameras;
  36648. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  36649. const camera2 = cameras[ j ];
  36650. if ( object.layers.test( camera2.layers ) ) {
  36651. const vp = camera2.viewport;
  36652. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  36653. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  36654. const viewportValue = this._currentRenderContext.viewportValue;
  36655. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  36656. viewportValue.minDepth = minDepth;
  36657. viewportValue.maxDepth = maxDepth;
  36658. this.backend.updateViewport( this._currentRenderContext );
  36659. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  36660. }
  36661. }
  36662. } else {
  36663. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  36664. }
  36665. }
  36666. }
  36667. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  36668. let overridePositionNode;
  36669. let overrideFragmentNode;
  36670. let overrideDepthNode;
  36671. //
  36672. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36673. //
  36674. if ( scene.overrideMaterial !== null ) {
  36675. const overrideMaterial = scene.overrideMaterial;
  36676. if ( material.positionNode && material.positionNode.isNode ) {
  36677. overridePositionNode = overrideMaterial.positionNode;
  36678. overrideMaterial.positionNode = material.positionNode;
  36679. }
  36680. if ( overrideMaterial.isShadowNodeMaterial ) {
  36681. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36682. if ( material.depthNode && material.depthNode.isNode ) {
  36683. overrideDepthNode = overrideMaterial.depthNode;
  36684. overrideMaterial.depthNode = material.depthNode;
  36685. }
  36686. if ( material.shadowNode && material.shadowNode.isNode ) {
  36687. overrideFragmentNode = overrideMaterial.fragmentNode;
  36688. overrideMaterial.fragmentNode = material.shadowNode;
  36689. }
  36690. if ( this.localClippingEnabled ) {
  36691. if ( material.clipShadows ) {
  36692. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  36693. overrideMaterial.clippingPlanes = material.clippingPlanes;
  36694. overrideMaterial.needsUpdate = true;
  36695. }
  36696. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  36697. overrideMaterial.clipIntersection = material.clipIntersection;
  36698. }
  36699. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  36700. overrideMaterial.clippingPlanes = null;
  36701. overrideMaterial.needsUpdate = true;
  36702. }
  36703. }
  36704. }
  36705. material = overrideMaterial;
  36706. }
  36707. //
  36708. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36709. material.side = BackSide;
  36710. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  36711. material.side = FrontSide;
  36712. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  36713. material.side = DoubleSide;
  36714. } else {
  36715. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  36716. }
  36717. //
  36718. if ( overridePositionNode !== undefined ) {
  36719. scene.overrideMaterial.positionNode = overridePositionNode;
  36720. }
  36721. if ( overrideDepthNode !== undefined ) {
  36722. scene.overrideMaterial.depthNode = overrideDepthNode;
  36723. }
  36724. if ( overrideFragmentNode !== undefined ) {
  36725. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  36726. }
  36727. //
  36728. object.onAfterRender( this, scene, camera, geometry, material, group );
  36729. }
  36730. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  36731. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36732. renderObject.drawRange = group || object.geometry.drawRange;
  36733. //
  36734. this._nodes.updateBefore( renderObject );
  36735. //
  36736. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  36737. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  36738. //
  36739. this._nodes.updateForRender( renderObject );
  36740. this._geometries.updateForRender( renderObject );
  36741. this._bindings.updateForRender( renderObject );
  36742. this._pipelines.updateForRender( renderObject );
  36743. //
  36744. if ( this._currentRenderBundle !== null && this._currentRenderBundle.needsUpdate === true ) {
  36745. const renderObjectData = this.backend.get( renderObject );
  36746. renderObjectData.bundleEncoder = undefined;
  36747. renderObjectData.lastPipelineGPU = undefined;
  36748. }
  36749. this.backend.draw( renderObject, this.info );
  36750. if ( this._currentRenderBundle !== null ) {
  36751. const renderContextData = this.backend.get( this._currentRenderContext );
  36752. renderContextData.renderObjects.push( renderObject );
  36753. }
  36754. this._nodes.updateAfter( renderObject );
  36755. }
  36756. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  36757. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  36758. //
  36759. this._nodes.updateBefore( renderObject );
  36760. //
  36761. this._nodes.updateForRender( renderObject );
  36762. this._geometries.updateForRender( renderObject );
  36763. this._bindings.updateForRender( renderObject );
  36764. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36765. this._nodes.updateAfter( renderObject );
  36766. }
  36767. get compute() {
  36768. return this.computeAsync;
  36769. }
  36770. get compile() {
  36771. return this.compileAsync;
  36772. }
  36773. }
  36774. class Binding {
  36775. constructor( name = '' ) {
  36776. this.name = name;
  36777. this.visibility = 0;
  36778. }
  36779. setVisibility( visibility ) {
  36780. this.visibility |= visibility;
  36781. }
  36782. clone() {
  36783. return Object.assign( new this.constructor(), this );
  36784. }
  36785. }
  36786. function getFloatLength( floatLength ) {
  36787. // ensure chunk size alignment (STD140 layout)
  36788. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36789. }
  36790. class Buffer extends Binding {
  36791. constructor( name, buffer = null ) {
  36792. super( name );
  36793. this.isBuffer = true;
  36794. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36795. this._buffer = buffer;
  36796. }
  36797. get byteLength() {
  36798. return getFloatLength( this._buffer.byteLength );
  36799. }
  36800. get buffer() {
  36801. return this._buffer;
  36802. }
  36803. update() {
  36804. return true;
  36805. }
  36806. }
  36807. class UniformBuffer extends Buffer {
  36808. constructor( name, buffer = null ) {
  36809. super( name, buffer );
  36810. this.isUniformBuffer = true;
  36811. }
  36812. }
  36813. let _id$2 = 0;
  36814. class NodeUniformBuffer extends UniformBuffer {
  36815. constructor( nodeUniform, groupNode ) {
  36816. super( 'UniformBuffer_' + _id$2 ++, nodeUniform ? nodeUniform.value : null );
  36817. this.nodeUniform = nodeUniform;
  36818. this.groupNode = groupNode;
  36819. }
  36820. get buffer() {
  36821. return this.nodeUniform.value;
  36822. }
  36823. }
  36824. class UniformsGroup extends UniformBuffer {
  36825. constructor( name ) {
  36826. super( name );
  36827. this.isUniformsGroup = true;
  36828. this._values = null;
  36829. // the order of uniforms in this array must match the order of uniforms in the shader
  36830. this.uniforms = [];
  36831. }
  36832. addUniform( uniform ) {
  36833. this.uniforms.push( uniform );
  36834. return this;
  36835. }
  36836. removeUniform( uniform ) {
  36837. const index = this.uniforms.indexOf( uniform );
  36838. if ( index !== - 1 ) {
  36839. this.uniforms.splice( index, 1 );
  36840. }
  36841. return this;
  36842. }
  36843. get values() {
  36844. if ( this._values === null ) {
  36845. this._values = Array.from( this.buffer );
  36846. }
  36847. return this._values;
  36848. }
  36849. get buffer() {
  36850. let buffer = this._buffer;
  36851. if ( buffer === null ) {
  36852. const byteLength = this.byteLength;
  36853. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36854. this._buffer = buffer;
  36855. }
  36856. return buffer;
  36857. }
  36858. get byteLength() {
  36859. let offset = 0; // global buffer offset in bytes
  36860. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36861. const uniform = this.uniforms[ i ];
  36862. const { boundary, itemSize } = uniform;
  36863. // offset within a single chunk in bytes
  36864. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36865. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36866. // conformance tests
  36867. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36868. // check for chunk overflow
  36869. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36870. } else if ( chunkOffset % boundary !== 0 ) {
  36871. // check for correct alignment
  36872. offset += ( chunkOffset % boundary );
  36873. }
  36874. uniform.offset = ( offset / this.bytesPerElement );
  36875. offset += ( itemSize * this.bytesPerElement );
  36876. }
  36877. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36878. }
  36879. update() {
  36880. let updated = false;
  36881. for ( const uniform of this.uniforms ) {
  36882. if ( this.updateByType( uniform ) === true ) {
  36883. updated = true;
  36884. }
  36885. }
  36886. return updated;
  36887. }
  36888. updateByType( uniform ) {
  36889. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36890. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36891. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36892. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36893. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36894. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36895. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36896. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36897. }
  36898. updateNumber( uniform ) {
  36899. let updated = false;
  36900. const a = this.values;
  36901. const v = uniform.getValue();
  36902. const offset = uniform.offset;
  36903. if ( a[ offset ] !== v ) {
  36904. const b = this.buffer;
  36905. b[ offset ] = a[ offset ] = v;
  36906. updated = true;
  36907. }
  36908. return updated;
  36909. }
  36910. updateVector2( uniform ) {
  36911. let updated = false;
  36912. const a = this.values;
  36913. const v = uniform.getValue();
  36914. const offset = uniform.offset;
  36915. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36916. const b = this.buffer;
  36917. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36918. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36919. updated = true;
  36920. }
  36921. return updated;
  36922. }
  36923. updateVector3( uniform ) {
  36924. let updated = false;
  36925. const a = this.values;
  36926. const v = uniform.getValue();
  36927. const offset = uniform.offset;
  36928. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36929. const b = this.buffer;
  36930. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36931. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36932. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36933. updated = true;
  36934. }
  36935. return updated;
  36936. }
  36937. updateVector4( uniform ) {
  36938. let updated = false;
  36939. const a = this.values;
  36940. const v = uniform.getValue();
  36941. const offset = uniform.offset;
  36942. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36943. const b = this.buffer;
  36944. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36945. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36946. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36947. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36948. updated = true;
  36949. }
  36950. return updated;
  36951. }
  36952. updateColor( uniform ) {
  36953. let updated = false;
  36954. const a = this.values;
  36955. const c = uniform.getValue();
  36956. const offset = uniform.offset;
  36957. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36958. const b = this.buffer;
  36959. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36960. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36961. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36962. updated = true;
  36963. }
  36964. return updated;
  36965. }
  36966. updateMatrix3( uniform ) {
  36967. let updated = false;
  36968. const a = this.values;
  36969. const e = uniform.getValue().elements;
  36970. const offset = uniform.offset;
  36971. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36972. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36973. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36974. const b = this.buffer;
  36975. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36976. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36977. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36978. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36979. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36980. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36981. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36982. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36983. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36984. updated = true;
  36985. }
  36986. return updated;
  36987. }
  36988. updateMatrix4( uniform ) {
  36989. let updated = false;
  36990. const a = this.values;
  36991. const e = uniform.getValue().elements;
  36992. const offset = uniform.offset;
  36993. if ( arraysEqual( a, e, offset ) === false ) {
  36994. const b = this.buffer;
  36995. b.set( e, offset );
  36996. setArray( a, e, offset );
  36997. updated = true;
  36998. }
  36999. return updated;
  37000. }
  37001. }
  37002. function setArray( a, b, offset ) {
  37003. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37004. a[ offset + i ] = b[ i ];
  37005. }
  37006. }
  37007. function arraysEqual( a, b, offset ) {
  37008. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37009. if ( a[ offset + i ] !== b[ i ] ) return false;
  37010. }
  37011. return true;
  37012. }
  37013. let id$1 = 0;
  37014. class NodeUniformsGroup extends UniformsGroup {
  37015. constructor( name, groupNode ) {
  37016. super( name );
  37017. this.id = id$1 ++;
  37018. this.groupNode = groupNode;
  37019. this.isNodeUniformsGroup = true;
  37020. }
  37021. getNodes() {
  37022. const nodes = [];
  37023. for ( const uniform of this.uniforms ) {
  37024. const node = uniform.nodeUniform.node;
  37025. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  37026. nodes.push( node );
  37027. }
  37028. return nodes;
  37029. }
  37030. }
  37031. let id = 0;
  37032. class SampledTexture extends Binding {
  37033. constructor( name, texture ) {
  37034. super( name );
  37035. this.id = id ++;
  37036. this.texture = texture;
  37037. this.version = texture ? texture.version : 0;
  37038. this.store = false;
  37039. this.isSampledTexture = true;
  37040. }
  37041. get needsBindingsUpdate() {
  37042. const { texture, version } = this;
  37043. return texture.isVideoTexture ? true : version !== texture.version; // @TODO: version === 0 && texture.version > 0 ( add it just to External Textures like PNG,JPG )
  37044. }
  37045. update() {
  37046. const { texture, version } = this;
  37047. if ( version !== texture.version ) {
  37048. this.version = texture.version;
  37049. return true;
  37050. }
  37051. return false;
  37052. }
  37053. }
  37054. class NodeSampledTexture extends SampledTexture {
  37055. constructor( name, textureNode, groupNode, access = null ) {
  37056. super( name, textureNode ? textureNode.value : null );
  37057. this.textureNode = textureNode;
  37058. this.groupNode = groupNode;
  37059. this.access = access;
  37060. }
  37061. get needsBindingsUpdate() {
  37062. return this.textureNode.value !== this.texture || super.needsBindingsUpdate;
  37063. }
  37064. update() {
  37065. const { textureNode } = this;
  37066. if ( this.texture !== textureNode.value ) {
  37067. this.texture = textureNode.value;
  37068. return true;
  37069. }
  37070. return super.update();
  37071. }
  37072. }
  37073. class NodeSampledCubeTexture extends NodeSampledTexture {
  37074. constructor( name, textureNode, groupNode, access ) {
  37075. super( name, textureNode, groupNode, access );
  37076. this.isSampledCubeTexture = true;
  37077. }
  37078. }
  37079. class NodeSampledTexture3D extends NodeSampledTexture {
  37080. constructor( name, textureNode, groupNode, access ) {
  37081. super( name, textureNode, groupNode, access );
  37082. this.isSampledTexture3D = true;
  37083. }
  37084. }
  37085. const glslMethods = {
  37086. [ MathNode.ATAN2 ]: 'atan',
  37087. textureDimensions: 'textureSize',
  37088. equals: 'equal'
  37089. };
  37090. const precisionLib = {
  37091. low: 'lowp',
  37092. medium: 'mediump',
  37093. high: 'highp'
  37094. };
  37095. const supports$1 = {
  37096. swizzleAssign: true,
  37097. storageBuffer: false
  37098. };
  37099. const defaultPrecisions = `
  37100. precision highp float;
  37101. precision highp int;
  37102. precision highp sampler2D;
  37103. precision highp sampler3D;
  37104. precision highp samplerCube;
  37105. precision highp sampler2DArray;
  37106. precision highp usampler2D;
  37107. precision highp usampler3D;
  37108. precision highp usamplerCube;
  37109. precision highp usampler2DArray;
  37110. precision highp isampler2D;
  37111. precision highp isampler3D;
  37112. precision highp isamplerCube;
  37113. precision highp isampler2DArray;
  37114. precision lowp sampler2DShadow;
  37115. `;
  37116. class GLSLNodeBuilder extends NodeBuilder {
  37117. constructor( object, renderer ) {
  37118. super( object, renderer, new GLSLNodeParser() );
  37119. this.uniformGroups = {};
  37120. this.transforms = [];
  37121. this.instanceBindGroups = false;
  37122. }
  37123. getMethod( method ) {
  37124. return glslMethods[ method ] || method;
  37125. }
  37126. getOutputStructName() {
  37127. return '';
  37128. }
  37129. buildFunctionCode( shaderNode ) {
  37130. const layout = shaderNode.layout;
  37131. const flowData = this.flowShaderNode( shaderNode );
  37132. const parameters = [];
  37133. for ( const input of layout.inputs ) {
  37134. parameters.push( this.getType( input.type ) + ' ' + input.name );
  37135. }
  37136. //
  37137. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  37138. ${ flowData.vars }
  37139. ${ flowData.code }
  37140. return ${ flowData.result };
  37141. }`;
  37142. //
  37143. return code;
  37144. }
  37145. setupPBO( storageBufferNode ) {
  37146. const attribute = storageBufferNode.value;
  37147. if ( attribute.pbo === undefined ) {
  37148. const originalArray = attribute.array;
  37149. const numElements = attribute.count * attribute.itemSize;
  37150. const { itemSize } = attribute;
  37151. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  37152. let format = isInteger ? RedIntegerFormat : RedFormat;
  37153. if ( itemSize === 2 ) {
  37154. format = isInteger ? RGIntegerFormat : RGFormat;
  37155. } else if ( itemSize === 3 ) {
  37156. format = isInteger ? RGBIntegerFormat : RGBFormat;
  37157. } else if ( itemSize === 4 ) {
  37158. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  37159. }
  37160. const typeMap = {
  37161. Float32Array: FloatType,
  37162. Uint8Array: UnsignedByteType,
  37163. Uint16Array: UnsignedShortType,
  37164. Uint32Array: UnsignedIntType,
  37165. Int8Array: ByteType,
  37166. Int16Array: ShortType,
  37167. Int32Array: IntType,
  37168. Uint8ClampedArray: UnsignedByteType,
  37169. };
  37170. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  37171. let height = Math.ceil( ( numElements / itemSize ) / width );
  37172. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  37173. const newSize = width * height * itemSize;
  37174. const newArray = new originalArray.constructor( newSize );
  37175. newArray.set( originalArray, 0 );
  37176. attribute.array = newArray;
  37177. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  37178. pboTexture.needsUpdate = true;
  37179. pboTexture.isPBOTexture = true;
  37180. const pbo = new TextureNode( pboTexture, null, null );
  37181. pbo.setPrecision( 'high' );
  37182. attribute.pboNode = pbo;
  37183. attribute.pbo = pbo.value;
  37184. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37185. }
  37186. }
  37187. getPropertyName( node, shaderStage = this.shaderStage ) {
  37188. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  37189. return shaderStage.charAt( 0 ) + '_' + node.name;
  37190. }
  37191. return super.getPropertyName( node, shaderStage );
  37192. }
  37193. generatePBO( storageArrayElementNode ) {
  37194. const { node, indexNode } = storageArrayElementNode;
  37195. const attribute = node.value;
  37196. if ( this.renderer.backend.has( attribute ) ) {
  37197. const attributeData = this.renderer.backend.get( attribute );
  37198. attributeData.pbo = attribute.pbo;
  37199. }
  37200. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37201. const textureName = this.getPropertyName( nodeUniform );
  37202. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  37203. const indexSnippet = indexNode.build( this, 'uint' );
  37204. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  37205. let propertyName = elementNodeData.propertyName;
  37206. if ( propertyName === undefined ) {
  37207. // property element
  37208. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  37209. propertyName = this.getPropertyName( nodeVar );
  37210. // property size
  37211. const bufferNodeData = this.getDataFromNode( node );
  37212. let propertySizeName = bufferNodeData.propertySizeName;
  37213. if ( propertySizeName === undefined ) {
  37214. propertySizeName = propertyName + 'Size';
  37215. this.getVarFromNode( node, propertySizeName, 'uint' );
  37216. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  37217. bufferNodeData.propertySizeName = propertySizeName;
  37218. }
  37219. //
  37220. const { itemSize } = attribute;
  37221. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  37222. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  37223. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  37224. //
  37225. let prefix = 'vec4';
  37226. if ( attribute.pbo.type === UnsignedIntType ) {
  37227. prefix = 'uvec4';
  37228. } else if ( attribute.pbo.type === IntType ) {
  37229. prefix = 'ivec4';
  37230. }
  37231. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  37232. elementNodeData.propertyName = propertyName;
  37233. }
  37234. return propertyName;
  37235. }
  37236. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  37237. if ( depthSnippet ) {
  37238. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  37239. } else {
  37240. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  37241. }
  37242. }
  37243. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  37244. if ( texture.isDepthTexture ) {
  37245. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  37246. } else {
  37247. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  37248. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  37249. }
  37250. }
  37251. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  37252. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  37253. }
  37254. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  37255. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  37256. }
  37257. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  37258. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  37259. }
  37260. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  37261. if ( shaderStage === 'fragment' ) {
  37262. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  37263. } else {
  37264. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  37265. }
  37266. }
  37267. getVars( shaderStage ) {
  37268. const snippets = [];
  37269. const vars = this.vars[ shaderStage ];
  37270. if ( vars !== undefined ) {
  37271. for ( const variable of vars ) {
  37272. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  37273. }
  37274. }
  37275. return snippets.join( '\n\t' );
  37276. }
  37277. getUniforms( shaderStage ) {
  37278. const uniforms = this.uniforms[ shaderStage ];
  37279. const bindingSnippets = [];
  37280. const uniformGroups = {};
  37281. for ( const uniform of uniforms ) {
  37282. let snippet = null;
  37283. let group = false;
  37284. if ( uniform.type === 'texture' ) {
  37285. const texture = uniform.node.value;
  37286. let typePrefix = '';
  37287. if ( texture.isDataTexture === true ) {
  37288. if ( texture.type === UnsignedIntType ) {
  37289. typePrefix = 'u';
  37290. } else if ( texture.type === IntType ) {
  37291. typePrefix = 'i';
  37292. }
  37293. }
  37294. if ( texture.compareFunction ) {
  37295. snippet = `sampler2DShadow ${ uniform.name };`;
  37296. } else if ( texture.isDataArrayTexture === true ) {
  37297. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  37298. } else {
  37299. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  37300. }
  37301. } else if ( uniform.type === 'cubeTexture' ) {
  37302. snippet = `samplerCube ${ uniform.name };`;
  37303. } else if ( uniform.type === 'texture3D' ) {
  37304. snippet = `sampler3D ${ uniform.name };`;
  37305. } else if ( uniform.type === 'buffer' ) {
  37306. const bufferNode = uniform.node;
  37307. const bufferType = this.getType( bufferNode.bufferType );
  37308. const bufferCount = bufferNode.bufferCount;
  37309. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  37310. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  37311. } else {
  37312. const vectorType = this.getVectorType( uniform.type );
  37313. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  37314. group = true;
  37315. }
  37316. const precision = uniform.node.precision;
  37317. if ( precision !== null ) {
  37318. snippet = precisionLib[ precision ] + ' ' + snippet;
  37319. }
  37320. if ( group ) {
  37321. snippet = '\t' + snippet;
  37322. const groupName = uniform.groupNode.name;
  37323. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  37324. groupSnippets.push( snippet );
  37325. } else {
  37326. snippet = 'uniform ' + snippet;
  37327. bindingSnippets.push( snippet );
  37328. }
  37329. }
  37330. let output = '';
  37331. for ( const name in uniformGroups ) {
  37332. const groupSnippets = uniformGroups[ name ];
  37333. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37334. }
  37335. output += bindingSnippets.join( '\n' );
  37336. return output;
  37337. }
  37338. getTypeFromAttribute( attribute ) {
  37339. let nodeType = super.getTypeFromAttribute( attribute );
  37340. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37341. let dataAttribute = attribute;
  37342. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37343. const array = dataAttribute.array;
  37344. if ( ( array instanceof Uint32Array || array instanceof Int32Array || array instanceof Uint16Array || array instanceof Int16Array ) === false ) {
  37345. nodeType = nodeType.slice( 1 );
  37346. }
  37347. }
  37348. return nodeType;
  37349. }
  37350. getAttributes( shaderStage ) {
  37351. let snippet = '';
  37352. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37353. const attributes = this.getAttributesArray();
  37354. let location = 0;
  37355. for ( const attribute of attributes ) {
  37356. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37357. }
  37358. }
  37359. return snippet;
  37360. }
  37361. getStructMembers( struct ) {
  37362. const snippets = [];
  37363. const members = struct.getMemberTypes();
  37364. for ( let i = 0; i < members.length; i ++ ) {
  37365. const member = members[ i ];
  37366. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  37367. }
  37368. return snippets.join( '\n' );
  37369. }
  37370. getStructs( shaderStage ) {
  37371. const snippets = [];
  37372. const structs = this.structs[ shaderStage ];
  37373. if ( structs.length === 0 ) {
  37374. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37375. }
  37376. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37377. const struct = structs[ index ];
  37378. let snippet = '\n';
  37379. snippet += this.getStructMembers( struct );
  37380. snippet += '\n';
  37381. snippets.push( snippet );
  37382. }
  37383. return snippets.join( '\n\n' );
  37384. }
  37385. getVaryings( shaderStage ) {
  37386. let snippet = '';
  37387. const varyings = this.varyings;
  37388. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37389. for ( const varying of varyings ) {
  37390. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37391. const type = varying.type;
  37392. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37393. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37394. }
  37395. } else if ( shaderStage === 'fragment' ) {
  37396. for ( const varying of varyings ) {
  37397. if ( varying.needsInterpolation ) {
  37398. const type = varying.type;
  37399. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37400. snippet += `${flat}in ${type} ${varying.name};\n`;
  37401. }
  37402. }
  37403. }
  37404. return snippet;
  37405. }
  37406. getVertexIndex() {
  37407. return 'uint( gl_VertexID )';
  37408. }
  37409. getInstanceIndex() {
  37410. return 'uint( gl_InstanceID )';
  37411. }
  37412. getDrawIndex() {
  37413. const extensions = this.renderer.backend.extensions;
  37414. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37415. return 'uint( gl_DrawID )';
  37416. }
  37417. return null;
  37418. }
  37419. getFrontFacing() {
  37420. return 'gl_FrontFacing';
  37421. }
  37422. getFragCoord() {
  37423. return 'gl_FragCoord';
  37424. }
  37425. getFragDepth() {
  37426. return 'gl_FragDepth';
  37427. }
  37428. getExtensions( shaderStage ) {
  37429. let extensions = '';
  37430. if ( shaderStage === 'vertex' ) {
  37431. const ext = this.renderer.backend.extensions;
  37432. const isBatchedMesh = this.object.isBatchedMesh;
  37433. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37434. extensions += '#extension GL_ANGLE_multi_draw : require\n';
  37435. }
  37436. }
  37437. return extensions;
  37438. }
  37439. isAvailable( name ) {
  37440. let result = supports$1[ name ];
  37441. if ( result === undefined ) {
  37442. if ( name === 'float32Filterable' ) {
  37443. const extensions = this.renderer.backend.extensions;
  37444. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  37445. extensions.get( 'OES_texture_float_linear' );
  37446. result = true;
  37447. } else {
  37448. result = false;
  37449. }
  37450. }
  37451. supports$1[ name ] = result;
  37452. }
  37453. return result;
  37454. }
  37455. isFlipY() {
  37456. return true;
  37457. }
  37458. registerTransform( varyingName, attributeNode ) {
  37459. this.transforms.push( { varyingName, attributeNode } );
  37460. }
  37461. getTransforms( /* shaderStage */ ) {
  37462. const transforms = this.transforms;
  37463. let snippet = '';
  37464. for ( let i = 0; i < transforms.length; i ++ ) {
  37465. const transform = transforms[ i ];
  37466. const attributeName = this.getPropertyName( transform.attributeNode );
  37467. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37468. }
  37469. return snippet;
  37470. }
  37471. _getGLSLUniformStruct( name, vars ) {
  37472. return `
  37473. layout( std140 ) uniform ${name} {
  37474. ${vars}
  37475. };`;
  37476. }
  37477. _getGLSLVertexCode( shaderData ) {
  37478. return `#version 300 es
  37479. // extensions
  37480. ${shaderData.extensions}
  37481. // precision
  37482. ${ defaultPrecisions }
  37483. // uniforms
  37484. ${shaderData.uniforms}
  37485. // varyings
  37486. ${shaderData.varyings}
  37487. // attributes
  37488. ${shaderData.attributes}
  37489. // codes
  37490. ${shaderData.codes}
  37491. void main() {
  37492. // vars
  37493. ${shaderData.vars}
  37494. // transforms
  37495. ${shaderData.transforms}
  37496. // flow
  37497. ${shaderData.flow}
  37498. gl_PointSize = 1.0;
  37499. }
  37500. `;
  37501. }
  37502. _getGLSLFragmentCode( shaderData ) {
  37503. return `#version 300 es
  37504. ${ this.getSignature() }
  37505. // precision
  37506. ${ defaultPrecisions }
  37507. // uniforms
  37508. ${shaderData.uniforms}
  37509. // varyings
  37510. ${shaderData.varyings}
  37511. // codes
  37512. ${shaderData.codes}
  37513. ${shaderData.structs}
  37514. void main() {
  37515. // vars
  37516. ${shaderData.vars}
  37517. // flow
  37518. ${shaderData.flow}
  37519. }
  37520. `;
  37521. }
  37522. buildCode() {
  37523. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37524. for ( const shaderStage in shadersData ) {
  37525. let flow = '// code\n\n';
  37526. flow += this.flowCode[ shaderStage ];
  37527. const flowNodes = this.flowNodes[ shaderStage ];
  37528. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37529. for ( const node of flowNodes ) {
  37530. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37531. const slotName = node.name;
  37532. if ( slotName ) {
  37533. if ( flow.length > 0 ) flow += '\n';
  37534. flow += `\t// flow -> ${ slotName }\n\t`;
  37535. }
  37536. flow += `${ flowSlotData.code }\n\t`;
  37537. if ( node === mainNode && shaderStage !== 'compute' ) {
  37538. flow += '// result\n\t';
  37539. if ( shaderStage === 'vertex' ) {
  37540. flow += 'gl_Position = ';
  37541. flow += `${ flowSlotData.result };`;
  37542. } else if ( shaderStage === 'fragment' ) {
  37543. if ( ! node.outputNode.isOutputStructNode ) {
  37544. flow += 'fragColor = ';
  37545. flow += `${ flowSlotData.result };`;
  37546. }
  37547. }
  37548. }
  37549. }
  37550. const stageData = shadersData[ shaderStage ];
  37551. stageData.extensions = this.getExtensions( shaderStage );
  37552. stageData.uniforms = this.getUniforms( shaderStage );
  37553. stageData.attributes = this.getAttributes( shaderStage );
  37554. stageData.varyings = this.getVaryings( shaderStage );
  37555. stageData.vars = this.getVars( shaderStage );
  37556. stageData.structs = this.getStructs( shaderStage );
  37557. stageData.codes = this.getCodes( shaderStage );
  37558. stageData.transforms = this.getTransforms( shaderStage );
  37559. stageData.flow = flow;
  37560. }
  37561. if ( this.material !== null ) {
  37562. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37563. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37564. } else {
  37565. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37566. }
  37567. }
  37568. getUniformFromNode( node, type, shaderStage, name = null ) {
  37569. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37570. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37571. let uniformGPU = nodeData.uniformGPU;
  37572. if ( uniformGPU === undefined ) {
  37573. const group = node.groupNode;
  37574. const groupName = group.name;
  37575. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37576. if ( type === 'texture' ) {
  37577. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37578. bindings.push( uniformGPU );
  37579. } else if ( type === 'cubeTexture' ) {
  37580. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37581. bindings.push( uniformGPU );
  37582. } else if ( type === 'texture3D' ) {
  37583. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37584. bindings.push( uniformGPU );
  37585. } else if ( type === 'buffer' ) {
  37586. node.name = `NodeBuffer_${ node.id }`;
  37587. uniformNode.name = `buffer${ node.id }`;
  37588. const buffer = new NodeUniformBuffer( node, group );
  37589. buffer.name = node.name;
  37590. bindings.push( buffer );
  37591. uniformGPU = buffer;
  37592. } else {
  37593. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37594. let uniformsGroup = uniformsStage[ groupName ];
  37595. if ( uniformsGroup === undefined ) {
  37596. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37597. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37598. uniformsStage[ groupName ] = uniformsGroup;
  37599. bindings.push( uniformsGroup );
  37600. }
  37601. uniformGPU = this.getNodeUniform( uniformNode, type );
  37602. uniformsGroup.addUniform( uniformGPU );
  37603. }
  37604. nodeData.uniformGPU = uniformGPU;
  37605. }
  37606. return uniformNode;
  37607. }
  37608. }
  37609. let vector2 = null;
  37610. let vector4 = null;
  37611. let color4 = null;
  37612. class Backend {
  37613. constructor( parameters = {} ) {
  37614. this.parameters = Object.assign( {}, parameters );
  37615. this.data = new WeakMap();
  37616. this.renderer = null;
  37617. this.domElement = null;
  37618. }
  37619. async init( renderer ) {
  37620. this.renderer = renderer;
  37621. }
  37622. // render context
  37623. begin( /*renderContext*/ ) { }
  37624. finish( /*renderContext*/ ) { }
  37625. // render object
  37626. draw( /*renderObject, info*/ ) { }
  37627. // program
  37628. createProgram( /*program*/ ) { }
  37629. destroyProgram( /*program*/ ) { }
  37630. // bindings
  37631. createBindings( /*renderObject*/ ) { }
  37632. updateBindings( /*renderObject*/ ) { }
  37633. // pipeline
  37634. createRenderPipeline( /*renderObject*/ ) { }
  37635. createComputePipeline( /*computeNode, pipeline*/ ) { }
  37636. destroyPipeline( /*pipeline*/ ) { }
  37637. // cache key
  37638. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  37639. getRenderCacheKey( /*renderObject*/ ) { } // return String
  37640. // node builder
  37641. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  37642. // textures
  37643. createSampler( /*texture*/ ) { }
  37644. createDefaultTexture( /*texture*/ ) { }
  37645. createTexture( /*texture*/ ) { }
  37646. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  37647. // attributes
  37648. createAttribute( /*attribute*/ ) { }
  37649. createIndexAttribute( /*attribute*/ ) { }
  37650. updateAttribute( /*attribute*/ ) { }
  37651. destroyAttribute( /*attribute*/ ) { }
  37652. // canvas
  37653. getContext() { }
  37654. updateSize() { }
  37655. // utils
  37656. resolveTimestampAsync( /*renderContext, type*/ ) { }
  37657. hasFeatureAsync( /*name*/ ) { } // return Boolean
  37658. hasFeature( /*name*/ ) { } // return Boolean
  37659. getInstanceCount( renderObject ) {
  37660. const { object, geometry } = renderObject;
  37661. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  37662. }
  37663. getDrawingBufferSize() {
  37664. vector2 = vector2 || new Vector2();
  37665. return this.renderer.getDrawingBufferSize( vector2 );
  37666. }
  37667. getScissor() {
  37668. vector4 = vector4 || new Vector4();
  37669. return this.renderer.getScissor( vector4 );
  37670. }
  37671. setScissorTest( /*boolean*/ ) { }
  37672. getClearColor() {
  37673. const renderer = this.renderer;
  37674. color4 = color4 || new Color4();
  37675. renderer.getClearColor( color4 );
  37676. color4.getRGB( color4, this.renderer.currentColorSpace );
  37677. return color4;
  37678. }
  37679. getDomElement() {
  37680. let domElement = this.domElement;
  37681. if ( domElement === null ) {
  37682. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  37683. // OffscreenCanvas does not have setAttribute, see #22811
  37684. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  37685. this.domElement = domElement;
  37686. }
  37687. return domElement;
  37688. }
  37689. // resource properties
  37690. set( object, value ) {
  37691. this.data.set( object, value );
  37692. }
  37693. get( object ) {
  37694. let map = this.data.get( object );
  37695. if ( map === undefined ) {
  37696. map = {};
  37697. this.data.set( object, map );
  37698. }
  37699. return map;
  37700. }
  37701. has( object ) {
  37702. return this.data.has( object );
  37703. }
  37704. delete( object ) {
  37705. this.data.delete( object );
  37706. }
  37707. }
  37708. let _id$1 = 0;
  37709. class DualAttributeData {
  37710. constructor( attributeData, dualBuffer ) {
  37711. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  37712. this.type = attributeData.type;
  37713. this.bufferType = attributeData.bufferType;
  37714. this.pbo = attributeData.pbo;
  37715. this.byteLength = attributeData.byteLength;
  37716. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  37717. this.version = attributeData.version;
  37718. this.isInteger = attributeData.isInteger;
  37719. this.activeBufferIndex = 0;
  37720. this.baseId = attributeData.id;
  37721. }
  37722. get id() {
  37723. return `${ this.baseId }|${ this.activeBufferIndex }`;
  37724. }
  37725. get bufferGPU() {
  37726. return this.buffers[ this.activeBufferIndex ];
  37727. }
  37728. get transformBuffer() {
  37729. return this.buffers[ this.activeBufferIndex ^ 1 ];
  37730. }
  37731. switchBuffers() {
  37732. this.activeBufferIndex ^= 1;
  37733. }
  37734. }
  37735. class WebGLAttributeUtils {
  37736. constructor( backend ) {
  37737. this.backend = backend;
  37738. }
  37739. createAttribute( attribute, bufferType ) {
  37740. const backend = this.backend;
  37741. const { gl } = backend;
  37742. const array = attribute.array;
  37743. const usage = attribute.usage || gl.STATIC_DRAW;
  37744. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37745. const bufferData = backend.get( bufferAttribute );
  37746. let bufferGPU = bufferData.bufferGPU;
  37747. if ( bufferGPU === undefined ) {
  37748. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  37749. bufferData.bufferGPU = bufferGPU;
  37750. bufferData.bufferType = bufferType;
  37751. bufferData.version = bufferAttribute.version;
  37752. }
  37753. //attribute.onUploadCallback();
  37754. let type;
  37755. if ( array instanceof Float32Array ) {
  37756. type = gl.FLOAT;
  37757. } else if ( array instanceof Uint16Array ) {
  37758. if ( attribute.isFloat16BufferAttribute ) {
  37759. type = gl.HALF_FLOAT;
  37760. } else {
  37761. type = gl.UNSIGNED_SHORT;
  37762. }
  37763. } else if ( array instanceof Int16Array ) {
  37764. type = gl.SHORT;
  37765. } else if ( array instanceof Uint32Array ) {
  37766. type = gl.UNSIGNED_INT;
  37767. } else if ( array instanceof Int32Array ) {
  37768. type = gl.INT;
  37769. } else if ( array instanceof Int8Array ) {
  37770. type = gl.BYTE;
  37771. } else if ( array instanceof Uint8Array ) {
  37772. type = gl.UNSIGNED_BYTE;
  37773. } else if ( array instanceof Uint8ClampedArray ) {
  37774. type = gl.UNSIGNED_BYTE;
  37775. } else {
  37776. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  37777. }
  37778. let attributeData = {
  37779. bufferGPU,
  37780. bufferType,
  37781. type,
  37782. byteLength: array.byteLength,
  37783. bytesPerElement: array.BYTES_PER_ELEMENT,
  37784. version: attribute.version,
  37785. pbo: attribute.pbo,
  37786. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || type === gl.UNSIGNED_SHORT || attribute.gpuType === IntType,
  37787. id: _id$1 ++
  37788. };
  37789. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  37790. // create buffer for tranform feedback use
  37791. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  37792. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  37793. }
  37794. backend.set( attribute, attributeData );
  37795. }
  37796. updateAttribute( attribute ) {
  37797. const backend = this.backend;
  37798. const { gl } = backend;
  37799. const array = attribute.array;
  37800. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37801. const bufferData = backend.get( bufferAttribute );
  37802. const bufferType = bufferData.bufferType;
  37803. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  37804. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  37805. if ( updateRanges.length === 0 ) {
  37806. // Not using update ranges
  37807. gl.bufferSubData( bufferType, 0, array );
  37808. } else {
  37809. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  37810. const range = updateRanges[ i ];
  37811. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  37812. array, range.start, range.count );
  37813. }
  37814. bufferAttribute.clearUpdateRanges();
  37815. }
  37816. gl.bindBuffer( bufferType, null );
  37817. bufferData.version = bufferAttribute.version;
  37818. }
  37819. destroyAttribute( attribute ) {
  37820. const backend = this.backend;
  37821. const { gl } = backend;
  37822. if ( attribute.isInterleavedBufferAttribute ) {
  37823. backend.delete( attribute.data );
  37824. }
  37825. const attributeData = backend.get( attribute );
  37826. gl.deleteBuffer( attributeData.bufferGPU );
  37827. backend.delete( attribute );
  37828. }
  37829. async getArrayBufferAsync( attribute ) {
  37830. const backend = this.backend;
  37831. const { gl } = backend;
  37832. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37833. const { bufferGPU } = backend.get( bufferAttribute );
  37834. const array = attribute.array;
  37835. const byteLength = array.byteLength;
  37836. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  37837. const writeBuffer = gl.createBuffer();
  37838. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  37839. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  37840. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  37841. await backend.utils._clientWaitAsync();
  37842. const dstBuffer = new attribute.array.constructor( array.length );
  37843. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  37844. gl.deleteBuffer( writeBuffer );
  37845. return dstBuffer.buffer;
  37846. }
  37847. _createBuffer( gl, bufferType, array, usage ) {
  37848. const bufferGPU = gl.createBuffer();
  37849. gl.bindBuffer( bufferType, bufferGPU );
  37850. gl.bufferData( bufferType, array, usage );
  37851. gl.bindBuffer( bufferType, null );
  37852. return bufferGPU;
  37853. }
  37854. }
  37855. let initialized$1 = false, equationToGL, factorToGL;
  37856. class WebGLState {
  37857. constructor( backend ) {
  37858. this.backend = backend;
  37859. this.gl = this.backend.gl;
  37860. this.enabled = {};
  37861. this.currentFlipSided = null;
  37862. this.currentCullFace = null;
  37863. this.currentProgram = null;
  37864. this.currentBlendingEnabled = false;
  37865. this.currentBlending = null;
  37866. this.currentBlendSrc = null;
  37867. this.currentBlendDst = null;
  37868. this.currentBlendSrcAlpha = null;
  37869. this.currentBlendDstAlpha = null;
  37870. this.currentPremultipledAlpha = null;
  37871. this.currentPolygonOffsetFactor = null;
  37872. this.currentPolygonOffsetUnits = null;
  37873. this.currentColorMask = null;
  37874. this.currentDepthFunc = null;
  37875. this.currentDepthMask = null;
  37876. this.currentStencilFunc = null;
  37877. this.currentStencilRef = null;
  37878. this.currentStencilFuncMask = null;
  37879. this.currentStencilFail = null;
  37880. this.currentStencilZFail = null;
  37881. this.currentStencilZPass = null;
  37882. this.currentStencilMask = null;
  37883. this.currentLineWidth = null;
  37884. this.currentBoundFramebuffers = {};
  37885. this.currentDrawbuffers = new WeakMap();
  37886. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  37887. this.currentTextureSlot = null;
  37888. this.currentBoundTextures = {};
  37889. if ( initialized$1 === false ) {
  37890. this._init( this.gl );
  37891. initialized$1 = true;
  37892. }
  37893. }
  37894. _init( gl ) {
  37895. // Store only WebGL constants here.
  37896. equationToGL = {
  37897. [ AddEquation ]: gl.FUNC_ADD,
  37898. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  37899. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  37900. };
  37901. factorToGL = {
  37902. [ ZeroFactor ]: gl.ZERO,
  37903. [ OneFactor ]: gl.ONE,
  37904. [ SrcColorFactor ]: gl.SRC_COLOR,
  37905. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  37906. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  37907. [ DstColorFactor ]: gl.DST_COLOR,
  37908. [ DstAlphaFactor ]: gl.DST_ALPHA,
  37909. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  37910. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  37911. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  37912. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  37913. };
  37914. }
  37915. enable( id ) {
  37916. const { enabled } = this;
  37917. if ( enabled[ id ] !== true ) {
  37918. this.gl.enable( id );
  37919. enabled[ id ] = true;
  37920. }
  37921. }
  37922. disable( id ) {
  37923. const { enabled } = this;
  37924. if ( enabled[ id ] !== false ) {
  37925. this.gl.disable( id );
  37926. enabled[ id ] = false;
  37927. }
  37928. }
  37929. setFlipSided( flipSided ) {
  37930. if ( this.currentFlipSided !== flipSided ) {
  37931. const { gl } = this;
  37932. if ( flipSided ) {
  37933. gl.frontFace( gl.CW );
  37934. } else {
  37935. gl.frontFace( gl.CCW );
  37936. }
  37937. this.currentFlipSided = flipSided;
  37938. }
  37939. }
  37940. setCullFace( cullFace ) {
  37941. const { gl } = this;
  37942. if ( cullFace !== CullFaceNone ) {
  37943. this.enable( gl.CULL_FACE );
  37944. if ( cullFace !== this.currentCullFace ) {
  37945. if ( cullFace === CullFaceBack ) {
  37946. gl.cullFace( gl.BACK );
  37947. } else if ( cullFace === CullFaceFront ) {
  37948. gl.cullFace( gl.FRONT );
  37949. } else {
  37950. gl.cullFace( gl.FRONT_AND_BACK );
  37951. }
  37952. }
  37953. } else {
  37954. this.disable( gl.CULL_FACE );
  37955. }
  37956. this.currentCullFace = cullFace;
  37957. }
  37958. setLineWidth( width ) {
  37959. const { currentLineWidth, gl } = this;
  37960. if ( width !== currentLineWidth ) {
  37961. gl.lineWidth( width );
  37962. this.currentLineWidth = width;
  37963. }
  37964. }
  37965. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  37966. const { gl } = this;
  37967. if ( blending === NoBlending ) {
  37968. if ( this.currentBlendingEnabled === true ) {
  37969. this.disable( gl.BLEND );
  37970. this.currentBlendingEnabled = false;
  37971. }
  37972. return;
  37973. }
  37974. if ( this.currentBlendingEnabled === false ) {
  37975. this.enable( gl.BLEND );
  37976. this.currentBlendingEnabled = true;
  37977. }
  37978. if ( blending !== CustomBlending ) {
  37979. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  37980. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  37981. gl.blendEquation( gl.FUNC_ADD );
  37982. this.currentBlendEquation = AddEquation;
  37983. this.currentBlendEquationAlpha = AddEquation;
  37984. }
  37985. if ( premultipliedAlpha ) {
  37986. switch ( blending ) {
  37987. case NormalBlending:
  37988. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37989. break;
  37990. case AdditiveBlending:
  37991. gl.blendFunc( gl.ONE, gl.ONE );
  37992. break;
  37993. case SubtractiveBlending:
  37994. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37995. break;
  37996. case MultiplyBlending:
  37997. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  37998. break;
  37999. default:
  38000. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38001. break;
  38002. }
  38003. } else {
  38004. switch ( blending ) {
  38005. case NormalBlending:
  38006. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38007. break;
  38008. case AdditiveBlending:
  38009. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  38010. break;
  38011. case SubtractiveBlending:
  38012. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38013. break;
  38014. case MultiplyBlending:
  38015. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  38016. break;
  38017. default:
  38018. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38019. break;
  38020. }
  38021. }
  38022. this.currentBlendSrc = null;
  38023. this.currentBlendDst = null;
  38024. this.currentBlendSrcAlpha = null;
  38025. this.currentBlendDstAlpha = null;
  38026. this.currentBlending = blending;
  38027. this.currentPremultipledAlpha = premultipliedAlpha;
  38028. }
  38029. return;
  38030. }
  38031. // custom blending
  38032. blendEquationAlpha = blendEquationAlpha || blendEquation;
  38033. blendSrcAlpha = blendSrcAlpha || blendSrc;
  38034. blendDstAlpha = blendDstAlpha || blendDst;
  38035. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  38036. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  38037. this.currentBlendEquation = blendEquation;
  38038. this.currentBlendEquationAlpha = blendEquationAlpha;
  38039. }
  38040. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  38041. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  38042. this.currentBlendSrc = blendSrc;
  38043. this.currentBlendDst = blendDst;
  38044. this.currentBlendSrcAlpha = blendSrcAlpha;
  38045. this.currentBlendDstAlpha = blendDstAlpha;
  38046. }
  38047. this.currentBlending = blending;
  38048. this.currentPremultipledAlpha = false;
  38049. }
  38050. setColorMask( colorMask ) {
  38051. if ( this.currentColorMask !== colorMask ) {
  38052. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  38053. this.currentColorMask = colorMask;
  38054. }
  38055. }
  38056. setDepthTest( depthTest ) {
  38057. const { gl } = this;
  38058. if ( depthTest ) {
  38059. this.enable( gl.DEPTH_TEST );
  38060. } else {
  38061. this.disable( gl.DEPTH_TEST );
  38062. }
  38063. }
  38064. setDepthMask( depthMask ) {
  38065. if ( this.currentDepthMask !== depthMask ) {
  38066. this.gl.depthMask( depthMask );
  38067. this.currentDepthMask = depthMask;
  38068. }
  38069. }
  38070. setDepthFunc( depthFunc ) {
  38071. if ( this.currentDepthFunc !== depthFunc ) {
  38072. const { gl } = this;
  38073. switch ( depthFunc ) {
  38074. case NeverDepth:
  38075. gl.depthFunc( gl.NEVER );
  38076. break;
  38077. case AlwaysDepth:
  38078. gl.depthFunc( gl.ALWAYS );
  38079. break;
  38080. case LessDepth:
  38081. gl.depthFunc( gl.LESS );
  38082. break;
  38083. case LessEqualDepth:
  38084. gl.depthFunc( gl.LEQUAL );
  38085. break;
  38086. case EqualDepth:
  38087. gl.depthFunc( gl.EQUAL );
  38088. break;
  38089. case GreaterEqualDepth:
  38090. gl.depthFunc( gl.GEQUAL );
  38091. break;
  38092. case GreaterDepth:
  38093. gl.depthFunc( gl.GREATER );
  38094. break;
  38095. case NotEqualDepth:
  38096. gl.depthFunc( gl.NOTEQUAL );
  38097. break;
  38098. default:
  38099. gl.depthFunc( gl.LEQUAL );
  38100. }
  38101. this.currentDepthFunc = depthFunc;
  38102. }
  38103. }
  38104. setStencilTest( stencilTest ) {
  38105. const { gl } = this;
  38106. if ( stencilTest ) {
  38107. this.enable( gl.STENCIL_TEST );
  38108. } else {
  38109. this.disable( gl.STENCIL_TEST );
  38110. }
  38111. }
  38112. setStencilMask( stencilMask ) {
  38113. if ( this.currentStencilMask !== stencilMask ) {
  38114. this.gl.stencilMask( stencilMask );
  38115. this.currentStencilMask = stencilMask;
  38116. }
  38117. }
  38118. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  38119. if ( this.currentStencilFunc !== stencilFunc ||
  38120. this.currentStencilRef !== stencilRef ||
  38121. this.currentStencilFuncMask !== stencilMask ) {
  38122. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  38123. this.currentStencilFunc = stencilFunc;
  38124. this.currentStencilRef = stencilRef;
  38125. this.currentStencilFuncMask = stencilMask;
  38126. }
  38127. }
  38128. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  38129. if ( this.currentStencilFail !== stencilFail ||
  38130. this.currentStencilZFail !== stencilZFail ||
  38131. this.currentStencilZPass !== stencilZPass ) {
  38132. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  38133. this.currentStencilFail = stencilFail;
  38134. this.currentStencilZFail = stencilZFail;
  38135. this.currentStencilZPass = stencilZPass;
  38136. }
  38137. }
  38138. setMaterial( material, frontFaceCW ) {
  38139. const { gl } = this;
  38140. material.side === DoubleSide
  38141. ? this.disable( gl.CULL_FACE )
  38142. : this.enable( gl.CULL_FACE );
  38143. let flipSided = ( material.side === BackSide );
  38144. if ( frontFaceCW ) flipSided = ! flipSided;
  38145. this.setFlipSided( flipSided );
  38146. ( material.blending === NormalBlending && material.transparent === false )
  38147. ? this.setBlending( NoBlending )
  38148. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  38149. this.setDepthFunc( material.depthFunc );
  38150. this.setDepthTest( material.depthTest );
  38151. this.setDepthMask( material.depthWrite );
  38152. this.setColorMask( material.colorWrite );
  38153. const stencilWrite = material.stencilWrite;
  38154. this.setStencilTest( stencilWrite );
  38155. if ( stencilWrite ) {
  38156. this.setStencilMask( material.stencilWriteMask );
  38157. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  38158. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  38159. }
  38160. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  38161. material.alphaToCoverage === true
  38162. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  38163. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  38164. }
  38165. setPolygonOffset( polygonOffset, factor, units ) {
  38166. const { gl } = this;
  38167. if ( polygonOffset ) {
  38168. this.enable( gl.POLYGON_OFFSET_FILL );
  38169. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  38170. gl.polygonOffset( factor, units );
  38171. this.currentPolygonOffsetFactor = factor;
  38172. this.currentPolygonOffsetUnits = units;
  38173. }
  38174. } else {
  38175. this.disable( gl.POLYGON_OFFSET_FILL );
  38176. }
  38177. }
  38178. useProgram( program ) {
  38179. if ( this.currentProgram !== program ) {
  38180. this.gl.useProgram( program );
  38181. this.currentProgram = program;
  38182. return true;
  38183. }
  38184. return false;
  38185. }
  38186. // framebuffer
  38187. bindFramebuffer( target, framebuffer ) {
  38188. const { gl, currentBoundFramebuffers } = this;
  38189. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  38190. gl.bindFramebuffer( target, framebuffer );
  38191. currentBoundFramebuffers[ target ] = framebuffer;
  38192. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  38193. if ( target === gl.DRAW_FRAMEBUFFER ) {
  38194. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  38195. }
  38196. if ( target === gl.FRAMEBUFFER ) {
  38197. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  38198. }
  38199. return true;
  38200. }
  38201. return false;
  38202. }
  38203. drawBuffers( renderContext, framebuffer ) {
  38204. const { gl } = this;
  38205. let drawBuffers = [];
  38206. let needsUpdate = false;
  38207. if ( renderContext.textures !== null ) {
  38208. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  38209. if ( drawBuffers === undefined ) {
  38210. drawBuffers = [];
  38211. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  38212. }
  38213. const textures = renderContext.textures;
  38214. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  38215. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  38216. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  38217. }
  38218. drawBuffers.length = textures.length;
  38219. needsUpdate = true;
  38220. }
  38221. } else {
  38222. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  38223. drawBuffers[ 0 ] = gl.BACK;
  38224. needsUpdate = true;
  38225. }
  38226. }
  38227. if ( needsUpdate ) {
  38228. gl.drawBuffers( drawBuffers );
  38229. }
  38230. }
  38231. // texture
  38232. activeTexture( webglSlot ) {
  38233. const { gl, currentTextureSlot, maxTextures } = this;
  38234. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38235. if ( currentTextureSlot !== webglSlot ) {
  38236. gl.activeTexture( webglSlot );
  38237. this.currentTextureSlot = webglSlot;
  38238. }
  38239. }
  38240. bindTexture( webglType, webglTexture, webglSlot ) {
  38241. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  38242. if ( webglSlot === undefined ) {
  38243. if ( currentTextureSlot === null ) {
  38244. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38245. } else {
  38246. webglSlot = currentTextureSlot;
  38247. }
  38248. }
  38249. let boundTexture = currentBoundTextures[ webglSlot ];
  38250. if ( boundTexture === undefined ) {
  38251. boundTexture = { type: undefined, texture: undefined };
  38252. currentBoundTextures[ webglSlot ] = boundTexture;
  38253. }
  38254. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  38255. if ( currentTextureSlot !== webglSlot ) {
  38256. gl.activeTexture( webglSlot );
  38257. this.currentTextureSlot = webglSlot;
  38258. }
  38259. gl.bindTexture( webglType, webglTexture );
  38260. boundTexture.type = webglType;
  38261. boundTexture.texture = webglTexture;
  38262. }
  38263. }
  38264. unbindTexture() {
  38265. const { gl, currentTextureSlot, currentBoundTextures } = this;
  38266. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  38267. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  38268. gl.bindTexture( boundTexture.type, null );
  38269. boundTexture.type = undefined;
  38270. boundTexture.texture = undefined;
  38271. }
  38272. }
  38273. }
  38274. class WebGLUtils {
  38275. constructor( backend ) {
  38276. this.backend = backend;
  38277. this.gl = this.backend.gl;
  38278. this.extensions = backend.extensions;
  38279. }
  38280. convert( p, colorSpace = NoColorSpace ) {
  38281. const { gl, extensions } = this;
  38282. let extension;
  38283. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  38284. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  38285. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  38286. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  38287. if ( p === ByteType ) return gl.BYTE;
  38288. if ( p === ShortType ) return gl.SHORT;
  38289. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  38290. if ( p === IntType ) return gl.INT;
  38291. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  38292. if ( p === FloatType ) return gl.FLOAT;
  38293. if ( p === HalfFloatType ) {
  38294. return gl.HALF_FLOAT;
  38295. }
  38296. if ( p === AlphaFormat ) return gl.ALPHA;
  38297. if ( p === RGBFormat ) return gl.RGB;
  38298. if ( p === RGBAFormat ) return gl.RGBA;
  38299. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  38300. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  38301. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  38302. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  38303. // WebGL2 formats.
  38304. if ( p === RedFormat ) return gl.RED;
  38305. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  38306. if ( p === RGFormat ) return gl.RG;
  38307. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  38308. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  38309. // S3TC
  38310. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  38311. if ( colorSpace === SRGBColorSpace ) {
  38312. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  38313. if ( extension !== null ) {
  38314. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  38315. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  38316. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  38317. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  38318. } else {
  38319. return null;
  38320. }
  38321. } else {
  38322. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  38323. if ( extension !== null ) {
  38324. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  38325. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  38326. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  38327. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  38328. } else {
  38329. return null;
  38330. }
  38331. }
  38332. }
  38333. // PVRTC
  38334. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  38335. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  38336. if ( extension !== null ) {
  38337. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  38338. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  38339. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  38340. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  38341. } else {
  38342. return null;
  38343. }
  38344. }
  38345. // ETC
  38346. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  38347. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  38348. if ( extension !== null ) {
  38349. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  38350. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  38351. } else {
  38352. return null;
  38353. }
  38354. }
  38355. // ASTC
  38356. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  38357. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  38358. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  38359. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  38360. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  38361. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  38362. if ( extension !== null ) {
  38363. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  38364. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  38365. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  38366. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  38367. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  38368. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  38369. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  38370. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  38371. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  38372. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  38373. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  38374. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  38375. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  38376. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  38377. } else {
  38378. return null;
  38379. }
  38380. }
  38381. // BPTC
  38382. if ( p === RGBA_BPTC_Format ) {
  38383. extension = extensions.get( 'EXT_texture_compression_bptc' );
  38384. if ( extension !== null ) {
  38385. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  38386. } else {
  38387. return null;
  38388. }
  38389. }
  38390. // RGTC
  38391. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  38392. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  38393. if ( extension !== null ) {
  38394. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  38395. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  38396. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  38397. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  38398. } else {
  38399. return null;
  38400. }
  38401. }
  38402. //
  38403. if ( p === UnsignedInt248Type ) {
  38404. return gl.UNSIGNED_INT_24_8;
  38405. }
  38406. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  38407. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  38408. }
  38409. _clientWaitAsync() {
  38410. const { gl } = this;
  38411. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  38412. gl.flush();
  38413. return new Promise( ( resolve, reject ) => {
  38414. function test() {
  38415. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  38416. if ( res === gl.WAIT_FAILED ) {
  38417. gl.deleteSync( sync );
  38418. reject();
  38419. return;
  38420. }
  38421. if ( res === gl.TIMEOUT_EXPIRED ) {
  38422. requestAnimationFrame( test );
  38423. return;
  38424. }
  38425. gl.deleteSync( sync );
  38426. resolve();
  38427. }
  38428. test();
  38429. } );
  38430. }
  38431. }
  38432. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  38433. class WebGLTextureUtils {
  38434. constructor( backend ) {
  38435. this.backend = backend;
  38436. this.gl = backend.gl;
  38437. this.extensions = backend.extensions;
  38438. this.defaultTextures = {};
  38439. if ( initialized === false ) {
  38440. this._init( this.gl );
  38441. initialized = true;
  38442. }
  38443. }
  38444. _init( gl ) {
  38445. // Store only WebGL constants here.
  38446. wrappingToGL = {
  38447. [ RepeatWrapping ]: gl.REPEAT,
  38448. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  38449. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  38450. };
  38451. filterToGL = {
  38452. [ NearestFilter ]: gl.NEAREST,
  38453. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  38454. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  38455. [ LinearFilter ]: gl.LINEAR,
  38456. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  38457. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  38458. };
  38459. compareToGL = {
  38460. [ NeverCompare ]: gl.NEVER,
  38461. [ AlwaysCompare ]: gl.ALWAYS,
  38462. [ LessCompare ]: gl.LESS,
  38463. [ LessEqualCompare ]: gl.LEQUAL,
  38464. [ EqualCompare ]: gl.EQUAL,
  38465. [ GreaterEqualCompare ]: gl.GEQUAL,
  38466. [ GreaterCompare ]: gl.GREATER,
  38467. [ NotEqualCompare ]: gl.NOTEQUAL
  38468. };
  38469. }
  38470. filterFallback( f ) {
  38471. const { gl } = this;
  38472. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  38473. return gl.NEAREST;
  38474. }
  38475. return gl.LINEAR;
  38476. }
  38477. getGLTextureType( texture ) {
  38478. const { gl } = this;
  38479. let glTextureType;
  38480. if ( texture.isCubeTexture === true ) {
  38481. glTextureType = gl.TEXTURE_CUBE_MAP;
  38482. } else if ( texture.isDataArrayTexture === true ) {
  38483. glTextureType = gl.TEXTURE_2D_ARRAY;
  38484. } else if ( texture.isData3DTexture === true ) {
  38485. glTextureType = gl.TEXTURE_3D;
  38486. } else {
  38487. glTextureType = gl.TEXTURE_2D;
  38488. }
  38489. return glTextureType;
  38490. }
  38491. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  38492. const { gl, extensions } = this;
  38493. if ( internalFormatName !== null ) {
  38494. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  38495. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  38496. }
  38497. let internalFormat = glFormat;
  38498. if ( glFormat === gl.RED ) {
  38499. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  38500. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  38501. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  38502. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  38503. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38504. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38505. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38506. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38507. }
  38508. if ( glFormat === gl.RED_INTEGER ) {
  38509. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  38510. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  38511. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38512. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38513. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38514. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38515. }
  38516. if ( glFormat === gl.RG ) {
  38517. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  38518. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  38519. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  38520. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  38521. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38522. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38523. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38524. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38525. }
  38526. if ( glFormat === gl.RG_INTEGER ) {
  38527. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  38528. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  38529. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38530. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38531. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38532. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38533. }
  38534. if ( glFormat === gl.RGB ) {
  38535. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  38536. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  38537. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  38538. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  38539. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38540. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38541. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38542. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38543. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  38544. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  38545. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38546. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  38547. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  38548. }
  38549. if ( glFormat === gl.RGB_INTEGER ) {
  38550. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  38551. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  38552. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38553. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38554. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38555. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38556. }
  38557. if ( glFormat === gl.RGBA ) {
  38558. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  38559. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  38560. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  38561. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  38562. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38563. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38564. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38565. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38566. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  38567. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  38568. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38569. }
  38570. if ( glFormat === gl.RGBA_INTEGER ) {
  38571. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  38572. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  38573. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38574. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38575. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38576. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38577. }
  38578. if ( glFormat === gl.DEPTH_COMPONENT ) {
  38579. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  38580. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  38581. }
  38582. if ( glFormat === gl.DEPTH_STENCIL ) {
  38583. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  38584. }
  38585. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  38586. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  38587. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  38588. extensions.get( 'EXT_color_buffer_float' );
  38589. }
  38590. return internalFormat;
  38591. }
  38592. setTextureParameters( textureType, texture ) {
  38593. const { gl, extensions, backend } = this;
  38594. const { currentAnisotropy } = backend.get( texture );
  38595. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  38596. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  38597. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  38598. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  38599. }
  38600. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  38601. // follow WebGPU backend mapping for texture filtering
  38602. const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter;
  38603. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  38604. if ( texture.compareFunction ) {
  38605. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  38606. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  38607. }
  38608. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38609. if ( texture.magFilter === NearestFilter ) return;
  38610. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  38611. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  38612. if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) {
  38613. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38614. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  38615. backend.get( texture ).currentAnisotropy = texture.anisotropy;
  38616. }
  38617. }
  38618. }
  38619. createDefaultTexture( texture ) {
  38620. const { gl, backend, defaultTextures } = this;
  38621. const glTextureType = this.getGLTextureType( texture );
  38622. let textureGPU = defaultTextures[ glTextureType ];
  38623. if ( textureGPU === undefined ) {
  38624. textureGPU = gl.createTexture();
  38625. backend.state.bindTexture( glTextureType, textureGPU );
  38626. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  38627. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  38628. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  38629. defaultTextures[ glTextureType ] = textureGPU;
  38630. }
  38631. backend.set( texture, {
  38632. textureGPU,
  38633. glTextureType,
  38634. isDefault: true
  38635. } );
  38636. }
  38637. createTexture( texture, options ) {
  38638. const { gl, backend } = this;
  38639. const { levels, width, height, depth } = options;
  38640. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  38641. const glType = backend.utils.convert( texture.type );
  38642. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  38643. const textureGPU = gl.createTexture();
  38644. const glTextureType = this.getGLTextureType( texture );
  38645. backend.state.bindTexture( glTextureType, textureGPU );
  38646. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  38647. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  38648. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  38649. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  38650. this.setTextureParameters( glTextureType, texture );
  38651. if ( texture.isDataArrayTexture ) {
  38652. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  38653. } else if ( texture.isData3DTexture ) {
  38654. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  38655. } else if ( ! texture.isVideoTexture ) {
  38656. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  38657. }
  38658. backend.set( texture, {
  38659. textureGPU,
  38660. glTextureType,
  38661. glFormat,
  38662. glType,
  38663. glInternalFormat
  38664. } );
  38665. }
  38666. copyBufferToTexture( buffer, texture ) {
  38667. const { gl, backend } = this;
  38668. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  38669. const { width, height } = texture.source.data;
  38670. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  38671. backend.state.bindTexture( glTextureType, textureGPU );
  38672. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  38673. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  38674. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  38675. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  38676. backend.state.unbindTexture();
  38677. // debug
  38678. // const framebuffer = gl.createFramebuffer();
  38679. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  38680. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  38681. // const readout = new Float32Array( width * height * 4 );
  38682. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  38683. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  38684. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  38685. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  38686. // console.log( readout );
  38687. }
  38688. updateTexture( texture, options ) {
  38689. const { gl } = this;
  38690. const { width, height } = options;
  38691. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  38692. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  38693. return;
  38694. const getImage = ( source ) => {
  38695. if ( source.isDataTexture ) {
  38696. return source.image.data;
  38697. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  38698. return source;
  38699. }
  38700. return source.data;
  38701. };
  38702. this.backend.state.bindTexture( glTextureType, textureGPU );
  38703. if ( texture.isCompressedTexture ) {
  38704. const mipmaps = texture.mipmaps;
  38705. for ( let i = 0; i < mipmaps.length; i ++ ) {
  38706. const mipmap = mipmaps[ i ];
  38707. if ( texture.isCompressedArrayTexture ) {
  38708. const image = options.image;
  38709. if ( texture.format !== gl.RGBA ) {
  38710. if ( glFormat !== null ) {
  38711. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  38712. } else {
  38713. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  38714. }
  38715. } else {
  38716. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  38717. }
  38718. } else {
  38719. if ( glFormat !== null ) {
  38720. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  38721. } else {
  38722. console.warn( 'Unsupported compressed texture format' );
  38723. }
  38724. }
  38725. }
  38726. } else if ( texture.isCubeTexture ) {
  38727. const images = options.images;
  38728. for ( let i = 0; i < 6; i ++ ) {
  38729. const image = getImage( images[ i ] );
  38730. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  38731. }
  38732. } else if ( texture.isDataArrayTexture ) {
  38733. const image = options.image;
  38734. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38735. } else if ( texture.isData3DTexture ) {
  38736. const image = options.image;
  38737. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38738. } else if ( texture.isVideoTexture ) {
  38739. texture.update();
  38740. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  38741. } else {
  38742. const image = getImage( options.image );
  38743. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  38744. }
  38745. }
  38746. generateMipmaps( texture ) {
  38747. const { gl, backend } = this;
  38748. const { textureGPU, glTextureType } = backend.get( texture );
  38749. backend.state.bindTexture( glTextureType, textureGPU );
  38750. gl.generateMipmap( glTextureType );
  38751. }
  38752. deallocateRenderBuffers( renderTarget ) {
  38753. const { gl, backend } = this;
  38754. // remove framebuffer reference
  38755. if ( renderTarget ) {
  38756. const renderContextData = backend.get( renderTarget );
  38757. renderContextData.renderBufferStorageSetup = undefined;
  38758. if ( renderContextData.framebuffer ) {
  38759. gl.deleteFramebuffer( renderContextData.framebuffer );
  38760. renderContextData.framebuffer = undefined;
  38761. }
  38762. if ( renderContextData.depthRenderbuffer ) {
  38763. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  38764. renderContextData.depthRenderbuffer = undefined;
  38765. }
  38766. if ( renderContextData.stencilRenderbuffer ) {
  38767. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  38768. renderContextData.stencilRenderbuffer = undefined;
  38769. }
  38770. if ( renderContextData.msaaFrameBuffer ) {
  38771. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  38772. renderContextData.msaaFrameBuffer = undefined;
  38773. }
  38774. if ( renderContextData.msaaRenderbuffers ) {
  38775. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  38776. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  38777. }
  38778. renderContextData.msaaRenderbuffers = undefined;
  38779. }
  38780. }
  38781. }
  38782. destroyTexture( texture ) {
  38783. const { gl, backend } = this;
  38784. const { textureGPU, renderTarget } = backend.get( texture );
  38785. this.deallocateRenderBuffers( renderTarget );
  38786. gl.deleteTexture( textureGPU );
  38787. backend.delete( texture );
  38788. }
  38789. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38790. const { gl, backend } = this;
  38791. const { state } = this.backend;
  38792. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  38793. let width, height, minX, minY;
  38794. let dstX, dstY;
  38795. if ( srcRegion !== null ) {
  38796. width = srcRegion.max.x - srcRegion.min.x;
  38797. height = srcRegion.max.y - srcRegion.min.y;
  38798. minX = srcRegion.min.x;
  38799. minY = srcRegion.min.y;
  38800. } else {
  38801. width = srcTexture.image.width;
  38802. height = srcTexture.image.height;
  38803. minX = 0;
  38804. minY = 0;
  38805. }
  38806. if ( dstPosition !== null ) {
  38807. dstX = dstPosition.x;
  38808. dstY = dstPosition.y;
  38809. } else {
  38810. dstX = 0;
  38811. dstY = 0;
  38812. }
  38813. state.bindTexture( glTextureType, dstTextureGPU );
  38814. // As another texture upload may have changed pixelStorei
  38815. // parameters, make sure they are correct for the dstTexture
  38816. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38817. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  38818. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  38819. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38820. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  38821. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  38822. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  38823. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  38824. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  38825. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  38826. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  38827. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  38828. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  38829. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  38830. if ( srcTexture.isDataTexture ) {
  38831. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  38832. } else {
  38833. if ( srcTexture.isCompressedTexture ) {
  38834. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  38835. } else {
  38836. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  38837. }
  38838. }
  38839. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  38840. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  38841. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  38842. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  38843. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  38844. // Generate mipmaps only when copying level 0
  38845. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  38846. state.unbindTexture();
  38847. }
  38848. copyFramebufferToTexture( texture, renderContext ) {
  38849. const { gl } = this;
  38850. const { state } = this.backend;
  38851. const { textureGPU } = this.backend.get( texture );
  38852. const width = texture.image.width;
  38853. const height = texture.image.height;
  38854. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  38855. if ( requireDrawFrameBuffer ) {
  38856. let mask;
  38857. let attachment;
  38858. if ( texture.isDepthTexture === true ) {
  38859. mask = gl.DEPTH_BUFFER_BIT;
  38860. attachment = gl.DEPTH_ATTACHMENT;
  38861. if ( renderContext.stencil ) {
  38862. mask |= gl.STENCIL_BUFFER_BIT;
  38863. }
  38864. } else {
  38865. mask = gl.COLOR_BUFFER_BIT;
  38866. attachment = gl.COLOR_ATTACHMENT0;
  38867. }
  38868. const fb = gl.createFramebuffer();
  38869. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38870. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  38871. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  38872. gl.deleteFramebuffer( fb );
  38873. } else {
  38874. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  38875. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  38876. state.unbindTexture();
  38877. }
  38878. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  38879. this.backend._setFramebuffer( renderContext );
  38880. }
  38881. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  38882. setupRenderBufferStorage( renderbuffer, renderContext ) {
  38883. const { gl } = this;
  38884. const renderTarget = renderContext.renderTarget;
  38885. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  38886. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  38887. if ( depthBuffer && ! stencilBuffer ) {
  38888. let glInternalFormat = gl.DEPTH_COMPONENT24;
  38889. if ( samples > 0 ) {
  38890. if ( depthTexture && depthTexture.isDepthTexture ) {
  38891. if ( depthTexture.type === gl.FLOAT ) {
  38892. glInternalFormat = gl.DEPTH_COMPONENT32F;
  38893. }
  38894. }
  38895. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  38896. } else {
  38897. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  38898. }
  38899. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38900. } else if ( depthBuffer && stencilBuffer ) {
  38901. if ( samples > 0 ) {
  38902. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  38903. } else {
  38904. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  38905. }
  38906. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38907. }
  38908. }
  38909. async copyTextureToBuffer( texture, x, y, width, height ) {
  38910. const { backend, gl } = this;
  38911. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  38912. const fb = gl.createFramebuffer();
  38913. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  38914. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  38915. const typedArrayType = this._getTypedArrayType( glType );
  38916. const bytesPerTexel = this._getBytesPerTexel( glFormat );
  38917. const elementCount = width * height;
  38918. const byteLength = elementCount * bytesPerTexel;
  38919. const buffer = gl.createBuffer();
  38920. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38921. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  38922. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  38923. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38924. await backend.utils._clientWaitAsync();
  38925. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  38926. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38927. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  38928. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38929. gl.deleteFramebuffer( fb );
  38930. return dstBuffer;
  38931. }
  38932. _getTypedArrayType( glType ) {
  38933. const { gl } = this;
  38934. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  38935. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  38936. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  38937. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  38938. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  38939. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  38940. if ( glType === gl.FLOAT ) return Float32Array;
  38941. throw new Error( `Unsupported WebGL type: ${glType}` );
  38942. }
  38943. _getBytesPerTexel( glFormat ) {
  38944. const { gl } = this;
  38945. if ( glFormat === gl.RGBA ) return 4;
  38946. if ( glFormat === gl.RGB ) return 3;
  38947. if ( glFormat === gl.ALPHA ) return 1;
  38948. }
  38949. }
  38950. class WebGLExtensions {
  38951. constructor( backend ) {
  38952. this.backend = backend;
  38953. this.gl = this.backend.gl;
  38954. this.availableExtensions = this.gl.getSupportedExtensions();
  38955. this.extensions = {};
  38956. }
  38957. get( name ) {
  38958. let extension = this.extensions[ name ];
  38959. if ( extension === undefined ) {
  38960. extension = this.gl.getExtension( name );
  38961. this.extensions[ name ] = extension;
  38962. }
  38963. return extension;
  38964. }
  38965. has( name ) {
  38966. return this.availableExtensions.includes( name );
  38967. }
  38968. }
  38969. class WebGLCapabilities {
  38970. constructor( backend ) {
  38971. this.backend = backend;
  38972. this.maxAnisotropy = null;
  38973. }
  38974. getMaxAnisotropy() {
  38975. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  38976. const gl = this.backend.gl;
  38977. const extensions = this.backend.extensions;
  38978. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38979. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38980. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  38981. } else {
  38982. this.maxAnisotropy = 0;
  38983. }
  38984. return this.maxAnisotropy;
  38985. }
  38986. }
  38987. const GLFeatureName = {
  38988. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  38989. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  38990. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  38991. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  38992. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38993. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38994. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  38995. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  38996. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  38997. };
  38998. class WebGLBufferRenderer {
  38999. constructor( backend ) {
  39000. this.gl = backend.gl;
  39001. this.extensions = backend.extensions;
  39002. this.info = backend.renderer.info;
  39003. this.mode = null;
  39004. this.index = 0;
  39005. this.type = null;
  39006. this.object = null;
  39007. }
  39008. render( start, count ) {
  39009. const { gl, mode, object, type, info, index } = this;
  39010. if ( index !== 0 ) {
  39011. gl.drawElements( mode, count, type, start );
  39012. } else {
  39013. gl.drawArrays( mode, start, count );
  39014. }
  39015. info.update( object, count, mode, 1 );
  39016. }
  39017. renderInstances( start, count, primcount ) {
  39018. const { gl, mode, type, index, object, info } = this;
  39019. if ( primcount === 0 ) return;
  39020. if ( index !== 0 ) {
  39021. gl.drawElementsInstanced( mode, count, type, start, primcount );
  39022. } else {
  39023. gl.drawArraysInstanced( mode, start, count, primcount );
  39024. }
  39025. info.update( object, count, mode, primcount );
  39026. }
  39027. renderMultiDraw( starts, counts, drawCount ) {
  39028. const { extensions, mode, object, info } = this;
  39029. if ( drawCount === 0 ) return;
  39030. const extension = extensions.get( 'WEBGL_multi_draw' );
  39031. if ( extension === null ) {
  39032. for ( let i = 0; i < drawCount; i ++ ) {
  39033. this.render( starts[ i ], counts[ i ] );
  39034. }
  39035. } else {
  39036. if ( this.index !== 0 ) {
  39037. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  39038. } else {
  39039. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  39040. }
  39041. let elementCount = 0;
  39042. for ( let i = 0; i < drawCount; i ++ ) {
  39043. elementCount += counts[ i ];
  39044. }
  39045. info.update( object, elementCount, mode, 1 );
  39046. }
  39047. }
  39048. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  39049. const { extensions, mode, object, info } = this;
  39050. if ( drawCount === 0 ) return;
  39051. const extension = extensions.get( 'WEBGL_multi_draw' );
  39052. if ( extension === null ) {
  39053. for ( let i = 0; i < drawCount; i ++ ) {
  39054. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  39055. }
  39056. } else {
  39057. if ( this.index !== 0 ) {
  39058. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  39059. } else {
  39060. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  39061. }
  39062. let elementCount = 0;
  39063. for ( let i = 0; i < drawCount; i ++ ) {
  39064. elementCount += counts[ i ];
  39065. }
  39066. for ( let i = 0; i < primcount.length; i ++ ) {
  39067. info.update( object, elementCount, mode, primcount[ i ] );
  39068. }
  39069. }
  39070. }
  39071. //
  39072. }
  39073. //
  39074. class WebGLBackend extends Backend {
  39075. constructor( parameters = {} ) {
  39076. super( parameters );
  39077. this.isWebGLBackend = true;
  39078. }
  39079. init( renderer ) {
  39080. super.init( renderer );
  39081. //
  39082. const parameters = this.parameters;
  39083. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  39084. this.gl = glContext;
  39085. this.extensions = new WebGLExtensions( this );
  39086. this.capabilities = new WebGLCapabilities( this );
  39087. this.attributeUtils = new WebGLAttributeUtils( this );
  39088. this.textureUtils = new WebGLTextureUtils( this );
  39089. this.bufferRenderer = new WebGLBufferRenderer( this );
  39090. this.state = new WebGLState( this );
  39091. this.utils = new WebGLUtils( this );
  39092. this.vaoCache = {};
  39093. this.transformFeedbackCache = {};
  39094. this.discard = false;
  39095. this.trackTimestamp = ( parameters.trackTimestamp === true );
  39096. this.extensions.get( 'EXT_color_buffer_float' );
  39097. this.extensions.get( 'WEBGL_multi_draw' );
  39098. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  39099. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  39100. this._currentContext = null;
  39101. }
  39102. get coordinateSystem() {
  39103. return WebGLCoordinateSystem;
  39104. }
  39105. async getArrayBufferAsync( attribute ) {
  39106. return await this.attributeUtils.getArrayBufferAsync( attribute );
  39107. }
  39108. initTimestampQuery( renderContext ) {
  39109. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  39110. const renderContextData = this.get( renderContext );
  39111. if ( this.queryRunning ) {
  39112. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  39113. renderContextData.queryQueue.push( renderContext );
  39114. return;
  39115. }
  39116. if ( renderContextData.activeQuery ) {
  39117. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  39118. renderContextData.activeQuery = null;
  39119. }
  39120. renderContextData.activeQuery = this.gl.createQuery();
  39121. if ( renderContextData.activeQuery !== null ) {
  39122. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  39123. this.queryRunning = true;
  39124. }
  39125. }
  39126. // timestamp utils
  39127. prepareTimestampBuffer( renderContext ) {
  39128. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  39129. const renderContextData = this.get( renderContext );
  39130. if ( renderContextData.activeQuery ) {
  39131. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  39132. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  39133. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  39134. renderContextData.activeQuery = null;
  39135. this.queryRunning = false;
  39136. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  39137. const nextRenderContext = renderContextData.queryQueue.shift();
  39138. this.initTimestampQuery( nextRenderContext );
  39139. }
  39140. }
  39141. }
  39142. async resolveTimestampAsync( renderContext, type = 'render' ) {
  39143. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  39144. const renderContextData = this.get( renderContext );
  39145. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  39146. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  39147. const queryInfo = renderContextData.gpuQueries[ i ];
  39148. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  39149. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  39150. if ( available && ! disjoint ) {
  39151. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  39152. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  39153. this.gl.deleteQuery( queryInfo.query );
  39154. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  39155. i --;
  39156. this.renderer.info.updateTimestamp( type, duration );
  39157. }
  39158. }
  39159. }
  39160. getContext() {
  39161. return this.gl;
  39162. }
  39163. beginRender( renderContext ) {
  39164. const { gl } = this;
  39165. const renderContextData = this.get( renderContext );
  39166. //
  39167. //
  39168. this.initTimestampQuery( renderContext );
  39169. renderContextData.previousContext = this._currentContext;
  39170. this._currentContext = renderContext;
  39171. this._setFramebuffer( renderContext );
  39172. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  39173. //
  39174. if ( renderContext.viewport ) {
  39175. this.updateViewport( renderContext );
  39176. } else {
  39177. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  39178. }
  39179. if ( renderContext.scissor ) {
  39180. const { x, y, width, height } = renderContext.scissorValue;
  39181. gl.scissor( x, y, width, height );
  39182. }
  39183. const occlusionQueryCount = renderContext.occlusionQueryCount;
  39184. if ( occlusionQueryCount > 0 ) {
  39185. // Get a reference to the array of objects with queries. The renderContextData property
  39186. // can be changed by another render pass before the async reading of all previous queries complete
  39187. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  39188. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  39189. renderContextData.lastOcclusionObject = null;
  39190. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  39191. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  39192. renderContextData.occlusionQueryIndex = 0;
  39193. }
  39194. }
  39195. finishRender( renderContext ) {
  39196. const { gl, state } = this;
  39197. const renderContextData = this.get( renderContext );
  39198. const previousContext = renderContextData.previousContext;
  39199. const textures = renderContext.textures;
  39200. if ( textures !== null ) {
  39201. for ( let i = 0; i < textures.length; i ++ ) {
  39202. const texture = textures[ i ];
  39203. if ( texture.generateMipmaps ) {
  39204. this.generateMipmaps( texture );
  39205. }
  39206. }
  39207. }
  39208. this._currentContext = previousContext;
  39209. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  39210. const renderTargetContextData = this.get( renderContext.renderTarget );
  39211. const { samples } = renderContext.renderTarget;
  39212. const fb = renderTargetContextData.framebuffer;
  39213. const mask = gl.COLOR_BUFFER_BIT;
  39214. if ( samples > 0 ) {
  39215. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39216. const textures = renderContext.textures;
  39217. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  39218. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39219. for ( let i = 0; i < textures.length; i ++ ) {
  39220. // TODO Add support for MRT
  39221. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  39222. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  39223. }
  39224. }
  39225. }
  39226. if ( previousContext !== null ) {
  39227. this._setFramebuffer( previousContext );
  39228. if ( previousContext.viewport ) {
  39229. this.updateViewport( previousContext );
  39230. } else {
  39231. const gl = this.gl;
  39232. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  39233. }
  39234. }
  39235. const occlusionQueryCount = renderContext.occlusionQueryCount;
  39236. if ( occlusionQueryCount > 0 ) {
  39237. const renderContextData = this.get( renderContext );
  39238. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  39239. const { gl } = this;
  39240. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39241. }
  39242. this.resolveOccludedAsync( renderContext );
  39243. }
  39244. this.prepareTimestampBuffer( renderContext );
  39245. }
  39246. resolveOccludedAsync( renderContext ) {
  39247. const renderContextData = this.get( renderContext );
  39248. // handle occlusion query results
  39249. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  39250. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  39251. const occluded = new WeakSet();
  39252. const { gl } = this;
  39253. renderContextData.currentOcclusionQueryObjects = null;
  39254. renderContextData.currentOcclusionQueries = null;
  39255. const check = () => {
  39256. let completed = 0;
  39257. // check all queries and requeue as appropriate
  39258. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  39259. const query = currentOcclusionQueries[ i ];
  39260. if ( query === null ) continue;
  39261. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  39262. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  39263. currentOcclusionQueries[ i ] = null;
  39264. gl.deleteQuery( query );
  39265. completed ++;
  39266. }
  39267. }
  39268. if ( completed < currentOcclusionQueries.length ) {
  39269. requestAnimationFrame( check );
  39270. } else {
  39271. renderContextData.occluded = occluded;
  39272. }
  39273. };
  39274. check();
  39275. }
  39276. }
  39277. isOccluded( renderContext, object ) {
  39278. const renderContextData = this.get( renderContext );
  39279. return renderContextData.occluded && renderContextData.occluded.has( object );
  39280. }
  39281. updateViewport( renderContext ) {
  39282. const gl = this.gl;
  39283. const { x, y, width, height } = renderContext.viewportValue;
  39284. gl.viewport( x, y, width, height );
  39285. }
  39286. setScissorTest( boolean ) {
  39287. const gl = this.gl;
  39288. if ( boolean ) {
  39289. gl.enable( gl.SCISSOR_TEST );
  39290. } else {
  39291. gl.disable( gl.SCISSOR_TEST );
  39292. }
  39293. }
  39294. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  39295. const { gl } = this;
  39296. if ( descriptor === null ) {
  39297. descriptor = {
  39298. textures: null,
  39299. clearColorValue: this.getClearColor()
  39300. };
  39301. }
  39302. //
  39303. let clear = 0;
  39304. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  39305. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  39306. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  39307. if ( clear !== 0 ) {
  39308. const clearColor = descriptor.clearColorValue || this.getClearColor();
  39309. if ( depth ) this.state.setDepthMask( true );
  39310. if ( descriptor.textures === null ) {
  39311. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  39312. gl.clear( clear );
  39313. } else {
  39314. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  39315. if ( color ) {
  39316. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  39317. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  39318. }
  39319. }
  39320. if ( depth && stencil ) {
  39321. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  39322. } else if ( depth ) {
  39323. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  39324. } else if ( stencil ) {
  39325. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  39326. }
  39327. }
  39328. }
  39329. }
  39330. beginCompute( computeGroup ) {
  39331. const gl = this.gl;
  39332. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39333. this.initTimestampQuery( computeGroup );
  39334. }
  39335. compute( computeGroup, computeNode, bindings, pipeline ) {
  39336. const gl = this.gl;
  39337. if ( ! this.discard ) {
  39338. // required here to handle async behaviour of render.compute()
  39339. gl.enable( gl.RASTERIZER_DISCARD );
  39340. this.discard = true;
  39341. }
  39342. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  39343. const vaoKey = this._getVaoKey( null, attributes );
  39344. const vaoGPU = this.vaoCache[ vaoKey ];
  39345. if ( vaoGPU === undefined ) {
  39346. this._createVao( null, attributes );
  39347. } else {
  39348. gl.bindVertexArray( vaoGPU );
  39349. }
  39350. gl.useProgram( programGPU );
  39351. this._bindUniforms( bindings );
  39352. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  39353. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39354. gl.beginTransformFeedback( gl.POINTS );
  39355. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  39356. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  39357. } else {
  39358. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  39359. }
  39360. gl.endTransformFeedback();
  39361. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39362. // switch active buffers
  39363. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39364. const dualAttributeData = transformBuffers[ i ];
  39365. if ( dualAttributeData.pbo ) {
  39366. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  39367. }
  39368. dualAttributeData.switchBuffers();
  39369. }
  39370. }
  39371. finishCompute( computeGroup ) {
  39372. const gl = this.gl;
  39373. this.discard = false;
  39374. gl.disable( gl.RASTERIZER_DISCARD );
  39375. this.prepareTimestampBuffer( computeGroup );
  39376. }
  39377. draw( renderObject/*, info*/ ) {
  39378. const { object, pipeline, material, context } = renderObject;
  39379. const { programGPU } = this.get( pipeline );
  39380. const { gl, state } = this;
  39381. const contextData = this.get( context );
  39382. //
  39383. this._bindUniforms( renderObject.getBindings() );
  39384. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  39385. state.setMaterial( material, frontFaceCW );
  39386. gl.useProgram( programGPU );
  39387. //
  39388. let vaoGPU = renderObject.staticVao;
  39389. if ( vaoGPU === undefined ) {
  39390. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  39391. vaoGPU = this.vaoCache[ vaoKey ];
  39392. if ( vaoGPU === undefined ) {
  39393. let staticVao;
  39394. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  39395. if ( staticVao ) renderObject.staticVao = vaoGPU;
  39396. }
  39397. }
  39398. gl.bindVertexArray( vaoGPU );
  39399. //
  39400. const index = renderObject.getIndex();
  39401. const geometry = renderObject.geometry;
  39402. const drawRange = renderObject.drawRange;
  39403. const firstVertex = drawRange.start;
  39404. //
  39405. const lastObject = contextData.lastOcclusionObject;
  39406. if ( lastObject !== object && lastObject !== undefined ) {
  39407. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  39408. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39409. contextData.occlusionQueryIndex ++;
  39410. }
  39411. if ( object.occlusionTest === true ) {
  39412. const query = gl.createQuery();
  39413. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  39414. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  39415. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  39416. }
  39417. contextData.lastOcclusionObject = object;
  39418. }
  39419. //
  39420. const renderer = this.bufferRenderer;
  39421. if ( object.isPoints ) renderer.mode = gl.POINTS;
  39422. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  39423. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  39424. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  39425. else {
  39426. if ( material.wireframe === true ) {
  39427. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  39428. renderer.mode = gl.LINES;
  39429. } else {
  39430. renderer.mode = gl.TRIANGLES;
  39431. }
  39432. }
  39433. //
  39434. let count;
  39435. renderer.object = object;
  39436. if ( index !== null ) {
  39437. const indexData = this.get( index );
  39438. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  39439. renderer.index = index.count;
  39440. renderer.type = indexData.type;
  39441. count = indexCount;
  39442. } else {
  39443. renderer.index = 0;
  39444. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  39445. count = vertexCount;
  39446. }
  39447. const instanceCount = this.getInstanceCount( renderObject );
  39448. if ( object.isBatchedMesh ) {
  39449. if ( object._multiDrawInstances !== null ) {
  39450. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  39451. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  39452. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  39453. } else {
  39454. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  39455. }
  39456. } else if ( instanceCount > 1 ) {
  39457. renderer.renderInstances( firstVertex, count, instanceCount );
  39458. } else {
  39459. renderer.render( firstVertex, count );
  39460. }
  39461. //
  39462. gl.bindVertexArray( null );
  39463. }
  39464. needsRenderUpdate( /*renderObject*/ ) {
  39465. return false;
  39466. }
  39467. getRenderCacheKey( renderObject ) {
  39468. return renderObject.id;
  39469. }
  39470. // textures
  39471. createDefaultTexture( texture ) {
  39472. this.textureUtils.createDefaultTexture( texture );
  39473. }
  39474. createTexture( texture, options ) {
  39475. this.textureUtils.createTexture( texture, options );
  39476. }
  39477. updateTexture( texture, options ) {
  39478. this.textureUtils.updateTexture( texture, options );
  39479. }
  39480. generateMipmaps( texture ) {
  39481. this.textureUtils.generateMipmaps( texture );
  39482. }
  39483. destroyTexture( texture ) {
  39484. this.textureUtils.destroyTexture( texture );
  39485. }
  39486. copyTextureToBuffer( texture, x, y, width, height ) {
  39487. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  39488. }
  39489. createSampler( /*texture*/ ) {
  39490. //console.warn( 'Abstract class.' );
  39491. }
  39492. destroySampler() {}
  39493. // node builder
  39494. createNodeBuilder( object, renderer ) {
  39495. return new GLSLNodeBuilder( object, renderer );
  39496. }
  39497. // program
  39498. createProgram( program ) {
  39499. const gl = this.gl;
  39500. const { stage, code } = program;
  39501. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  39502. gl.shaderSource( shader, code );
  39503. gl.compileShader( shader );
  39504. this.set( program, {
  39505. shaderGPU: shader
  39506. } );
  39507. }
  39508. destroyProgram( /*program*/ ) {
  39509. console.warn( 'Abstract class.' );
  39510. }
  39511. createRenderPipeline( renderObject, promises ) {
  39512. const gl = this.gl;
  39513. const pipeline = renderObject.pipeline;
  39514. // Program
  39515. const { fragmentProgram, vertexProgram } = pipeline;
  39516. const programGPU = gl.createProgram();
  39517. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39518. const vertexShader = this.get( vertexProgram ).shaderGPU;
  39519. gl.attachShader( programGPU, fragmentShader );
  39520. gl.attachShader( programGPU, vertexShader );
  39521. gl.linkProgram( programGPU );
  39522. this.set( pipeline, {
  39523. programGPU,
  39524. fragmentShader,
  39525. vertexShader
  39526. } );
  39527. if ( promises !== null && this.parallel ) {
  39528. const p = new Promise( ( resolve /*, reject*/ ) => {
  39529. const parallel = this.parallel;
  39530. const checkStatus = () => {
  39531. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  39532. this._completeCompile( renderObject, pipeline );
  39533. resolve();
  39534. } else {
  39535. requestAnimationFrame( checkStatus );
  39536. }
  39537. };
  39538. checkStatus();
  39539. } );
  39540. promises.push( p );
  39541. return;
  39542. }
  39543. this._completeCompile( renderObject, pipeline );
  39544. }
  39545. _handleSource( string, errorLine ) {
  39546. const lines = string.split( '\n' );
  39547. const lines2 = [];
  39548. const from = Math.max( errorLine - 6, 0 );
  39549. const to = Math.min( errorLine + 6, lines.length );
  39550. for ( let i = from; i < to; i ++ ) {
  39551. const line = i + 1;
  39552. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  39553. }
  39554. return lines2.join( '\n' );
  39555. }
  39556. _getShaderErrors( gl, shader, type ) {
  39557. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  39558. const errors = gl.getShaderInfoLog( shader ).trim();
  39559. if ( status && errors === '' ) return '';
  39560. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  39561. if ( errorMatches ) {
  39562. const errorLine = parseInt( errorMatches[ 1 ] );
  39563. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  39564. } else {
  39565. return errors;
  39566. }
  39567. }
  39568. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  39569. if ( this.renderer.debug.checkShaderErrors ) {
  39570. const gl = this.gl;
  39571. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  39572. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39573. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  39574. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  39575. } else {
  39576. // default error reporting
  39577. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  39578. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  39579. console.error(
  39580. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  39581. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  39582. 'Program Info Log: ' + programLog + '\n' +
  39583. vertexErrors + '\n' +
  39584. fragmentErrors
  39585. );
  39586. }
  39587. } else if ( programLog !== '' ) {
  39588. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  39589. }
  39590. }
  39591. }
  39592. _completeCompile( renderObject, pipeline ) {
  39593. const gl = this.gl;
  39594. const pipelineData = this.get( pipeline );
  39595. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  39596. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39597. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39598. }
  39599. gl.useProgram( programGPU );
  39600. // Bindings
  39601. const bindings = renderObject.getBindings();
  39602. this._setupBindings( bindings, programGPU );
  39603. //
  39604. this.set( pipeline, {
  39605. programGPU
  39606. } );
  39607. }
  39608. createComputePipeline( computePipeline, bindings ) {
  39609. const gl = this.gl;
  39610. // Program
  39611. const fragmentProgram = {
  39612. stage: 'fragment',
  39613. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  39614. };
  39615. this.createProgram( fragmentProgram );
  39616. const { computeProgram } = computePipeline;
  39617. const programGPU = gl.createProgram();
  39618. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39619. const vertexShader = this.get( computeProgram ).shaderGPU;
  39620. const transforms = computeProgram.transforms;
  39621. const transformVaryingNames = [];
  39622. const transformAttributeNodes = [];
  39623. for ( let i = 0; i < transforms.length; i ++ ) {
  39624. const transform = transforms[ i ];
  39625. transformVaryingNames.push( transform.varyingName );
  39626. transformAttributeNodes.push( transform.attributeNode );
  39627. }
  39628. gl.attachShader( programGPU, fragmentShader );
  39629. gl.attachShader( programGPU, vertexShader );
  39630. gl.transformFeedbackVaryings(
  39631. programGPU,
  39632. transformVaryingNames,
  39633. gl.SEPARATE_ATTRIBS
  39634. );
  39635. gl.linkProgram( programGPU );
  39636. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39637. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39638. }
  39639. gl.useProgram( programGPU );
  39640. // Bindings
  39641. this.createBindings( null, bindings );
  39642. this._setupBindings( bindings, programGPU );
  39643. const attributeNodes = computeProgram.attributes;
  39644. const attributes = [];
  39645. const transformBuffers = [];
  39646. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  39647. const attribute = attributeNodes[ i ].node.attribute;
  39648. attributes.push( attribute );
  39649. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39650. }
  39651. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  39652. const attribute = transformAttributeNodes[ i ].attribute;
  39653. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39654. const attributeData = this.get( attribute );
  39655. transformBuffers.push( attributeData );
  39656. }
  39657. //
  39658. this.set( computePipeline, {
  39659. programGPU,
  39660. transformBuffers,
  39661. attributes
  39662. } );
  39663. }
  39664. createBindings( bindGroup, bindings ) {
  39665. this.updateBindings( bindGroup, bindings );
  39666. }
  39667. updateBindings( bindGroup, bindings ) {
  39668. const { gl } = this;
  39669. let groupIndex = 0;
  39670. let textureIndex = 0;
  39671. for ( const bindGroup of bindings ) {
  39672. for ( const binding of bindGroup.bindings ) {
  39673. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39674. const bufferGPU = gl.createBuffer();
  39675. const data = binding.buffer;
  39676. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39677. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39678. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  39679. this.set( binding, {
  39680. index: groupIndex ++,
  39681. bufferGPU
  39682. } );
  39683. } else if ( binding.isSampledTexture ) {
  39684. const { textureGPU, glTextureType } = this.get( binding.texture );
  39685. this.set( binding, {
  39686. index: textureIndex ++,
  39687. textureGPU,
  39688. glTextureType
  39689. } );
  39690. }
  39691. }
  39692. }
  39693. }
  39694. updateBinding( binding ) {
  39695. const gl = this.gl;
  39696. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39697. const bindingData = this.get( binding );
  39698. const bufferGPU = bindingData.bufferGPU;
  39699. const data = binding.buffer;
  39700. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39701. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39702. }
  39703. }
  39704. // attributes
  39705. createIndexAttribute( attribute ) {
  39706. const gl = this.gl;
  39707. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  39708. }
  39709. createAttribute( attribute ) {
  39710. if ( this.has( attribute ) ) return;
  39711. const gl = this.gl;
  39712. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39713. }
  39714. createStorageAttribute( attribute ) {
  39715. if ( this.has( attribute ) ) return;
  39716. const gl = this.gl;
  39717. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39718. }
  39719. updateAttribute( attribute ) {
  39720. this.attributeUtils.updateAttribute( attribute );
  39721. }
  39722. destroyAttribute( attribute ) {
  39723. this.attributeUtils.destroyAttribute( attribute );
  39724. }
  39725. updateSize() {
  39726. //console.warn( 'Abstract class.' );
  39727. }
  39728. hasFeature( name ) {
  39729. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  39730. const extensions = this.extensions;
  39731. for ( let i = 0; i < keysMatching.length; i ++ ) {
  39732. if ( extensions.has( keysMatching[ i ] ) ) return true;
  39733. }
  39734. return false;
  39735. }
  39736. getMaxAnisotropy() {
  39737. return this.capabilities.getMaxAnisotropy();
  39738. }
  39739. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  39740. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  39741. }
  39742. copyFramebufferToTexture( texture, renderContext ) {
  39743. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  39744. }
  39745. _setFramebuffer( renderContext ) {
  39746. const { gl, state } = this;
  39747. let currentFrameBuffer = null;
  39748. if ( renderContext.textures !== null ) {
  39749. const renderTarget = renderContext.renderTarget;
  39750. const renderTargetContextData = this.get( renderTarget );
  39751. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  39752. const cubeFace = this.renderer._activeCubeFace;
  39753. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  39754. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  39755. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  39756. let fb;
  39757. if ( isCube ) {
  39758. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  39759. renderTargetContextData.cubeFramebuffers = [];
  39760. }
  39761. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  39762. } else {
  39763. fb = renderTargetContextData.framebuffer;
  39764. }
  39765. if ( fb === undefined ) {
  39766. fb = gl.createFramebuffer();
  39767. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  39768. const textures = renderContext.textures;
  39769. if ( isCube ) {
  39770. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  39771. const { textureGPU } = this.get( textures[ 0 ] );
  39772. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  39773. } else {
  39774. for ( let i = 0; i < textures.length; i ++ ) {
  39775. const texture = textures[ i ];
  39776. const textureData = this.get( texture );
  39777. textureData.renderTarget = renderContext.renderTarget;
  39778. const attachment = gl.COLOR_ATTACHMENT0 + i;
  39779. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39780. }
  39781. renderTargetContextData.framebuffer = fb;
  39782. state.drawBuffers( renderContext, fb );
  39783. }
  39784. if ( renderContext.depthTexture !== null ) {
  39785. const textureData = this.get( renderContext.depthTexture );
  39786. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39787. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39788. }
  39789. }
  39790. if ( samples > 0 ) {
  39791. if ( msaaFb === undefined ) {
  39792. const invalidationArray = [];
  39793. msaaFb = gl.createFramebuffer();
  39794. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  39795. const msaaRenderbuffers = [];
  39796. const textures = renderContext.textures;
  39797. for ( let i = 0; i < textures.length; i ++ ) {
  39798. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  39799. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39800. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  39801. if ( depthBuffer ) {
  39802. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39803. invalidationArray.push( depthStyle );
  39804. }
  39805. const texture = renderContext.textures[ i ];
  39806. const textureData = this.get( texture );
  39807. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  39808. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39809. }
  39810. renderTargetContextData.msaaFrameBuffer = msaaFb;
  39811. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  39812. if ( depthRenderbuffer === undefined ) {
  39813. depthRenderbuffer = gl.createRenderbuffer();
  39814. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  39815. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  39816. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39817. invalidationArray.push( depthStyle );
  39818. }
  39819. renderTargetContextData.invalidationArray = invalidationArray;
  39820. }
  39821. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39822. } else {
  39823. currentFrameBuffer = fb;
  39824. }
  39825. }
  39826. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  39827. }
  39828. _getVaoKey( index, attributes ) {
  39829. let key = [];
  39830. if ( index !== null ) {
  39831. const indexData = this.get( index );
  39832. key += ':' + indexData.id;
  39833. }
  39834. for ( let i = 0; i < attributes.length; i ++ ) {
  39835. const attributeData = this.get( attributes[ i ] );
  39836. key += ':' + attributeData.id;
  39837. }
  39838. return key;
  39839. }
  39840. _createVao( index, attributes ) {
  39841. const { gl } = this;
  39842. const vaoGPU = gl.createVertexArray();
  39843. let key = '';
  39844. let staticVao = true;
  39845. gl.bindVertexArray( vaoGPU );
  39846. if ( index !== null ) {
  39847. const indexData = this.get( index );
  39848. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  39849. key += ':' + indexData.id;
  39850. }
  39851. for ( let i = 0; i < attributes.length; i ++ ) {
  39852. const attribute = attributes[ i ];
  39853. const attributeData = this.get( attribute );
  39854. key += ':' + attributeData.id;
  39855. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  39856. gl.enableVertexAttribArray( i );
  39857. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  39858. let stride, offset;
  39859. if ( attribute.isInterleavedBufferAttribute === true ) {
  39860. stride = attribute.data.stride * attributeData.bytesPerElement;
  39861. offset = attribute.offset * attributeData.bytesPerElement;
  39862. } else {
  39863. stride = 0;
  39864. offset = 0;
  39865. }
  39866. if ( attributeData.isInteger ) {
  39867. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  39868. } else {
  39869. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  39870. }
  39871. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  39872. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  39873. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  39874. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  39875. }
  39876. }
  39877. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  39878. this.vaoCache[ key ] = vaoGPU;
  39879. return { vaoGPU, staticVao };
  39880. }
  39881. _getTransformFeedback( transformBuffers ) {
  39882. let key = '';
  39883. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39884. key += ':' + transformBuffers[ i ].id;
  39885. }
  39886. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  39887. if ( transformFeedbackGPU !== undefined ) {
  39888. return transformFeedbackGPU;
  39889. }
  39890. const gl = this.gl;
  39891. transformFeedbackGPU = gl.createTransformFeedback();
  39892. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39893. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39894. const attributeData = transformBuffers[ i ];
  39895. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  39896. }
  39897. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39898. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  39899. return transformFeedbackGPU;
  39900. }
  39901. _setupBindings( bindings, programGPU ) {
  39902. const gl = this.gl;
  39903. for ( const bindGroup of bindings ) {
  39904. for ( const binding of bindGroup.bindings ) {
  39905. const bindingData = this.get( binding );
  39906. const index = bindingData.index;
  39907. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39908. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  39909. gl.uniformBlockBinding( programGPU, location, index );
  39910. } else if ( binding.isSampledTexture ) {
  39911. const location = gl.getUniformLocation( programGPU, binding.name );
  39912. gl.uniform1i( location, index );
  39913. }
  39914. }
  39915. }
  39916. }
  39917. _bindUniforms( bindings ) {
  39918. const { gl, state } = this;
  39919. for ( const bindGroup of bindings ) {
  39920. for ( const binding of bindGroup.bindings ) {
  39921. const bindingData = this.get( binding );
  39922. const index = bindingData.index;
  39923. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39924. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  39925. } else if ( binding.isSampledTexture ) {
  39926. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  39927. }
  39928. }
  39929. }
  39930. }
  39931. }
  39932. class Sampler extends Binding {
  39933. constructor( name, texture ) {
  39934. super( name );
  39935. this.texture = texture;
  39936. this.version = texture ? texture.version : 0;
  39937. this.isSampler = true;
  39938. }
  39939. }
  39940. class NodeSampler extends Sampler {
  39941. constructor( name, textureNode, groupNode ) {
  39942. super( name, textureNode ? textureNode.value : null );
  39943. this.textureNode = textureNode;
  39944. this.groupNode = groupNode;
  39945. }
  39946. update() {
  39947. this.texture = this.textureNode.value;
  39948. }
  39949. }
  39950. class StorageBuffer extends Buffer {
  39951. constructor( name, attribute ) {
  39952. super( name, attribute ? attribute.array : null );
  39953. this.attribute = attribute;
  39954. this.isStorageBuffer = true;
  39955. }
  39956. }
  39957. let _id = 0;
  39958. class NodeStorageBuffer extends StorageBuffer {
  39959. constructor( nodeUniform, groupNode ) {
  39960. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  39961. this.nodeUniform = nodeUniform;
  39962. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  39963. this.groupNode = groupNode;
  39964. }
  39965. get buffer() {
  39966. return this.nodeUniform.value;
  39967. }
  39968. }
  39969. class WebGPUTexturePassUtils {
  39970. constructor( device ) {
  39971. this.device = device;
  39972. const mipmapVertexSource = `
  39973. struct VarysStruct {
  39974. @builtin( position ) Position: vec4<f32>,
  39975. @location( 0 ) vTex : vec2<f32>
  39976. };
  39977. @vertex
  39978. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  39979. var Varys : VarysStruct;
  39980. var pos = array< vec2<f32>, 4 >(
  39981. vec2<f32>( -1.0, 1.0 ),
  39982. vec2<f32>( 1.0, 1.0 ),
  39983. vec2<f32>( -1.0, -1.0 ),
  39984. vec2<f32>( 1.0, -1.0 )
  39985. );
  39986. var tex = array< vec2<f32>, 4 >(
  39987. vec2<f32>( 0.0, 0.0 ),
  39988. vec2<f32>( 1.0, 0.0 ),
  39989. vec2<f32>( 0.0, 1.0 ),
  39990. vec2<f32>( 1.0, 1.0 )
  39991. );
  39992. Varys.vTex = tex[ vertexIndex ];
  39993. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  39994. return Varys;
  39995. }
  39996. `;
  39997. const mipmapFragmentSource = `
  39998. @group( 0 ) @binding( 0 )
  39999. var imgSampler : sampler;
  40000. @group( 0 ) @binding( 1 )
  40001. var img : texture_2d<f32>;
  40002. @fragment
  40003. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  40004. return textureSample( img, imgSampler, vTex );
  40005. }
  40006. `;
  40007. const flipYFragmentSource = `
  40008. @group( 0 ) @binding( 0 )
  40009. var imgSampler : sampler;
  40010. @group( 0 ) @binding( 1 )
  40011. var img : texture_2d<f32>;
  40012. @fragment
  40013. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  40014. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  40015. }
  40016. `;
  40017. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  40018. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  40019. // We'll need a new pipeline for every texture format used.
  40020. this.transferPipelines = {};
  40021. this.flipYPipelines = {};
  40022. this.mipmapVertexShaderModule = device.createShaderModule( {
  40023. label: 'mipmapVertex',
  40024. code: mipmapVertexSource
  40025. } );
  40026. this.mipmapFragmentShaderModule = device.createShaderModule( {
  40027. label: 'mipmapFragment',
  40028. code: mipmapFragmentSource
  40029. } );
  40030. this.flipYFragmentShaderModule = device.createShaderModule( {
  40031. label: 'flipYFragment',
  40032. code: flipYFragmentSource
  40033. } );
  40034. }
  40035. getTransferPipeline( format ) {
  40036. let pipeline = this.transferPipelines[ format ];
  40037. if ( pipeline === undefined ) {
  40038. pipeline = this.device.createRenderPipeline( {
  40039. vertex: {
  40040. module: this.mipmapVertexShaderModule,
  40041. entryPoint: 'main'
  40042. },
  40043. fragment: {
  40044. module: this.mipmapFragmentShaderModule,
  40045. entryPoint: 'main',
  40046. targets: [ { format } ]
  40047. },
  40048. primitive: {
  40049. topology: GPUPrimitiveTopology.TriangleStrip,
  40050. stripIndexFormat: GPUIndexFormat.Uint32
  40051. },
  40052. layout: 'auto'
  40053. } );
  40054. this.transferPipelines[ format ] = pipeline;
  40055. }
  40056. return pipeline;
  40057. }
  40058. getFlipYPipeline( format ) {
  40059. let pipeline = this.flipYPipelines[ format ];
  40060. if ( pipeline === undefined ) {
  40061. pipeline = this.device.createRenderPipeline( {
  40062. vertex: {
  40063. module: this.mipmapVertexShaderModule,
  40064. entryPoint: 'main'
  40065. },
  40066. fragment: {
  40067. module: this.flipYFragmentShaderModule,
  40068. entryPoint: 'main',
  40069. targets: [ { format } ]
  40070. },
  40071. primitive: {
  40072. topology: GPUPrimitiveTopology.TriangleStrip,
  40073. stripIndexFormat: GPUIndexFormat.Uint32
  40074. },
  40075. layout: 'auto'
  40076. } );
  40077. this.flipYPipelines[ format ] = pipeline;
  40078. }
  40079. return pipeline;
  40080. }
  40081. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  40082. const format = textureGPUDescriptor.format;
  40083. const { width, height } = textureGPUDescriptor.size;
  40084. const transferPipeline = this.getTransferPipeline( format );
  40085. const flipYPipeline = this.getFlipYPipeline( format );
  40086. const tempTexture = this.device.createTexture( {
  40087. size: { width, height, depthOrArrayLayers: 1 },
  40088. format,
  40089. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  40090. } );
  40091. const srcView = textureGPU.createView( {
  40092. baseMipLevel: 0,
  40093. mipLevelCount: 1,
  40094. dimension: GPUTextureViewDimension.TwoD,
  40095. baseArrayLayer
  40096. } );
  40097. const dstView = tempTexture.createView( {
  40098. baseMipLevel: 0,
  40099. mipLevelCount: 1,
  40100. dimension: GPUTextureViewDimension.TwoD,
  40101. baseArrayLayer: 0
  40102. } );
  40103. const commandEncoder = this.device.createCommandEncoder( {} );
  40104. const pass = ( pipeline, sourceView, destinationView ) => {
  40105. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  40106. const bindGroup = this.device.createBindGroup( {
  40107. layout: bindGroupLayout,
  40108. entries: [ {
  40109. binding: 0,
  40110. resource: this.flipYSampler
  40111. }, {
  40112. binding: 1,
  40113. resource: sourceView
  40114. } ]
  40115. } );
  40116. const passEncoder = commandEncoder.beginRenderPass( {
  40117. colorAttachments: [ {
  40118. view: destinationView,
  40119. loadOp: GPULoadOp.Clear,
  40120. storeOp: GPUStoreOp.Store,
  40121. clearValue: [ 0, 0, 0, 0 ]
  40122. } ]
  40123. } );
  40124. passEncoder.setPipeline( pipeline );
  40125. passEncoder.setBindGroup( 0, bindGroup );
  40126. passEncoder.draw( 4, 1, 0, 0 );
  40127. passEncoder.end();
  40128. };
  40129. pass( transferPipeline, srcView, dstView );
  40130. pass( flipYPipeline, dstView, srcView );
  40131. this.device.queue.submit( [ commandEncoder.finish() ] );
  40132. tempTexture.destroy();
  40133. }
  40134. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  40135. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  40136. const commandEncoder = this.device.createCommandEncoder( {} );
  40137. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  40138. let srcView = textureGPU.createView( {
  40139. baseMipLevel: 0,
  40140. mipLevelCount: 1,
  40141. dimension: GPUTextureViewDimension.TwoD,
  40142. baseArrayLayer
  40143. } );
  40144. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  40145. const bindGroup = this.device.createBindGroup( {
  40146. layout: bindGroupLayout,
  40147. entries: [ {
  40148. binding: 0,
  40149. resource: this.mipmapSampler
  40150. }, {
  40151. binding: 1,
  40152. resource: srcView
  40153. } ]
  40154. } );
  40155. const dstView = textureGPU.createView( {
  40156. baseMipLevel: i,
  40157. mipLevelCount: 1,
  40158. dimension: GPUTextureViewDimension.TwoD,
  40159. baseArrayLayer
  40160. } );
  40161. const passEncoder = commandEncoder.beginRenderPass( {
  40162. colorAttachments: [ {
  40163. view: dstView,
  40164. loadOp: GPULoadOp.Clear,
  40165. storeOp: GPUStoreOp.Store,
  40166. clearValue: [ 0, 0, 0, 0 ]
  40167. } ]
  40168. } );
  40169. passEncoder.setPipeline( pipeline );
  40170. passEncoder.setBindGroup( 0, bindGroup );
  40171. passEncoder.draw( 4, 1, 0, 0 );
  40172. passEncoder.end();
  40173. srcView = dstView;
  40174. }
  40175. this.device.queue.submit( [ commandEncoder.finish() ] );
  40176. }
  40177. }
  40178. const _compareToWebGPU = {
  40179. [ NeverCompare ]: 'never',
  40180. [ LessCompare ]: 'less',
  40181. [ EqualCompare ]: 'equal',
  40182. [ LessEqualCompare ]: 'less-equal',
  40183. [ GreaterCompare ]: 'greater',
  40184. [ GreaterEqualCompare ]: 'greater-equal',
  40185. [ AlwaysCompare ]: 'always',
  40186. [ NotEqualCompare ]: 'not-equal'
  40187. };
  40188. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  40189. class WebGPUTextureUtils {
  40190. constructor( backend ) {
  40191. this.backend = backend;
  40192. this._passUtils = null;
  40193. this.defaultTexture = {};
  40194. this.defaultCubeTexture = {};
  40195. this.colorBuffer = null;
  40196. this.depthTexture = new DepthTexture();
  40197. this.depthTexture.name = 'depthBuffer';
  40198. }
  40199. createSampler( texture ) {
  40200. const backend = this.backend;
  40201. const device = backend.device;
  40202. const textureGPU = backend.get( texture );
  40203. const samplerDescriptorGPU = {
  40204. addressModeU: this._convertAddressMode( texture.wrapS ),
  40205. addressModeV: this._convertAddressMode( texture.wrapT ),
  40206. addressModeW: this._convertAddressMode( texture.wrapR ),
  40207. magFilter: this._convertFilterMode( texture.magFilter ),
  40208. minFilter: this._convertFilterMode( texture.minFilter ),
  40209. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  40210. maxAnisotropy: texture.anisotropy
  40211. };
  40212. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  40213. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  40214. }
  40215. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  40216. }
  40217. createDefaultTexture( texture ) {
  40218. let textureGPU;
  40219. const format = getFormat( texture );
  40220. if ( texture.isCubeTexture ) {
  40221. textureGPU = this._getDefaultCubeTextureGPU( format );
  40222. } else {
  40223. textureGPU = this._getDefaultTextureGPU( format );
  40224. }
  40225. this.backend.get( texture ).texture = textureGPU;
  40226. }
  40227. createTexture( texture, options = {} ) {
  40228. const backend = this.backend;
  40229. const textureData = backend.get( texture );
  40230. if ( textureData.initialized ) {
  40231. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  40232. }
  40233. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  40234. if ( options.levels === undefined ) options.levels = 1;
  40235. if ( options.depth === undefined ) options.depth = 1;
  40236. const { width, height, depth, levels } = options;
  40237. const dimension = this._getDimension( texture );
  40238. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  40239. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  40240. sampleCount = backend.utils.getSampleCount( sampleCount );
  40241. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  40242. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  40243. if ( texture.isStorageTexture === true ) {
  40244. usage |= GPUTextureUsage.STORAGE_BINDING;
  40245. }
  40246. if ( texture.isCompressedTexture !== true ) {
  40247. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  40248. }
  40249. const textureDescriptorGPU = {
  40250. label: texture.name,
  40251. size: {
  40252. width: width,
  40253. height: height,
  40254. depthOrArrayLayers: depth,
  40255. },
  40256. mipLevelCount: levels,
  40257. sampleCount: primarySampleCount,
  40258. dimension: dimension,
  40259. format: format,
  40260. usage: usage
  40261. };
  40262. // texture creation
  40263. if ( texture.isVideoTexture ) {
  40264. const video = texture.source.data;
  40265. const videoFrame = new VideoFrame( video );
  40266. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  40267. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  40268. videoFrame.close();
  40269. textureData.externalTexture = video;
  40270. } else {
  40271. if ( format === undefined ) {
  40272. console.warn( 'WebGPURenderer: Texture format not supported.' );
  40273. return this.createDefaultTexture( texture );
  40274. }
  40275. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  40276. }
  40277. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  40278. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  40279. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  40280. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  40281. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  40282. }
  40283. textureData.initialized = true;
  40284. textureData.textureDescriptorGPU = textureDescriptorGPU;
  40285. }
  40286. destroyTexture( texture ) {
  40287. const backend = this.backend;
  40288. const textureData = backend.get( texture );
  40289. textureData.texture.destroy();
  40290. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  40291. backend.delete( texture );
  40292. }
  40293. destroySampler( texture ) {
  40294. const backend = this.backend;
  40295. const textureData = backend.get( texture );
  40296. delete textureData.sampler;
  40297. }
  40298. generateMipmaps( texture ) {
  40299. const textureData = this.backend.get( texture );
  40300. if ( texture.isCubeTexture ) {
  40301. for ( let i = 0; i < 6; i ++ ) {
  40302. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  40303. }
  40304. } else {
  40305. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU );
  40306. }
  40307. }
  40308. getColorBuffer() {
  40309. if ( this.colorBuffer ) this.colorBuffer.destroy();
  40310. const backend = this.backend;
  40311. const { width, height } = backend.getDrawingBufferSize();
  40312. this.colorBuffer = backend.device.createTexture( {
  40313. label: 'colorBuffer',
  40314. size: {
  40315. width: width,
  40316. height: height,
  40317. depthOrArrayLayers: 1
  40318. },
  40319. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  40320. format: GPUTextureFormat.BGRA8Unorm,
  40321. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  40322. } );
  40323. return this.colorBuffer;
  40324. }
  40325. getDepthBuffer( depth = true, stencil = false ) {
  40326. const backend = this.backend;
  40327. const { width, height } = backend.getDrawingBufferSize();
  40328. const depthTexture = this.depthTexture;
  40329. const depthTextureGPU = backend.get( depthTexture ).texture;
  40330. let format, type;
  40331. if ( stencil ) {
  40332. format = DepthStencilFormat;
  40333. type = UnsignedInt248Type;
  40334. } else if ( depth ) {
  40335. format = DepthFormat;
  40336. type = UnsignedIntType;
  40337. }
  40338. if ( depthTextureGPU !== undefined ) {
  40339. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  40340. return depthTextureGPU;
  40341. }
  40342. this.destroyTexture( depthTexture );
  40343. }
  40344. depthTexture.name = 'depthBuffer';
  40345. depthTexture.format = format;
  40346. depthTexture.type = type;
  40347. depthTexture.image.width = width;
  40348. depthTexture.image.height = height;
  40349. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  40350. return backend.get( depthTexture ).texture;
  40351. }
  40352. updateTexture( texture, options ) {
  40353. const textureData = this.backend.get( texture );
  40354. const { textureDescriptorGPU } = textureData;
  40355. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  40356. return;
  40357. // transfer texture data
  40358. if ( texture.isDataTexture ) {
  40359. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40360. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  40361. for ( let i = 0; i < options.image.depth; i ++ ) {
  40362. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  40363. }
  40364. } else if ( texture.isCompressedTexture ) {
  40365. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  40366. } else if ( texture.isCubeTexture ) {
  40367. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  40368. } else if ( texture.isVideoTexture ) {
  40369. const video = texture.source.data;
  40370. textureData.externalTexture = video;
  40371. } else {
  40372. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40373. }
  40374. //
  40375. textureData.version = texture.version;
  40376. if ( texture.onUpdate ) texture.onUpdate( texture );
  40377. }
  40378. async copyTextureToBuffer( texture, x, y, width, height ) {
  40379. const device = this.backend.device;
  40380. const textureData = this.backend.get( texture );
  40381. const textureGPU = textureData.texture;
  40382. const format = textureData.textureDescriptorGPU.format;
  40383. const bytesPerTexel = this._getBytesPerTexel( format );
  40384. let bytesPerRow = width * bytesPerTexel;
  40385. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  40386. const readBuffer = device.createBuffer(
  40387. {
  40388. size: width * height * bytesPerTexel,
  40389. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  40390. }
  40391. );
  40392. const encoder = device.createCommandEncoder();
  40393. encoder.copyTextureToBuffer(
  40394. {
  40395. texture: textureGPU,
  40396. origin: { x, y },
  40397. },
  40398. {
  40399. buffer: readBuffer,
  40400. bytesPerRow: bytesPerRow
  40401. },
  40402. {
  40403. width: width,
  40404. height: height
  40405. }
  40406. );
  40407. const typedArrayType = this._getTypedArrayType( format );
  40408. device.queue.submit( [ encoder.finish() ] );
  40409. await readBuffer.mapAsync( GPUMapMode.READ );
  40410. const buffer = readBuffer.getMappedRange();
  40411. return new typedArrayType( buffer );
  40412. }
  40413. _isEnvironmentTexture( texture ) {
  40414. const mapping = texture.mapping;
  40415. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  40416. }
  40417. _getDefaultTextureGPU( format ) {
  40418. let defaultTexture = this.defaultTexture[ format ];
  40419. if ( defaultTexture === undefined ) {
  40420. const texture = new Texture();
  40421. texture.minFilter = NearestFilter;
  40422. texture.magFilter = NearestFilter;
  40423. this.createTexture( texture, { width: 1, height: 1, format } );
  40424. this.defaultTexture[ format ] = defaultTexture = texture;
  40425. }
  40426. return this.backend.get( defaultTexture ).texture;
  40427. }
  40428. _getDefaultCubeTextureGPU( format ) {
  40429. let defaultCubeTexture = this.defaultTexture[ format ];
  40430. if ( defaultCubeTexture === undefined ) {
  40431. const texture = new CubeTexture();
  40432. texture.minFilter = NearestFilter;
  40433. texture.magFilter = NearestFilter;
  40434. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  40435. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  40436. }
  40437. return this.backend.get( defaultCubeTexture ).texture;
  40438. }
  40439. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  40440. for ( let i = 0; i < 6; i ++ ) {
  40441. const image = images[ i ];
  40442. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  40443. if ( image.isDataTexture ) {
  40444. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40445. } else {
  40446. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40447. }
  40448. }
  40449. }
  40450. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  40451. const device = this.backend.device;
  40452. device.queue.copyExternalImageToTexture(
  40453. {
  40454. source: image
  40455. }, {
  40456. texture: textureGPU,
  40457. mipLevel: 0,
  40458. origin: { x: 0, y: 0, z: originDepth }
  40459. }, {
  40460. width: image.width,
  40461. height: image.height,
  40462. depthOrArrayLayers: 1
  40463. }
  40464. );
  40465. if ( flipY === true ) {
  40466. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40467. }
  40468. }
  40469. _getPassUtils() {
  40470. let passUtils = this._passUtils;
  40471. if ( passUtils === null ) {
  40472. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  40473. }
  40474. return passUtils;
  40475. }
  40476. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  40477. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  40478. }
  40479. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  40480. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  40481. }
  40482. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  40483. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40484. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  40485. const device = this.backend.device;
  40486. const data = image.data;
  40487. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  40488. const bytesPerRow = image.width * bytesPerTexel;
  40489. device.queue.writeTexture(
  40490. {
  40491. texture: textureGPU,
  40492. mipLevel: 0,
  40493. origin: { x: 0, y: 0, z: originDepth }
  40494. },
  40495. data,
  40496. {
  40497. offset: image.width * image.height * bytesPerTexel * depth,
  40498. bytesPerRow
  40499. },
  40500. {
  40501. width: image.width,
  40502. height: image.height,
  40503. depthOrArrayLayers: 1
  40504. } );
  40505. if ( flipY === true ) {
  40506. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40507. }
  40508. }
  40509. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  40510. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40511. const device = this.backend.device;
  40512. const blockData = this._getBlockData( textureDescriptorGPU.format );
  40513. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40514. const mipmap = mipmaps[ i ];
  40515. const width = mipmap.width;
  40516. const height = mipmap.height;
  40517. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  40518. device.queue.writeTexture(
  40519. {
  40520. texture: textureGPU,
  40521. mipLevel: i
  40522. },
  40523. mipmap.data,
  40524. {
  40525. offset: 0,
  40526. bytesPerRow
  40527. },
  40528. {
  40529. width: Math.ceil( width / blockData.width ) * blockData.width,
  40530. height: Math.ceil( height / blockData.width ) * blockData.width,
  40531. depthOrArrayLayers: 1
  40532. }
  40533. );
  40534. }
  40535. }
  40536. _getBlockData( format ) {
  40537. // this method is only relevant for compressed texture formats
  40538. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  40539. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  40540. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  40541. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  40542. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  40543. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  40544. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  40545. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40546. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40547. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40548. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  40549. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  40550. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  40551. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  40552. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40553. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  40554. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  40555. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  40556. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  40557. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  40558. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  40559. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  40560. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  40561. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  40562. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  40563. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  40564. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  40565. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  40566. }
  40567. _convertAddressMode( value ) {
  40568. let addressMode = GPUAddressMode.ClampToEdge;
  40569. if ( value === RepeatWrapping ) {
  40570. addressMode = GPUAddressMode.Repeat;
  40571. } else if ( value === MirroredRepeatWrapping ) {
  40572. addressMode = GPUAddressMode.MirrorRepeat;
  40573. }
  40574. return addressMode;
  40575. }
  40576. _convertFilterMode( value ) {
  40577. let filterMode = GPUFilterMode.Linear;
  40578. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  40579. filterMode = GPUFilterMode.Nearest;
  40580. }
  40581. return filterMode;
  40582. }
  40583. _getBytesPerTexel( format ) {
  40584. // 8-bit formats
  40585. if ( format === GPUTextureFormat.R8Unorm ||
  40586. format === GPUTextureFormat.R8Snorm ||
  40587. format === GPUTextureFormat.R8Uint ||
  40588. format === GPUTextureFormat.R8Sint ) return 1;
  40589. // 16-bit formats
  40590. if ( format === GPUTextureFormat.R16Uint ||
  40591. format === GPUTextureFormat.R16Sint ||
  40592. format === GPUTextureFormat.R16Float ||
  40593. format === GPUTextureFormat.RG8Unorm ||
  40594. format === GPUTextureFormat.RG8Snorm ||
  40595. format === GPUTextureFormat.RG8Uint ||
  40596. format === GPUTextureFormat.RG8Sint ) return 2;
  40597. // 32-bit formats
  40598. if ( format === GPUTextureFormat.R32Uint ||
  40599. format === GPUTextureFormat.R32Sint ||
  40600. format === GPUTextureFormat.R32Float ||
  40601. format === GPUTextureFormat.RG16Uint ||
  40602. format === GPUTextureFormat.RG16Sint ||
  40603. format === GPUTextureFormat.RG16Float ||
  40604. format === GPUTextureFormat.RGBA8Unorm ||
  40605. format === GPUTextureFormat.RGBA8UnormSRGB ||
  40606. format === GPUTextureFormat.RGBA8Snorm ||
  40607. format === GPUTextureFormat.RGBA8Uint ||
  40608. format === GPUTextureFormat.RGBA8Sint ||
  40609. format === GPUTextureFormat.BGRA8Unorm ||
  40610. format === GPUTextureFormat.BGRA8UnormSRGB ||
  40611. // Packed 32-bit formats
  40612. format === GPUTextureFormat.RGB9E5UFloat ||
  40613. format === GPUTextureFormat.RGB10A2Unorm ||
  40614. format === GPUTextureFormat.RG11B10UFloat ||
  40615. format === GPUTextureFormat.Depth32Float ||
  40616. format === GPUTextureFormat.Depth24Plus ||
  40617. format === GPUTextureFormat.Depth24PlusStencil8 ||
  40618. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  40619. // 64-bit formats
  40620. if ( format === GPUTextureFormat.RG32Uint ||
  40621. format === GPUTextureFormat.RG32Sint ||
  40622. format === GPUTextureFormat.RG32Float ||
  40623. format === GPUTextureFormat.RGBA16Uint ||
  40624. format === GPUTextureFormat.RGBA16Sint ||
  40625. format === GPUTextureFormat.RGBA16Float ) return 8;
  40626. // 128-bit formats
  40627. if ( format === GPUTextureFormat.RGBA32Uint ||
  40628. format === GPUTextureFormat.RGBA32Sint ||
  40629. format === GPUTextureFormat.RGBA32Float ) return 16;
  40630. }
  40631. _getTypedArrayType( format ) {
  40632. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  40633. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  40634. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  40635. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  40636. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  40637. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  40638. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  40639. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  40640. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  40641. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  40642. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  40643. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  40644. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  40645. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  40646. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  40647. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  40648. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  40649. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  40650. if ( format === GPUTextureFormat.R16Float ) return Float32Array;
  40651. if ( format === GPUTextureFormat.RG16Float ) return Float32Array;
  40652. if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array;
  40653. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  40654. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  40655. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  40656. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  40657. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  40658. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  40659. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  40660. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  40661. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  40662. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  40663. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  40664. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  40665. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  40666. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  40667. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  40668. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  40669. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  40670. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  40671. }
  40672. _getDimension( texture ) {
  40673. let dimension;
  40674. if ( texture.isData3DTexture ) {
  40675. dimension = GPUTextureDimension.ThreeD;
  40676. } else {
  40677. dimension = GPUTextureDimension.TwoD;
  40678. }
  40679. return dimension;
  40680. }
  40681. }
  40682. function getFormat( texture, device = null ) {
  40683. const format = texture.format;
  40684. const type = texture.type;
  40685. const colorSpace = texture.colorSpace;
  40686. let formatGPU;
  40687. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  40688. formatGPU = GPUTextureFormat.BGRA8Unorm;
  40689. } else if ( texture.isCompressedTexture === true ) {
  40690. switch ( format ) {
  40691. case RGBA_S3TC_DXT1_Format:
  40692. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  40693. break;
  40694. case RGBA_S3TC_DXT3_Format:
  40695. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  40696. break;
  40697. case RGBA_S3TC_DXT5_Format:
  40698. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  40699. break;
  40700. case RGB_ETC2_Format:
  40701. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  40702. break;
  40703. case RGBA_ETC2_EAC_Format:
  40704. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  40705. break;
  40706. case RGBA_ASTC_4x4_Format:
  40707. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  40708. break;
  40709. case RGBA_ASTC_5x4_Format:
  40710. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  40711. break;
  40712. case RGBA_ASTC_5x5_Format:
  40713. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  40714. break;
  40715. case RGBA_ASTC_6x5_Format:
  40716. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  40717. break;
  40718. case RGBA_ASTC_6x6_Format:
  40719. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  40720. break;
  40721. case RGBA_ASTC_8x5_Format:
  40722. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  40723. break;
  40724. case RGBA_ASTC_8x6_Format:
  40725. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  40726. break;
  40727. case RGBA_ASTC_8x8_Format:
  40728. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  40729. break;
  40730. case RGBA_ASTC_10x5_Format:
  40731. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  40732. break;
  40733. case RGBA_ASTC_10x6_Format:
  40734. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  40735. break;
  40736. case RGBA_ASTC_10x8_Format:
  40737. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  40738. break;
  40739. case RGBA_ASTC_10x10_Format:
  40740. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  40741. break;
  40742. case RGBA_ASTC_12x10_Format:
  40743. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  40744. break;
  40745. case RGBA_ASTC_12x12_Format:
  40746. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  40747. break;
  40748. default:
  40749. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40750. }
  40751. } else {
  40752. switch ( format ) {
  40753. case RGBAFormat:
  40754. switch ( type ) {
  40755. case ByteType:
  40756. formatGPU = GPUTextureFormat.RGBA8Snorm;
  40757. break;
  40758. case ShortType:
  40759. formatGPU = GPUTextureFormat.RGBA16Sint;
  40760. break;
  40761. case UnsignedShortType:
  40762. formatGPU = GPUTextureFormat.RGBA16Uint;
  40763. break;
  40764. case UnsignedIntType:
  40765. formatGPU = GPUTextureFormat.RGBA32Uint;
  40766. break;
  40767. case IntType:
  40768. formatGPU = GPUTextureFormat.RGBA32Sint;
  40769. break;
  40770. case UnsignedByteType:
  40771. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  40772. break;
  40773. case HalfFloatType:
  40774. formatGPU = GPUTextureFormat.RGBA16Float;
  40775. break;
  40776. case FloatType:
  40777. formatGPU = GPUTextureFormat.RGBA32Float;
  40778. break;
  40779. default:
  40780. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  40781. }
  40782. break;
  40783. case RGBFormat:
  40784. switch ( type ) {
  40785. case UnsignedInt5999Type:
  40786. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  40787. break;
  40788. default:
  40789. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  40790. }
  40791. break;
  40792. case RedFormat:
  40793. switch ( type ) {
  40794. case ByteType:
  40795. formatGPU = GPUTextureFormat.R8Snorm;
  40796. break;
  40797. case ShortType:
  40798. formatGPU = GPUTextureFormat.R16Sint;
  40799. break;
  40800. case UnsignedShortType:
  40801. formatGPU = GPUTextureFormat.R16Uint;
  40802. break;
  40803. case UnsignedIntType:
  40804. formatGPU = GPUTextureFormat.R32Uint;
  40805. break;
  40806. case IntType:
  40807. formatGPU = GPUTextureFormat.R32Sint;
  40808. break;
  40809. case UnsignedByteType:
  40810. formatGPU = GPUTextureFormat.R8Unorm;
  40811. break;
  40812. case HalfFloatType:
  40813. formatGPU = GPUTextureFormat.R16Float;
  40814. break;
  40815. case FloatType:
  40816. formatGPU = GPUTextureFormat.R32Float;
  40817. break;
  40818. default:
  40819. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  40820. }
  40821. break;
  40822. case RGFormat:
  40823. switch ( type ) {
  40824. case ByteType:
  40825. formatGPU = GPUTextureFormat.RG8Snorm;
  40826. break;
  40827. case ShortType:
  40828. formatGPU = GPUTextureFormat.RG16Sint;
  40829. break;
  40830. case UnsignedShortType:
  40831. formatGPU = GPUTextureFormat.RG16Uint;
  40832. break;
  40833. case UnsignedIntType:
  40834. formatGPU = GPUTextureFormat.RG32Uint;
  40835. break;
  40836. case IntType:
  40837. formatGPU = GPUTextureFormat.RG32Sint;
  40838. break;
  40839. case UnsignedByteType:
  40840. formatGPU = GPUTextureFormat.RG8Unorm;
  40841. break;
  40842. case HalfFloatType:
  40843. formatGPU = GPUTextureFormat.RG16Float;
  40844. break;
  40845. case FloatType:
  40846. formatGPU = GPUTextureFormat.RG32Float;
  40847. break;
  40848. default:
  40849. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  40850. }
  40851. break;
  40852. case DepthFormat:
  40853. switch ( type ) {
  40854. case UnsignedShortType:
  40855. formatGPU = GPUTextureFormat.Depth16Unorm;
  40856. break;
  40857. case UnsignedIntType:
  40858. formatGPU = GPUTextureFormat.Depth24Plus;
  40859. break;
  40860. case FloatType:
  40861. formatGPU = GPUTextureFormat.Depth32Float;
  40862. break;
  40863. default:
  40864. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  40865. }
  40866. break;
  40867. case DepthStencilFormat:
  40868. switch ( type ) {
  40869. case UnsignedInt248Type:
  40870. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  40871. break;
  40872. case FloatType:
  40873. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  40874. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  40875. }
  40876. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  40877. break;
  40878. default:
  40879. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  40880. }
  40881. break;
  40882. case RedIntegerFormat:
  40883. switch ( type ) {
  40884. case IntType:
  40885. formatGPU = GPUTextureFormat.R32Sint;
  40886. break;
  40887. case UnsignedIntType:
  40888. formatGPU = GPUTextureFormat.R32Uint;
  40889. break;
  40890. default:
  40891. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  40892. }
  40893. break;
  40894. case RGIntegerFormat:
  40895. switch ( type ) {
  40896. case IntType:
  40897. formatGPU = GPUTextureFormat.RG32Sint;
  40898. break;
  40899. case UnsignedIntType:
  40900. formatGPU = GPUTextureFormat.RG32Uint;
  40901. break;
  40902. default:
  40903. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  40904. }
  40905. break;
  40906. case RGBAIntegerFormat:
  40907. switch ( type ) {
  40908. case IntType:
  40909. formatGPU = GPUTextureFormat.RGBA32Sint;
  40910. break;
  40911. case UnsignedIntType:
  40912. formatGPU = GPUTextureFormat.RGBA32Uint;
  40913. break;
  40914. default:
  40915. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  40916. }
  40917. break;
  40918. default:
  40919. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40920. }
  40921. }
  40922. return formatGPU;
  40923. }
  40924. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  40925. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  40926. const wgslTypeLib$1 = {
  40927. 'f32': 'float',
  40928. 'i32': 'int',
  40929. 'u32': 'uint',
  40930. 'bool': 'bool',
  40931. 'vec2<f32>': 'vec2',
  40932. 'vec2<i32>': 'ivec2',
  40933. 'vec2<u32>': 'uvec2',
  40934. 'vec2<bool>': 'bvec2',
  40935. 'vec2f': 'vec2',
  40936. 'vec2i': 'ivec2',
  40937. 'vec2u': 'uvec2',
  40938. 'vec2b': 'bvec2',
  40939. 'vec3<f32>': 'vec3',
  40940. 'vec3<i32>': 'ivec3',
  40941. 'vec3<u32>': 'uvec3',
  40942. 'vec3<bool>': 'bvec3',
  40943. 'vec3f': 'vec3',
  40944. 'vec3i': 'ivec3',
  40945. 'vec3u': 'uvec3',
  40946. 'vec3b': 'bvec3',
  40947. 'vec4<f32>': 'vec4',
  40948. 'vec4<i32>': 'ivec4',
  40949. 'vec4<u32>': 'uvec4',
  40950. 'vec4<bool>': 'bvec4',
  40951. 'vec4f': 'vec4',
  40952. 'vec4i': 'ivec4',
  40953. 'vec4u': 'uvec4',
  40954. 'vec4b': 'bvec4',
  40955. 'mat2x2<f32>': 'mat2',
  40956. 'mat2x2f': 'mat2',
  40957. 'mat3x3<f32>': 'mat3',
  40958. 'mat3x3f': 'mat3',
  40959. 'mat4x4<f32>': 'mat4',
  40960. 'mat4x4f': 'mat4',
  40961. 'sampler': 'sampler',
  40962. 'texture_2d': 'texture',
  40963. 'texture_cube': 'cubeTexture',
  40964. 'texture_depth_2d': 'depthTexture',
  40965. 'texture_storage_2d': 'storageTexture',
  40966. 'texture_3d': 'texture3D'
  40967. };
  40968. const parse = ( source ) => {
  40969. source = source.trim();
  40970. const declaration = source.match( declarationRegexp );
  40971. if ( declaration !== null && declaration.length === 4 ) {
  40972. const inputsCode = declaration[ 2 ];
  40973. const propsMatches = [];
  40974. let match = null;
  40975. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  40976. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  40977. }
  40978. // Process matches to correctly pair names and types
  40979. const inputs = [];
  40980. for ( let i = 0; i < propsMatches.length; i ++ ) {
  40981. const { name, type } = propsMatches[ i ];
  40982. let resolvedType = type;
  40983. if ( resolvedType.startsWith( 'texture' ) ) {
  40984. resolvedType = type.split( '<' )[ 0 ];
  40985. }
  40986. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  40987. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  40988. }
  40989. const blockCode = source.substring( declaration[ 0 ].length );
  40990. const outputType = declaration[ 3 ] || 'void';
  40991. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  40992. const type = wgslTypeLib$1[ outputType ] || outputType;
  40993. return {
  40994. type,
  40995. inputs,
  40996. name,
  40997. inputsCode,
  40998. blockCode,
  40999. outputType
  41000. };
  41001. } else {
  41002. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  41003. }
  41004. };
  41005. class WGSLNodeFunction extends NodeFunction {
  41006. constructor( source ) {
  41007. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  41008. super( type, inputs, name );
  41009. this.inputsCode = inputsCode;
  41010. this.blockCode = blockCode;
  41011. this.outputType = outputType;
  41012. }
  41013. getCode( name = this.name ) {
  41014. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  41015. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  41016. }
  41017. }
  41018. class WGSLNodeParser extends NodeParser {
  41019. parseFunction( source ) {
  41020. return new WGSLNodeFunction( source );
  41021. }
  41022. }
  41023. // GPUShaderStage is not defined in browsers not supporting WebGPU
  41024. const GPUShaderStage = self.GPUShaderStage;
  41025. const gpuShaderStageLib = {
  41026. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  41027. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  41028. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  41029. };
  41030. const supports = {
  41031. instance: true,
  41032. swizzleAssign: false,
  41033. storageBuffer: true
  41034. };
  41035. const wgslFnOpLib = {
  41036. '^^': 'threejs_xor'
  41037. };
  41038. const wgslTypeLib = {
  41039. float: 'f32',
  41040. int: 'i32',
  41041. uint: 'u32',
  41042. bool: 'bool',
  41043. color: 'vec3<f32>',
  41044. vec2: 'vec2<f32>',
  41045. ivec2: 'vec2<i32>',
  41046. uvec2: 'vec2<u32>',
  41047. bvec2: 'vec2<bool>',
  41048. vec3: 'vec3<f32>',
  41049. ivec3: 'vec3<i32>',
  41050. uvec3: 'vec3<u32>',
  41051. bvec3: 'vec3<bool>',
  41052. vec4: 'vec4<f32>',
  41053. ivec4: 'vec4<i32>',
  41054. uvec4: 'vec4<u32>',
  41055. bvec4: 'vec4<bool>',
  41056. mat2: 'mat2x2<f32>',
  41057. imat2: 'mat2x2<i32>',
  41058. umat2: 'mat2x2<u32>',
  41059. bmat2: 'mat2x2<bool>',
  41060. mat3: 'mat3x3<f32>',
  41061. imat3: 'mat3x3<i32>',
  41062. umat3: 'mat3x3<u32>',
  41063. bmat3: 'mat3x3<bool>',
  41064. mat4: 'mat4x4<f32>',
  41065. imat4: 'mat4x4<i32>',
  41066. umat4: 'mat4x4<u32>',
  41067. bmat4: 'mat4x4<bool>'
  41068. };
  41069. const wgslMethods = {
  41070. dFdx: 'dpdx',
  41071. dFdy: '- dpdy',
  41072. mod_float: 'threejs_mod_float',
  41073. mod_vec2: 'threejs_mod_vec2',
  41074. mod_vec3: 'threejs_mod_vec3',
  41075. mod_vec4: 'threejs_mod_vec4',
  41076. equals_bool: 'threejs_equals_bool',
  41077. equals_bvec2: 'threejs_equals_bvec2',
  41078. equals_bvec3: 'threejs_equals_bvec3',
  41079. equals_bvec4: 'threejs_equals_bvec4',
  41080. lessThanEqual: 'threejs_lessThanEqual',
  41081. greaterThan: 'threejs_greaterThan',
  41082. inversesqrt: 'inverseSqrt',
  41083. bitcast: 'bitcast<f32>'
  41084. };
  41085. const wgslPolyfill = {
  41086. threejs_xor: new CodeNode( `
  41087. fn threejs_xor( a : bool, b : bool ) -> bool {
  41088. return ( a || b ) && !( a && b );
  41089. }
  41090. ` ),
  41091. lessThanEqual: new CodeNode( `
  41092. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  41093. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  41094. }
  41095. ` ),
  41096. greaterThan: new CodeNode( `
  41097. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  41098. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  41099. }
  41100. ` ),
  41101. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  41102. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  41103. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  41104. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  41105. equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  41106. 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 ); }' ),
  41107. 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 ); }' ),
  41108. 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 ); }' ),
  41109. repeatWrapping: new CodeNode( `
  41110. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  41111. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  41112. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  41113. }
  41114. ` ),
  41115. biquadraticTexture: new CodeNode( `
  41116. fn threejs_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  41117. let res = vec2f( textureDimensions( map, level ) );
  41118. let uvScaled = coord * res;
  41119. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  41120. // https://www.shadertoy.com/view/WtyXRy
  41121. let uv = uvWrapping - 0.5;
  41122. let iuv = floor( uv );
  41123. let f = fract( uv );
  41124. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  41125. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  41126. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  41127. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  41128. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  41129. }
  41130. ` )
  41131. };
  41132. class WGSLNodeBuilder extends NodeBuilder {
  41133. constructor( object, renderer ) {
  41134. super( object, renderer, new WGSLNodeParser() );
  41135. this.uniformGroups = {};
  41136. this.builtins = {};
  41137. }
  41138. needsColorSpaceToLinear( texture ) {
  41139. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  41140. }
  41141. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41142. if ( shaderStage === 'fragment' ) {
  41143. if ( depthSnippet ) {
  41144. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  41145. } else {
  41146. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  41147. }
  41148. } else if ( this.isFilteredTexture( texture ) ) {
  41149. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  41150. } else {
  41151. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  41152. }
  41153. }
  41154. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  41155. if ( shaderStage === 'fragment' ) {
  41156. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  41157. } else {
  41158. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  41159. }
  41160. }
  41161. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41162. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  41163. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  41164. } else if ( this.isFilteredTexture( texture ) ) {
  41165. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  41166. } else {
  41167. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  41168. }
  41169. }
  41170. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  41171. this._include( 'biquadraticTexture' );
  41172. return `threejs_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  41173. }
  41174. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  41175. this._include( 'repeatWrapping' );
  41176. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  41177. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  41178. }
  41179. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  41180. if ( depthSnippet ) {
  41181. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  41182. } else {
  41183. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  41184. }
  41185. }
  41186. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  41187. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  41188. }
  41189. isUnfilterable( texture ) {
  41190. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  41191. }
  41192. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41193. let snippet = null;
  41194. if ( texture.isVideoTexture === true ) {
  41195. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  41196. } else if ( this.isUnfilterable( texture ) ) {
  41197. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  41198. } else {
  41199. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  41200. }
  41201. return snippet;
  41202. }
  41203. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41204. if ( shaderStage === 'fragment' ) {
  41205. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  41206. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  41207. } else {
  41208. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  41209. }
  41210. }
  41211. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41212. if ( shaderStage === 'fragment' ) {
  41213. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  41214. } else {
  41215. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  41216. }
  41217. }
  41218. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41219. let snippet = null;
  41220. if ( texture.isVideoTexture === true ) {
  41221. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  41222. } else {
  41223. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  41224. }
  41225. return snippet;
  41226. }
  41227. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41228. if ( shaderStage === 'fragment' ) {
  41229. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  41230. } else {
  41231. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  41232. }
  41233. }
  41234. getPropertyName( node, shaderStage = this.shaderStage ) {
  41235. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  41236. if ( shaderStage === 'vertex' ) {
  41237. return `varyings.${ node.name }`;
  41238. }
  41239. } else if ( node.isNodeUniform === true ) {
  41240. const name = node.name;
  41241. const type = node.type;
  41242. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  41243. return name;
  41244. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  41245. return `NodeBuffer_${ node.id }.${name}`;
  41246. } else {
  41247. return node.groupNode.name + '.' + name;
  41248. }
  41249. }
  41250. return super.getPropertyName( node );
  41251. }
  41252. getOutputStructName() {
  41253. return 'output';
  41254. }
  41255. _getUniformGroupCount( shaderStage ) {
  41256. return Object.keys( this.uniforms[ shaderStage ] ).length;
  41257. }
  41258. getFunctionOperator( op ) {
  41259. const fnOp = wgslFnOpLib[ op ];
  41260. if ( fnOp !== undefined ) {
  41261. this._include( fnOp );
  41262. return fnOp;
  41263. }
  41264. return null;
  41265. }
  41266. getStorageAccess( node ) {
  41267. if ( node.isStorageTextureNode ) {
  41268. switch ( node.access ) {
  41269. case GPUStorageTextureAccess.ReadOnly:
  41270. return 'read';
  41271. case GPUStorageTextureAccess.WriteOnly:
  41272. return 'write';
  41273. default:
  41274. return 'read_write';
  41275. }
  41276. } else {
  41277. switch ( node.access ) {
  41278. case GPUBufferBindingType.Storage:
  41279. return 'read_write';
  41280. case GPUBufferBindingType.ReadOnlyStorage:
  41281. return 'read';
  41282. default:
  41283. return 'write';
  41284. }
  41285. }
  41286. }
  41287. getUniformFromNode( node, type, shaderStage, name = null ) {
  41288. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  41289. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  41290. if ( nodeData.uniformGPU === undefined ) {
  41291. let uniformGPU;
  41292. const group = node.groupNode;
  41293. const groupName = group.name;
  41294. const bindings = this.getBindGroupArray( groupName, shaderStage );
  41295. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  41296. let texture = null;
  41297. if ( type === 'texture' || type === 'storageTexture' ) {
  41298. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  41299. } else if ( type === 'cubeTexture' ) {
  41300. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  41301. } else if ( type === 'texture3D' ) {
  41302. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  41303. }
  41304. texture.store = node.isStorageTextureNode === true;
  41305. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41306. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  41307. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  41308. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41309. bindings.push( sampler, texture );
  41310. uniformGPU = [ sampler, texture ];
  41311. } else {
  41312. bindings.push( texture );
  41313. uniformGPU = [ texture ];
  41314. }
  41315. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  41316. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  41317. const buffer = new bufferClass( node, group );
  41318. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41319. bindings.push( buffer );
  41320. uniformGPU = buffer;
  41321. } else {
  41322. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  41323. let uniformsGroup = uniformsStage[ groupName ];
  41324. if ( uniformsGroup === undefined ) {
  41325. uniformsGroup = new NodeUniformsGroup( groupName, group );
  41326. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41327. uniformsStage[ groupName ] = uniformsGroup;
  41328. bindings.push( uniformsGroup );
  41329. }
  41330. uniformGPU = this.getNodeUniform( uniformNode, type );
  41331. uniformsGroup.addUniform( uniformGPU );
  41332. }
  41333. nodeData.uniformGPU = uniformGPU;
  41334. }
  41335. return uniformNode;
  41336. }
  41337. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  41338. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  41339. if ( map.has( name ) === false ) {
  41340. map.set( name, {
  41341. name,
  41342. property,
  41343. type
  41344. } );
  41345. }
  41346. return property;
  41347. }
  41348. getVertexIndex() {
  41349. if ( this.shaderStage === 'vertex' ) {
  41350. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  41351. }
  41352. return 'vertexIndex';
  41353. }
  41354. buildFunctionCode( shaderNode ) {
  41355. const layout = shaderNode.layout;
  41356. const flowData = this.flowShaderNode( shaderNode );
  41357. const parameters = [];
  41358. for ( const input of layout.inputs ) {
  41359. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  41360. }
  41361. //
  41362. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  41363. ${ flowData.vars }
  41364. ${ flowData.code }
  41365. return ${ flowData.result };
  41366. }`;
  41367. //
  41368. return code;
  41369. }
  41370. getInstanceIndex() {
  41371. if ( this.shaderStage === 'vertex' ) {
  41372. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  41373. }
  41374. return 'instanceIndex';
  41375. }
  41376. getDrawIndex() {
  41377. return null;
  41378. }
  41379. getFrontFacing() {
  41380. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  41381. }
  41382. getFragCoord() {
  41383. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xyz';
  41384. }
  41385. getFragDepth() {
  41386. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  41387. }
  41388. isFlipY() {
  41389. return false;
  41390. }
  41391. getBuiltins( shaderStage ) {
  41392. const snippets = [];
  41393. const builtins = this.builtins[ shaderStage ];
  41394. if ( builtins !== undefined ) {
  41395. for ( const { name, property, type } of builtins.values() ) {
  41396. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  41397. }
  41398. }
  41399. return snippets.join( ',\n\t' );
  41400. }
  41401. getAttributes( shaderStage ) {
  41402. const snippets = [];
  41403. if ( shaderStage === 'compute' ) {
  41404. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  41405. }
  41406. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41407. const builtins = this.getBuiltins( 'attribute' );
  41408. if ( builtins ) snippets.push( builtins );
  41409. const attributes = this.getAttributesArray();
  41410. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  41411. const attribute = attributes[ index ];
  41412. const name = attribute.name;
  41413. const type = this.getType( attribute.type );
  41414. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  41415. }
  41416. }
  41417. return snippets.join( ',\n\t' );
  41418. }
  41419. getStructMembers( struct ) {
  41420. const snippets = [];
  41421. const members = struct.getMemberTypes();
  41422. for ( let i = 0; i < members.length; i ++ ) {
  41423. const member = members[ i ];
  41424. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  41425. }
  41426. const builtins = this.getBuiltins( 'output' );
  41427. if ( builtins ) snippets.push( builtins );
  41428. return snippets.join( ',\n' );
  41429. }
  41430. getStructs( shaderStage ) {
  41431. const snippets = [];
  41432. const structs = this.structs[ shaderStage ];
  41433. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  41434. const struct = structs[ index ];
  41435. const name = struct.name;
  41436. let snippet = `\struct ${ name } {\n`;
  41437. snippet += this.getStructMembers( struct );
  41438. snippet += '\n}';
  41439. snippets.push( snippet );
  41440. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  41441. }
  41442. return snippets.join( '\n\n' );
  41443. }
  41444. getVar( type, name ) {
  41445. return `var ${ name } : ${ this.getType( type ) }`;
  41446. }
  41447. getVars( shaderStage ) {
  41448. const snippets = [];
  41449. const vars = this.vars[ shaderStage ];
  41450. if ( vars !== undefined ) {
  41451. for ( const variable of vars ) {
  41452. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  41453. }
  41454. }
  41455. return `\n${ snippets.join( '\n' ) }\n`;
  41456. }
  41457. getVaryings( shaderStage ) {
  41458. const snippets = [];
  41459. if ( shaderStage === 'vertex' ) {
  41460. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  41461. }
  41462. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  41463. const varyings = this.varyings;
  41464. const vars = this.vars[ shaderStage ];
  41465. for ( let index = 0; index < varyings.length; index ++ ) {
  41466. const varying = varyings[ index ];
  41467. if ( varying.needsInterpolation ) {
  41468. let attributesSnippet = `@location( ${index} )`;
  41469. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  41470. attributesSnippet += ' @interpolate( flat )';
  41471. }
  41472. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  41473. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  41474. vars.push( varying );
  41475. }
  41476. }
  41477. }
  41478. const builtins = this.getBuiltins( shaderStage );
  41479. if ( builtins ) snippets.push( builtins );
  41480. const code = snippets.join( ',\n\t' );
  41481. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  41482. }
  41483. getUniforms( shaderStage ) {
  41484. const uniforms = this.uniforms[ shaderStage ];
  41485. const bindingSnippets = [];
  41486. const bufferSnippets = [];
  41487. const structSnippets = [];
  41488. const uniformGroups = {};
  41489. for ( const uniform of uniforms ) {
  41490. const groundName = uniform.groupNode.name;
  41491. const uniformIndexes = this.bindingsIndexes[ groundName ];
  41492. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  41493. const texture = uniform.node.value;
  41494. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  41495. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  41496. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  41497. } else {
  41498. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  41499. }
  41500. }
  41501. let textureType;
  41502. let multisampled = '';
  41503. if ( texture.isMultisampleRenderTargetTexture === true ) {
  41504. multisampled = '_multisampled';
  41505. }
  41506. if ( texture.isCubeTexture === true ) {
  41507. textureType = 'texture_cube<f32>';
  41508. } else if ( texture.isDataArrayTexture === true ) {
  41509. textureType = 'texture_2d_array<f32>';
  41510. } else if ( texture.isDepthTexture === true ) {
  41511. textureType = `texture_depth${multisampled}_2d`;
  41512. } else if ( texture.isVideoTexture === true ) {
  41513. textureType = 'texture_external';
  41514. } else if ( texture.isData3DTexture === true ) {
  41515. textureType = 'texture_3d<f32>';
  41516. } else if ( uniform.node.isStorageTextureNode === true ) {
  41517. const format = getFormat( texture );
  41518. const access = this.getStorageAccess( uniform.node );
  41519. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  41520. } else {
  41521. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  41522. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  41523. }
  41524. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  41525. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  41526. const bufferNode = uniform.node;
  41527. const bufferType = this.getType( bufferNode.bufferType );
  41528. const bufferCount = bufferNode.bufferCount;
  41529. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  41530. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferType }${ bufferCountSnippet } >\n`;
  41531. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  41532. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  41533. } else {
  41534. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  41535. const groupName = uniform.groupNode.name;
  41536. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  41537. index: uniformIndexes.binding ++,
  41538. id: uniformIndexes.group,
  41539. snippets: []
  41540. } );
  41541. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  41542. }
  41543. }
  41544. for ( const name in uniformGroups ) {
  41545. const group = uniformGroups[ name ];
  41546. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  41547. }
  41548. let code = bindingSnippets.join( '\n' );
  41549. code += bufferSnippets.join( '\n' );
  41550. code += structSnippets.join( '\n' );
  41551. return code;
  41552. }
  41553. buildCode() {
  41554. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  41555. for ( const shaderStage in shadersData ) {
  41556. const stageData = shadersData[ shaderStage ];
  41557. stageData.uniforms = this.getUniforms( shaderStage );
  41558. stageData.attributes = this.getAttributes( shaderStage );
  41559. stageData.varyings = this.getVaryings( shaderStage );
  41560. stageData.structs = this.getStructs( shaderStage );
  41561. stageData.vars = this.getVars( shaderStage );
  41562. stageData.codes = this.getCodes( shaderStage );
  41563. //
  41564. let flow = '// code\n\n';
  41565. flow += this.flowCode[ shaderStage ];
  41566. const flowNodes = this.flowNodes[ shaderStage ];
  41567. const mainNode = flowNodes[ flowNodes.length - 1 ];
  41568. const outputNode = mainNode.outputNode;
  41569. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  41570. for ( const node of flowNodes ) {
  41571. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  41572. const slotName = node.name;
  41573. if ( slotName ) {
  41574. if ( flow.length > 0 ) flow += '\n';
  41575. flow += `\t// flow -> ${ slotName }\n\t`;
  41576. }
  41577. flow += `${ flowSlotData.code }\n\t`;
  41578. if ( node === mainNode && shaderStage !== 'compute' ) {
  41579. flow += '// result\n\n\t';
  41580. if ( shaderStage === 'vertex' ) {
  41581. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  41582. } else if ( shaderStage === 'fragment' ) {
  41583. if ( isOutputStruct ) {
  41584. stageData.returnType = outputNode.nodeType;
  41585. flow += `return ${ flowSlotData.result };`;
  41586. } else {
  41587. let structSnippet = '\t@location(0) color: vec4<f32>';
  41588. const builtins = this.getBuiltins( 'output' );
  41589. if ( builtins ) structSnippet += ',\n\t' + builtins;
  41590. stageData.returnType = 'OutputStruct';
  41591. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  41592. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  41593. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  41594. }
  41595. }
  41596. }
  41597. }
  41598. stageData.flow = flow;
  41599. }
  41600. if ( this.material !== null ) {
  41601. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  41602. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  41603. } else {
  41604. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  41605. }
  41606. }
  41607. getMethod( method, output = null ) {
  41608. let wgslMethod;
  41609. if ( output !== null ) {
  41610. wgslMethod = this._getWGSLMethod( method + '_' + output );
  41611. }
  41612. if ( wgslMethod === undefined ) {
  41613. wgslMethod = this._getWGSLMethod( method );
  41614. }
  41615. return wgslMethod || method;
  41616. }
  41617. getType( type ) {
  41618. return wgslTypeLib[ type ] || type;
  41619. }
  41620. isAvailable( name ) {
  41621. let result = supports[ name ];
  41622. if ( result === undefined ) {
  41623. if ( name === 'float32Filterable' ) {
  41624. result = this.renderer.hasFeature( 'float32-filterable' );
  41625. }
  41626. supports[ name ] = result;
  41627. }
  41628. return result;
  41629. }
  41630. _getWGSLMethod( method ) {
  41631. if ( wgslPolyfill[ method ] !== undefined ) {
  41632. this._include( method );
  41633. }
  41634. return wgslMethods[ method ];
  41635. }
  41636. _include( name ) {
  41637. const codeNode = wgslPolyfill[ name ];
  41638. codeNode.build( this );
  41639. if ( this.currentFunctionNode !== null ) {
  41640. this.currentFunctionNode.includes.push( codeNode );
  41641. }
  41642. return codeNode;
  41643. }
  41644. _getWGSLVertexCode( shaderData ) {
  41645. return `${ this.getSignature() }
  41646. // uniforms
  41647. ${shaderData.uniforms}
  41648. // varyings
  41649. ${shaderData.varyings}
  41650. var<private> varyings : VaryingsStruct;
  41651. // codes
  41652. ${shaderData.codes}
  41653. @vertex
  41654. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  41655. // vars
  41656. ${shaderData.vars}
  41657. // flow
  41658. ${shaderData.flow}
  41659. return varyings;
  41660. }
  41661. `;
  41662. }
  41663. _getWGSLFragmentCode( shaderData ) {
  41664. return `${ this.getSignature() }
  41665. // uniforms
  41666. ${shaderData.uniforms}
  41667. // structs
  41668. ${shaderData.structs}
  41669. // codes
  41670. ${shaderData.codes}
  41671. @fragment
  41672. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  41673. // vars
  41674. ${shaderData.vars}
  41675. // flow
  41676. ${shaderData.flow}
  41677. }
  41678. `;
  41679. }
  41680. _getWGSLComputeCode( shaderData, workgroupSize ) {
  41681. return `${ this.getSignature() }
  41682. // system
  41683. var<private> instanceIndex : u32;
  41684. // uniforms
  41685. ${shaderData.uniforms}
  41686. // codes
  41687. ${shaderData.codes}
  41688. @compute @workgroup_size( ${workgroupSize} )
  41689. fn main( ${shaderData.attributes} ) {
  41690. // system
  41691. instanceIndex = id.x;
  41692. // vars
  41693. ${shaderData.vars}
  41694. // flow
  41695. ${shaderData.flow}
  41696. }
  41697. `;
  41698. }
  41699. _getWGSLStruct( name, vars ) {
  41700. return `
  41701. struct ${name} {
  41702. ${vars}
  41703. };`;
  41704. }
  41705. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  41706. const structName = name + 'Struct';
  41707. const structSnippet = this._getWGSLStruct( structName, vars );
  41708. return `${structSnippet}
  41709. @binding( ${binding} ) @group( ${group} )
  41710. var<${access}> ${name} : ${structName};`;
  41711. }
  41712. }
  41713. class WebGPUUtils {
  41714. constructor( backend ) {
  41715. this.backend = backend;
  41716. }
  41717. getCurrentDepthStencilFormat( renderContext ) {
  41718. let format;
  41719. if ( renderContext.depthTexture !== null ) {
  41720. format = this.getTextureFormatGPU( renderContext.depthTexture );
  41721. } else if ( renderContext.depth && renderContext.stencil ) {
  41722. format = GPUTextureFormat.Depth24PlusStencil8;
  41723. } else if ( renderContext.depth ) {
  41724. format = GPUTextureFormat.Depth24Plus;
  41725. }
  41726. return format;
  41727. }
  41728. getTextureFormatGPU( texture ) {
  41729. return this.backend.get( texture ).texture.format;
  41730. }
  41731. getCurrentColorFormat( renderContext ) {
  41732. let format;
  41733. if ( renderContext.textures !== null ) {
  41734. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  41735. } else {
  41736. format = GPUTextureFormat.BGRA8Unorm; // default context format
  41737. }
  41738. return format;
  41739. }
  41740. getCurrentColorSpace( renderContext ) {
  41741. if ( renderContext.textures !== null ) {
  41742. return renderContext.textures[ 0 ].colorSpace;
  41743. }
  41744. return this.backend.renderer.outputColorSpace;
  41745. }
  41746. getPrimitiveTopology( object, material ) {
  41747. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  41748. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  41749. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  41750. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  41751. }
  41752. getSampleCount( sampleCount ) {
  41753. let count = 1;
  41754. if ( sampleCount > 1 ) {
  41755. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  41756. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  41757. if ( count === 2 ) {
  41758. count = 4;
  41759. }
  41760. }
  41761. return count;
  41762. }
  41763. getSampleCountRenderContext( renderContext ) {
  41764. if ( renderContext.textures !== null ) {
  41765. return this.getSampleCount( renderContext.sampleCount );
  41766. }
  41767. return this.getSampleCount( this.backend.renderer.samples );
  41768. }
  41769. }
  41770. const typedArraysToVertexFormatPrefix = new Map( [
  41771. [ Int8Array, [ 'sint8', 'snorm8' ]],
  41772. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  41773. [ Int16Array, [ 'sint16', 'snorm16' ]],
  41774. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  41775. [ Int32Array, [ 'sint32', 'snorm32' ]],
  41776. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  41777. [ Float32Array, [ 'float32', ]],
  41778. ] );
  41779. const typedAttributeToVertexFormatPrefix = new Map( [
  41780. [ Float16BufferAttribute, [ 'float16', ]],
  41781. ] );
  41782. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  41783. [ Int32Array, 'sint32' ],
  41784. [ Int16Array, 'sint32' ], // patch for INT16
  41785. [ Uint32Array, 'uint32' ],
  41786. [ Uint16Array, 'uint32' ], // patch for UINT16
  41787. [ Float32Array, 'float32' ]
  41788. ] );
  41789. class WebGPUAttributeUtils {
  41790. constructor( backend ) {
  41791. this.backend = backend;
  41792. }
  41793. createAttribute( attribute, usage ) {
  41794. const bufferAttribute = this._getBufferAttribute( attribute );
  41795. const backend = this.backend;
  41796. const bufferData = backend.get( bufferAttribute );
  41797. let buffer = bufferData.buffer;
  41798. if ( buffer === undefined ) {
  41799. const device = backend.device;
  41800. let array = bufferAttribute.array;
  41801. // patch for INT16 and UINT16
  41802. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  41803. const tempArray = new Uint32Array( array.length );
  41804. for ( let i = 0; i < array.length; i ++ ) {
  41805. tempArray[ i ] = array[ i ];
  41806. }
  41807. array = tempArray;
  41808. }
  41809. bufferAttribute.array = array;
  41810. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  41811. array = new array.constructor( bufferAttribute.count * 4 );
  41812. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  41813. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  41814. }
  41815. // Update BufferAttribute
  41816. bufferAttribute.itemSize = 4;
  41817. bufferAttribute.array = array;
  41818. }
  41819. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  41820. buffer = device.createBuffer( {
  41821. label: bufferAttribute.name,
  41822. size: size,
  41823. usage: usage,
  41824. mappedAtCreation: true
  41825. } );
  41826. new array.constructor( buffer.getMappedRange() ).set( array );
  41827. buffer.unmap();
  41828. bufferData.buffer = buffer;
  41829. }
  41830. }
  41831. updateAttribute( attribute ) {
  41832. const bufferAttribute = this._getBufferAttribute( attribute );
  41833. const backend = this.backend;
  41834. const device = backend.device;
  41835. const buffer = backend.get( bufferAttribute ).buffer;
  41836. const array = bufferAttribute.array;
  41837. const updateRanges = bufferAttribute.updateRanges;
  41838. if ( updateRanges.length === 0 ) {
  41839. // Not using update ranges
  41840. device.queue.writeBuffer(
  41841. buffer,
  41842. 0,
  41843. array,
  41844. 0
  41845. );
  41846. } else {
  41847. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41848. const range = updateRanges[ i ];
  41849. device.queue.writeBuffer(
  41850. buffer,
  41851. 0,
  41852. array,
  41853. range.start * array.BYTES_PER_ELEMENT,
  41854. range.count * array.BYTES_PER_ELEMENT
  41855. );
  41856. }
  41857. bufferAttribute.clearUpdateRanges();
  41858. }
  41859. }
  41860. createShaderVertexBuffers( renderObject ) {
  41861. const attributes = renderObject.getAttributes();
  41862. const vertexBuffers = new Map();
  41863. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  41864. const geometryAttribute = attributes[ slot ];
  41865. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  41866. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  41867. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  41868. if ( vertexBufferLayout === undefined ) {
  41869. let arrayStride, stepMode;
  41870. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  41871. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  41872. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41873. } else {
  41874. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  41875. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41876. }
  41877. // patch for INT16 and UINT16
  41878. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  41879. arrayStride = 4;
  41880. }
  41881. vertexBufferLayout = {
  41882. arrayStride,
  41883. attributes: [],
  41884. stepMode
  41885. };
  41886. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  41887. }
  41888. const format = this._getVertexFormat( geometryAttribute );
  41889. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  41890. vertexBufferLayout.attributes.push( {
  41891. shaderLocation: slot,
  41892. offset,
  41893. format
  41894. } );
  41895. }
  41896. return Array.from( vertexBuffers.values() );
  41897. }
  41898. destroyAttribute( attribute ) {
  41899. const backend = this.backend;
  41900. const data = backend.get( this._getBufferAttribute( attribute ) );
  41901. data.buffer.destroy();
  41902. backend.delete( attribute );
  41903. }
  41904. async getArrayBufferAsync( attribute ) {
  41905. const backend = this.backend;
  41906. const device = backend.device;
  41907. const data = backend.get( this._getBufferAttribute( attribute ) );
  41908. const bufferGPU = data.buffer;
  41909. const size = bufferGPU.size;
  41910. let readBufferGPU = data.readBuffer;
  41911. let needsUnmap = true;
  41912. if ( readBufferGPU === undefined ) {
  41913. readBufferGPU = device.createBuffer( {
  41914. label: attribute.name,
  41915. size,
  41916. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41917. } );
  41918. needsUnmap = false;
  41919. data.readBuffer = readBufferGPU;
  41920. }
  41921. const cmdEncoder = device.createCommandEncoder( {} );
  41922. cmdEncoder.copyBufferToBuffer(
  41923. bufferGPU,
  41924. 0,
  41925. readBufferGPU,
  41926. 0,
  41927. size
  41928. );
  41929. if ( needsUnmap ) readBufferGPU.unmap();
  41930. const gpuCommands = cmdEncoder.finish();
  41931. device.queue.submit( [ gpuCommands ] );
  41932. await readBufferGPU.mapAsync( GPUMapMode.READ );
  41933. const arrayBuffer = readBufferGPU.getMappedRange();
  41934. return arrayBuffer;
  41935. }
  41936. _getVertexFormat( geometryAttribute ) {
  41937. const { itemSize, normalized } = geometryAttribute;
  41938. const ArrayType = geometryAttribute.array.constructor;
  41939. const AttributeType = geometryAttribute.constructor;
  41940. let format;
  41941. if ( itemSize == 1 ) {
  41942. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  41943. } else {
  41944. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  41945. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  41946. if ( prefix ) {
  41947. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  41948. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  41949. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  41950. if ( paddedItemSize % 1 ) {
  41951. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  41952. }
  41953. format = `${prefix}x${paddedItemSize}`;
  41954. }
  41955. }
  41956. if ( ! format ) {
  41957. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  41958. }
  41959. return format;
  41960. }
  41961. _getBufferAttribute( attribute ) {
  41962. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  41963. return attribute;
  41964. }
  41965. }
  41966. class WebGPUBindingUtils {
  41967. constructor( backend ) {
  41968. this.backend = backend;
  41969. }
  41970. createBindingsLayout( bindGroup ) {
  41971. const backend = this.backend;
  41972. const device = backend.device;
  41973. const entries = [];
  41974. let index = 0;
  41975. for ( const binding of bindGroup.bindings ) {
  41976. const bindingGPU = {
  41977. binding: index ++,
  41978. visibility: binding.visibility
  41979. };
  41980. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  41981. const buffer = {}; // GPUBufferBindingLayout
  41982. if ( binding.isStorageBuffer ) {
  41983. buffer.type = binding.access;
  41984. }
  41985. bindingGPU.buffer = buffer;
  41986. } else if ( binding.isSampler ) {
  41987. const sampler = {}; // GPUSamplerBindingLayout
  41988. if ( binding.texture.isDepthTexture ) {
  41989. if ( binding.texture.compareFunction !== null ) {
  41990. sampler.type = 'comparison';
  41991. }
  41992. }
  41993. bindingGPU.sampler = sampler;
  41994. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  41995. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  41996. } else if ( binding.isSampledTexture && binding.store ) {
  41997. const format = this.backend.get( binding.texture ).texture.format;
  41998. const access = binding.access;
  41999. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  42000. } else if ( binding.isSampledTexture ) {
  42001. const texture = {}; // GPUTextureBindingLayout
  42002. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  42003. texture.multisampled = true;
  42004. }
  42005. if ( binding.texture.isDepthTexture ) {
  42006. texture.sampleType = GPUTextureSampleType.Depth;
  42007. } else if ( binding.texture.isDataTexture ) {
  42008. const type = binding.texture.type;
  42009. if ( type === IntType ) {
  42010. texture.sampleType = GPUTextureSampleType.SInt;
  42011. } else if ( type === UnsignedIntType ) {
  42012. texture.sampleType = GPUTextureSampleType.UInt;
  42013. } else if ( type === FloatType ) {
  42014. // @TODO: Add support for this soon: backend.hasFeature( 'float32-filterable' )
  42015. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  42016. }
  42017. }
  42018. if ( binding.isSampledCubeTexture ) {
  42019. texture.viewDimension = GPUTextureViewDimension.Cube;
  42020. } else if ( binding.texture.isDataArrayTexture ) {
  42021. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  42022. } else if ( binding.isSampledTexture3D ) {
  42023. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  42024. }
  42025. bindingGPU.texture = texture;
  42026. } else {
  42027. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  42028. }
  42029. entries.push( bindingGPU );
  42030. }
  42031. return device.createBindGroupLayout( { entries } );
  42032. }
  42033. createBindings( bindGroup ) {
  42034. const backend = this.backend;
  42035. const bindingsData = backend.get( bindGroup );
  42036. // setup (static) binding layout and (dynamic) binding group
  42037. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  42038. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  42039. bindingsData.layout = bindLayoutGPU;
  42040. bindingsData.group = bindGroupGPU;
  42041. }
  42042. updateBinding( binding ) {
  42043. const backend = this.backend;
  42044. const device = backend.device;
  42045. const buffer = binding.buffer;
  42046. const bufferGPU = backend.get( binding ).buffer;
  42047. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  42048. }
  42049. createBindGroup( bindGroup, layoutGPU ) {
  42050. const backend = this.backend;
  42051. const device = backend.device;
  42052. let bindingPoint = 0;
  42053. const entriesGPU = [];
  42054. for ( const binding of bindGroup.bindings ) {
  42055. if ( binding.isUniformBuffer ) {
  42056. const bindingData = backend.get( binding );
  42057. if ( bindingData.buffer === undefined ) {
  42058. const byteLength = binding.byteLength;
  42059. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  42060. const bufferGPU = device.createBuffer( {
  42061. label: 'bindingBuffer_' + binding.name,
  42062. size: byteLength,
  42063. usage: usage
  42064. } );
  42065. bindingData.buffer = bufferGPU;
  42066. }
  42067. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  42068. } else if ( binding.isStorageBuffer ) {
  42069. const bindingData = backend.get( binding );
  42070. if ( bindingData.buffer === undefined ) {
  42071. const attribute = binding.attribute;
  42072. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  42073. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  42074. bindingData.buffer = backend.get( attribute ).buffer;
  42075. }
  42076. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  42077. } else if ( binding.isSampler ) {
  42078. const textureGPU = backend.get( binding.texture );
  42079. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  42080. } else if ( binding.isSampledTexture ) {
  42081. const textureData = backend.get( binding.texture );
  42082. let dimensionViewGPU;
  42083. if ( binding.isSampledCubeTexture ) {
  42084. dimensionViewGPU = GPUTextureViewDimension.Cube;
  42085. } else if ( binding.isSampledTexture3D ) {
  42086. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  42087. } else if ( binding.texture.isDataArrayTexture ) {
  42088. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  42089. } else {
  42090. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  42091. }
  42092. let resourceGPU;
  42093. if ( textureData.externalTexture !== undefined ) {
  42094. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  42095. } else {
  42096. const aspectGPU = GPUTextureAspect.All;
  42097. resourceGPU = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount: binding.store ? 1 : textureData.mipLevelCount } );
  42098. }
  42099. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  42100. }
  42101. bindingPoint ++;
  42102. }
  42103. return device.createBindGroup( {
  42104. label: 'bindGroup_' + bindGroup.name,
  42105. layout: layoutGPU,
  42106. entries: entriesGPU
  42107. } );
  42108. }
  42109. }
  42110. class WebGPUPipelineUtils {
  42111. constructor( backend ) {
  42112. this.backend = backend;
  42113. }
  42114. _getSampleCount( renderObjectContext ) {
  42115. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  42116. }
  42117. createRenderPipeline( renderObject, promises ) {
  42118. const { object, material, geometry, pipeline } = renderObject;
  42119. const { vertexProgram, fragmentProgram } = pipeline;
  42120. const backend = this.backend;
  42121. const device = backend.device;
  42122. const utils = backend.utils;
  42123. const pipelineData = backend.get( pipeline );
  42124. // bind group layouts
  42125. const bindGroupLayouts = [];
  42126. for ( const bindGroup of renderObject.getBindings() ) {
  42127. const bindingsData = backend.get( bindGroup );
  42128. bindGroupLayouts.push( bindingsData.layout );
  42129. }
  42130. // vertex buffers
  42131. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  42132. // blending
  42133. let blending;
  42134. if ( material.transparent === true && material.blending !== NoBlending ) {
  42135. blending = this._getBlending( material );
  42136. }
  42137. // stencil
  42138. let stencilFront = {};
  42139. if ( material.stencilWrite === true ) {
  42140. stencilFront = {
  42141. compare: this._getStencilCompare( material ),
  42142. failOp: this._getStencilOperation( material.stencilFail ),
  42143. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  42144. passOp: this._getStencilOperation( material.stencilZPass )
  42145. };
  42146. }
  42147. const colorWriteMask = this._getColorWriteMask( material );
  42148. const targets = [];
  42149. if ( renderObject.context.textures !== null ) {
  42150. const textures = renderObject.context.textures;
  42151. for ( let i = 0; i < textures.length; i ++ ) {
  42152. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  42153. targets.push( {
  42154. format: colorFormat,
  42155. blend: blending,
  42156. writeMask: colorWriteMask
  42157. } );
  42158. }
  42159. } else {
  42160. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  42161. targets.push( {
  42162. format: colorFormat,
  42163. blend: blending,
  42164. writeMask: colorWriteMask
  42165. } );
  42166. }
  42167. const vertexModule = backend.get( vertexProgram ).module;
  42168. const fragmentModule = backend.get( fragmentProgram ).module;
  42169. const primitiveState = this._getPrimitiveState( object, geometry, material );
  42170. const depthCompare = this._getDepthCompare( material );
  42171. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  42172. const sampleCount = this._getSampleCount( renderObject.context );
  42173. const pipelineDescriptor = {
  42174. label: 'renderPipeline',
  42175. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  42176. fragment: Object.assign( {}, fragmentModule, { targets } ),
  42177. primitive: primitiveState,
  42178. depthStencil: {
  42179. format: depthStencilFormat,
  42180. depthWriteEnabled: material.depthWrite,
  42181. depthCompare: depthCompare,
  42182. stencilFront: stencilFront,
  42183. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  42184. stencilReadMask: material.stencilFuncMask,
  42185. stencilWriteMask: material.stencilWriteMask
  42186. },
  42187. multisample: {
  42188. count: sampleCount,
  42189. alphaToCoverageEnabled: material.alphaToCoverage
  42190. },
  42191. layout: device.createPipelineLayout( {
  42192. bindGroupLayouts
  42193. } )
  42194. };
  42195. if ( promises === null ) {
  42196. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  42197. } else {
  42198. const p = new Promise( ( resolve /*, reject*/ ) => {
  42199. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  42200. pipelineData.pipeline = pipeline;
  42201. resolve();
  42202. } );
  42203. } );
  42204. promises.push( p );
  42205. }
  42206. }
  42207. createBundleEncoder( renderContext, renderObject ) {
  42208. const backend = this.backend;
  42209. const { utils, device } = backend;
  42210. const renderContextData = backend.get( renderContext );
  42211. const renderObjectData = backend.get( renderObject );
  42212. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  42213. const colorFormat = utils.getCurrentColorFormat( renderContext );
  42214. const sampleCount = this._getSampleCount( renderObject.context );
  42215. const descriptor = {
  42216. label: 'renderBundleEncoder',
  42217. colorFormats: [ colorFormat ],
  42218. depthStencilFormat,
  42219. sampleCount
  42220. };
  42221. const bundleEncoder = device.createRenderBundleEncoder( descriptor );
  42222. renderObjectData.bundleEncoder = bundleEncoder;
  42223. renderContextData.currentSets = { attributes: {} };
  42224. renderContextData._renderBundleViewport = renderContext.width + '_' + renderContext.height;
  42225. return bundleEncoder;
  42226. }
  42227. createComputePipeline( pipeline, bindings ) {
  42228. const backend = this.backend;
  42229. const device = backend.device;
  42230. const computeProgram = backend.get( pipeline.computeProgram ).module;
  42231. const pipelineGPU = backend.get( pipeline );
  42232. // bind group layouts
  42233. const bindGroupLayouts = [];
  42234. for ( const bindingsGroup of bindings ) {
  42235. const bindingsData = backend.get( bindingsGroup );
  42236. bindGroupLayouts.push( bindingsData.layout );
  42237. }
  42238. pipelineGPU.pipeline = device.createComputePipeline( {
  42239. compute: computeProgram,
  42240. layout: device.createPipelineLayout( {
  42241. bindGroupLayouts
  42242. } )
  42243. } );
  42244. }
  42245. _getBlending( material ) {
  42246. let color, alpha;
  42247. const blending = material.blending;
  42248. const blendSrc = material.blendSrc;
  42249. const blendDst = material.blendDst;
  42250. const blendEquation = material.blendEquation;
  42251. if ( blending === CustomBlending ) {
  42252. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  42253. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  42254. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  42255. color = {
  42256. srcFactor: this._getBlendFactor( blendSrc ),
  42257. dstFactor: this._getBlendFactor( blendDst ),
  42258. operation: this._getBlendOperation( blendEquation )
  42259. };
  42260. alpha = {
  42261. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  42262. dstFactor: this._getBlendFactor( blendDstAlpha ),
  42263. operation: this._getBlendOperation( blendEquationAlpha )
  42264. };
  42265. } else {
  42266. const premultipliedAlpha = material.premultipliedAlpha;
  42267. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  42268. color = {
  42269. srcFactor: srcRGB,
  42270. dstFactor: dstRGB,
  42271. operation: GPUBlendOperation.Add
  42272. };
  42273. alpha = {
  42274. srcFactor: srcAlpha,
  42275. dstFactor: dstAlpha,
  42276. operation: GPUBlendOperation.Add
  42277. };
  42278. };
  42279. if ( premultipliedAlpha ) {
  42280. switch ( blending ) {
  42281. case NormalBlending:
  42282. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  42283. break;
  42284. case AdditiveBlending:
  42285. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  42286. break;
  42287. case SubtractiveBlending:
  42288. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42289. break;
  42290. case MultiplyBlending:
  42291. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  42292. break;
  42293. }
  42294. } else {
  42295. switch ( blending ) {
  42296. case NormalBlending:
  42297. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  42298. break;
  42299. case AdditiveBlending:
  42300. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  42301. break;
  42302. case SubtractiveBlending:
  42303. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42304. break;
  42305. case MultiplyBlending:
  42306. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  42307. break;
  42308. }
  42309. }
  42310. }
  42311. if ( color !== undefined && alpha !== undefined ) {
  42312. return { color, alpha };
  42313. } else {
  42314. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  42315. }
  42316. }
  42317. _getBlendFactor( blend ) {
  42318. let blendFactor;
  42319. switch ( blend ) {
  42320. case ZeroFactor:
  42321. blendFactor = GPUBlendFactor.Zero;
  42322. break;
  42323. case OneFactor:
  42324. blendFactor = GPUBlendFactor.One;
  42325. break;
  42326. case SrcColorFactor:
  42327. blendFactor = GPUBlendFactor.Src;
  42328. break;
  42329. case OneMinusSrcColorFactor:
  42330. blendFactor = GPUBlendFactor.OneMinusSrc;
  42331. break;
  42332. case SrcAlphaFactor:
  42333. blendFactor = GPUBlendFactor.SrcAlpha;
  42334. break;
  42335. case OneMinusSrcAlphaFactor:
  42336. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  42337. break;
  42338. case DstColorFactor:
  42339. blendFactor = GPUBlendFactor.Dst;
  42340. break;
  42341. case OneMinusDstColorFactor:
  42342. blendFactor = GPUBlendFactor.OneMinusDstColor;
  42343. break;
  42344. case DstAlphaFactor:
  42345. blendFactor = GPUBlendFactor.DstAlpha;
  42346. break;
  42347. case OneMinusDstAlphaFactor:
  42348. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  42349. break;
  42350. case SrcAlphaSaturateFactor:
  42351. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  42352. break;
  42353. case BlendColorFactor:
  42354. blendFactor = GPUBlendFactor.Constant;
  42355. break;
  42356. case OneMinusBlendColorFactor:
  42357. blendFactor = GPUBlendFactor.OneMinusConstant;
  42358. break;
  42359. default:
  42360. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  42361. }
  42362. return blendFactor;
  42363. }
  42364. _getStencilCompare( material ) {
  42365. let stencilCompare;
  42366. const stencilFunc = material.stencilFunc;
  42367. switch ( stencilFunc ) {
  42368. case NeverStencilFunc:
  42369. stencilCompare = GPUCompareFunction.Never;
  42370. break;
  42371. case AlwaysStencilFunc:
  42372. stencilCompare = GPUCompareFunction.Always;
  42373. break;
  42374. case LessStencilFunc:
  42375. stencilCompare = GPUCompareFunction.Less;
  42376. break;
  42377. case LessEqualStencilFunc:
  42378. stencilCompare = GPUCompareFunction.LessEqual;
  42379. break;
  42380. case EqualStencilFunc:
  42381. stencilCompare = GPUCompareFunction.Equal;
  42382. break;
  42383. case GreaterEqualStencilFunc:
  42384. stencilCompare = GPUCompareFunction.GreaterEqual;
  42385. break;
  42386. case GreaterStencilFunc:
  42387. stencilCompare = GPUCompareFunction.Greater;
  42388. break;
  42389. case NotEqualStencilFunc:
  42390. stencilCompare = GPUCompareFunction.NotEqual;
  42391. break;
  42392. default:
  42393. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  42394. }
  42395. return stencilCompare;
  42396. }
  42397. _getStencilOperation( op ) {
  42398. let stencilOperation;
  42399. switch ( op ) {
  42400. case KeepStencilOp:
  42401. stencilOperation = GPUStencilOperation.Keep;
  42402. break;
  42403. case ZeroStencilOp:
  42404. stencilOperation = GPUStencilOperation.Zero;
  42405. break;
  42406. case ReplaceStencilOp:
  42407. stencilOperation = GPUStencilOperation.Replace;
  42408. break;
  42409. case InvertStencilOp:
  42410. stencilOperation = GPUStencilOperation.Invert;
  42411. break;
  42412. case IncrementStencilOp:
  42413. stencilOperation = GPUStencilOperation.IncrementClamp;
  42414. break;
  42415. case DecrementStencilOp:
  42416. stencilOperation = GPUStencilOperation.DecrementClamp;
  42417. break;
  42418. case IncrementWrapStencilOp:
  42419. stencilOperation = GPUStencilOperation.IncrementWrap;
  42420. break;
  42421. case DecrementWrapStencilOp:
  42422. stencilOperation = GPUStencilOperation.DecrementWrap;
  42423. break;
  42424. default:
  42425. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  42426. }
  42427. return stencilOperation;
  42428. }
  42429. _getBlendOperation( blendEquation ) {
  42430. let blendOperation;
  42431. switch ( blendEquation ) {
  42432. case AddEquation:
  42433. blendOperation = GPUBlendOperation.Add;
  42434. break;
  42435. case SubtractEquation:
  42436. blendOperation = GPUBlendOperation.Subtract;
  42437. break;
  42438. case ReverseSubtractEquation:
  42439. blendOperation = GPUBlendOperation.ReverseSubtract;
  42440. break;
  42441. case MinEquation:
  42442. blendOperation = GPUBlendOperation.Min;
  42443. break;
  42444. case MaxEquation:
  42445. blendOperation = GPUBlendOperation.Max;
  42446. break;
  42447. default:
  42448. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  42449. }
  42450. return blendOperation;
  42451. }
  42452. _getPrimitiveState( object, geometry, material ) {
  42453. const descriptor = {};
  42454. const utils = this.backend.utils;
  42455. descriptor.topology = utils.getPrimitiveTopology( object, material );
  42456. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  42457. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42458. }
  42459. switch ( material.side ) {
  42460. case FrontSide:
  42461. descriptor.frontFace = GPUFrontFace.CCW;
  42462. descriptor.cullMode = GPUCullMode.Back;
  42463. break;
  42464. case BackSide:
  42465. descriptor.frontFace = GPUFrontFace.CCW;
  42466. descriptor.cullMode = GPUCullMode.Front;
  42467. break;
  42468. case DoubleSide:
  42469. descriptor.frontFace = GPUFrontFace.CCW;
  42470. descriptor.cullMode = GPUCullMode.None;
  42471. break;
  42472. default:
  42473. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  42474. break;
  42475. }
  42476. return descriptor;
  42477. }
  42478. _getColorWriteMask( material ) {
  42479. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  42480. }
  42481. _getDepthCompare( material ) {
  42482. let depthCompare;
  42483. if ( material.depthTest === false ) {
  42484. depthCompare = GPUCompareFunction.Always;
  42485. } else {
  42486. const depthFunc = material.depthFunc;
  42487. switch ( depthFunc ) {
  42488. case NeverDepth:
  42489. depthCompare = GPUCompareFunction.Never;
  42490. break;
  42491. case AlwaysDepth:
  42492. depthCompare = GPUCompareFunction.Always;
  42493. break;
  42494. case LessDepth:
  42495. depthCompare = GPUCompareFunction.Less;
  42496. break;
  42497. case LessEqualDepth:
  42498. depthCompare = GPUCompareFunction.LessEqual;
  42499. break;
  42500. case EqualDepth:
  42501. depthCompare = GPUCompareFunction.Equal;
  42502. break;
  42503. case GreaterEqualDepth:
  42504. depthCompare = GPUCompareFunction.GreaterEqual;
  42505. break;
  42506. case GreaterDepth:
  42507. depthCompare = GPUCompareFunction.Greater;
  42508. break;
  42509. case NotEqualDepth:
  42510. depthCompare = GPUCompareFunction.NotEqual;
  42511. break;
  42512. default:
  42513. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  42514. }
  42515. }
  42516. return depthCompare;
  42517. }
  42518. }
  42519. /*// debugger tools
  42520. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  42521. //*/
  42522. //
  42523. class WebGPUBackend extends Backend {
  42524. constructor( parameters = {} ) {
  42525. super( parameters );
  42526. this.isWebGPUBackend = true;
  42527. // some parameters require default values other than "undefined"
  42528. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  42529. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  42530. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42531. this.device = null;
  42532. this.context = null;
  42533. this.colorBuffer = null;
  42534. this.defaultRenderPassdescriptor = null;
  42535. this.utils = new WebGPUUtils( this );
  42536. this.attributeUtils = new WebGPUAttributeUtils( this );
  42537. this.bindingUtils = new WebGPUBindingUtils( this );
  42538. this.pipelineUtils = new WebGPUPipelineUtils( this );
  42539. this.textureUtils = new WebGPUTextureUtils( this );
  42540. this.occludedResolveCache = new Map();
  42541. }
  42542. async init( renderer ) {
  42543. await super.init( renderer );
  42544. //
  42545. const parameters = this.parameters;
  42546. // create the device if it is not passed with parameters
  42547. let device;
  42548. if ( parameters.device === undefined ) {
  42549. const adapterOptions = {
  42550. powerPreference: parameters.powerPreference
  42551. };
  42552. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  42553. if ( adapter === null ) {
  42554. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  42555. }
  42556. // feature support
  42557. const features = Object.values( GPUFeatureName );
  42558. const supportedFeatures = [];
  42559. for ( const name of features ) {
  42560. if ( adapter.features.has( name ) ) {
  42561. supportedFeatures.push( name );
  42562. }
  42563. }
  42564. const deviceDescriptor = {
  42565. requiredFeatures: supportedFeatures,
  42566. requiredLimits: parameters.requiredLimits
  42567. };
  42568. device = await adapter.requestDevice( deviceDescriptor );
  42569. } else {
  42570. device = parameters.device;
  42571. }
  42572. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  42573. this.device = device;
  42574. this.context = context;
  42575. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  42576. this.context.configure( {
  42577. device: this.device,
  42578. format: GPUTextureFormat.BGRA8Unorm,
  42579. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  42580. alphaMode: alphaMode
  42581. } );
  42582. this.updateSize();
  42583. }
  42584. get coordinateSystem() {
  42585. return WebGPUCoordinateSystem;
  42586. }
  42587. async getArrayBufferAsync( attribute ) {
  42588. return await this.attributeUtils.getArrayBufferAsync( attribute );
  42589. }
  42590. getContext() {
  42591. return this.context;
  42592. }
  42593. _getDefaultRenderPassDescriptor() {
  42594. let descriptor = this.defaultRenderPassdescriptor;
  42595. if ( descriptor === null ) {
  42596. const renderer = this.renderer;
  42597. descriptor = {
  42598. colorAttachments: [ {
  42599. view: null
  42600. } ],
  42601. depthStencilAttachment: {
  42602. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  42603. }
  42604. };
  42605. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42606. if ( this.renderer.samples > 0 ) {
  42607. colorAttachment.view = this.colorBuffer.createView();
  42608. } else {
  42609. colorAttachment.resolveTarget = undefined;
  42610. }
  42611. this.defaultRenderPassdescriptor = descriptor;
  42612. }
  42613. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42614. if ( this.renderer.samples > 0 ) {
  42615. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  42616. } else {
  42617. colorAttachment.view = this.context.getCurrentTexture().createView();
  42618. }
  42619. return descriptor;
  42620. }
  42621. _getRenderPassDescriptor( renderContext ) {
  42622. const renderTarget = renderContext.renderTarget;
  42623. const renderTargetData = this.get( renderTarget );
  42624. let descriptors = renderTargetData.descriptors;
  42625. if ( descriptors === undefined ) {
  42626. descriptors = [];
  42627. renderTargetData.descriptors = descriptors;
  42628. }
  42629. if ( renderTargetData.width !== renderTarget.width ||
  42630. renderTargetData.height !== renderTarget.height ||
  42631. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  42632. renderTargetData.samples !== renderTarget.samples
  42633. ) {
  42634. descriptors.length = 0;
  42635. }
  42636. let descriptor = descriptors[ renderContext.activeCubeFace ];
  42637. if ( descriptor === undefined ) {
  42638. const textures = renderContext.textures;
  42639. const colorAttachments = [];
  42640. for ( let i = 0; i < textures.length; i ++ ) {
  42641. const textureData = this.get( textures[ i ] );
  42642. const textureView = textureData.texture.createView( {
  42643. baseMipLevel: renderContext.activeMipmapLevel,
  42644. mipLevelCount: 1,
  42645. baseArrayLayer: renderContext.activeCubeFace,
  42646. dimension: GPUTextureViewDimension.TwoD
  42647. } );
  42648. let view, resolveTarget;
  42649. if ( textureData.msaaTexture !== undefined ) {
  42650. view = textureData.msaaTexture.createView();
  42651. resolveTarget = textureView;
  42652. } else {
  42653. view = textureView;
  42654. resolveTarget = undefined;
  42655. }
  42656. colorAttachments.push( {
  42657. view,
  42658. resolveTarget,
  42659. loadOp: GPULoadOp.Load,
  42660. storeOp: GPUStoreOp.Store
  42661. } );
  42662. }
  42663. const depthTextureData = this.get( renderContext.depthTexture );
  42664. const depthStencilAttachment = {
  42665. view: depthTextureData.texture.createView()
  42666. };
  42667. descriptor = {
  42668. colorAttachments,
  42669. depthStencilAttachment
  42670. };
  42671. descriptors[ renderContext.activeCubeFace ] = descriptor;
  42672. renderTargetData.width = renderTarget.width;
  42673. renderTargetData.height = renderTarget.height;
  42674. renderTargetData.samples = renderTarget.samples;
  42675. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  42676. }
  42677. return descriptor;
  42678. }
  42679. beginRender( renderContext ) {
  42680. const renderContextData = this.get( renderContext );
  42681. const device = this.device;
  42682. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42683. let occlusionQuerySet;
  42684. if ( occlusionQueryCount > 0 ) {
  42685. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  42686. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  42687. // Get a reference to the array of objects with queries. The renderContextData property
  42688. // can be changed by another render pass before the buffer.mapAsyc() completes.
  42689. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  42690. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  42691. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42692. //
  42693. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  42694. renderContextData.occlusionQuerySet = occlusionQuerySet;
  42695. renderContextData.occlusionQueryIndex = 0;
  42696. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42697. renderContextData.lastOcclusionObject = null;
  42698. }
  42699. let descriptor;
  42700. if ( renderContext.textures === null ) {
  42701. descriptor = this._getDefaultRenderPassDescriptor();
  42702. } else {
  42703. descriptor = this._getRenderPassDescriptor( renderContext );
  42704. }
  42705. this.initTimestampQuery( renderContext, descriptor );
  42706. descriptor.occlusionQuerySet = occlusionQuerySet;
  42707. const depthStencilAttachment = descriptor.depthStencilAttachment;
  42708. if ( renderContext.textures !== null ) {
  42709. const colorAttachments = descriptor.colorAttachments;
  42710. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  42711. const colorAttachment = colorAttachments[ i ];
  42712. if ( renderContext.clearColor ) {
  42713. colorAttachment.clearValue = renderContext.clearColorValue;
  42714. colorAttachment.loadOp = GPULoadOp.Clear;
  42715. colorAttachment.storeOp = GPUStoreOp.Store;
  42716. } else {
  42717. colorAttachment.loadOp = GPULoadOp.Load;
  42718. colorAttachment.storeOp = GPUStoreOp.Store;
  42719. }
  42720. }
  42721. } else {
  42722. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42723. if ( renderContext.clearColor ) {
  42724. colorAttachment.clearValue = renderContext.clearColorValue;
  42725. colorAttachment.loadOp = GPULoadOp.Clear;
  42726. colorAttachment.storeOp = GPUStoreOp.Store;
  42727. } else {
  42728. colorAttachment.loadOp = GPULoadOp.Load;
  42729. colorAttachment.storeOp = GPUStoreOp.Store;
  42730. }
  42731. }
  42732. //
  42733. if ( renderContext.depth ) {
  42734. if ( renderContext.clearDepth ) {
  42735. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  42736. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42737. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42738. } else {
  42739. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42740. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42741. }
  42742. }
  42743. if ( renderContext.stencil ) {
  42744. if ( renderContext.clearStencil ) {
  42745. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  42746. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42747. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42748. } else {
  42749. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42750. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42751. }
  42752. }
  42753. //
  42754. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  42755. const currentPass = encoder.beginRenderPass( descriptor );
  42756. //
  42757. renderContextData.descriptor = descriptor;
  42758. renderContextData.encoder = encoder;
  42759. renderContextData.currentPass = currentPass;
  42760. renderContextData.currentSets = { attributes: {} };
  42761. //
  42762. if ( renderContext.viewport ) {
  42763. this.updateViewport( renderContext );
  42764. }
  42765. if ( renderContext.scissor ) {
  42766. const { x, y, width, height } = renderContext.scissorValue;
  42767. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  42768. }
  42769. }
  42770. finishRender( renderContext ) {
  42771. const renderContextData = this.get( renderContext );
  42772. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42773. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  42774. renderContextData.registerBundlesPhase = false;
  42775. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  42776. }
  42777. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  42778. renderContextData.currentPass.endOcclusionQuery();
  42779. }
  42780. renderContextData.currentPass.end();
  42781. if ( occlusionQueryCount > 0 ) {
  42782. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  42783. //
  42784. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  42785. if ( queryResolveBuffer === undefined ) {
  42786. queryResolveBuffer = this.device.createBuffer(
  42787. {
  42788. size: bufferSize,
  42789. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  42790. }
  42791. );
  42792. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  42793. }
  42794. //
  42795. const readBuffer = this.device.createBuffer(
  42796. {
  42797. size: bufferSize,
  42798. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42799. }
  42800. );
  42801. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  42802. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  42803. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  42804. renderContextData.occlusionQueryBuffer = readBuffer;
  42805. //
  42806. this.resolveOccludedAsync( renderContext );
  42807. }
  42808. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  42809. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  42810. //
  42811. if ( renderContext.textures !== null ) {
  42812. const textures = renderContext.textures;
  42813. for ( let i = 0; i < textures.length; i ++ ) {
  42814. const texture = textures[ i ];
  42815. if ( texture.generateMipmaps === true ) {
  42816. this.textureUtils.generateMipmaps( texture );
  42817. }
  42818. }
  42819. }
  42820. }
  42821. isOccluded( renderContext, object ) {
  42822. const renderContextData = this.get( renderContext );
  42823. return renderContextData.occluded && renderContextData.occluded.has( object );
  42824. }
  42825. async resolveOccludedAsync( renderContext ) {
  42826. const renderContextData = this.get( renderContext );
  42827. // handle occlusion query results
  42828. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  42829. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  42830. const occluded = new WeakSet();
  42831. renderContextData.currentOcclusionQueryObjects = null;
  42832. renderContextData.currentOcclusionQueryBuffer = null;
  42833. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  42834. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  42835. const results = new BigUint64Array( buffer );
  42836. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  42837. if ( results[ i ] !== BigInt( 0 ) ) {
  42838. occluded.add( currentOcclusionQueryObjects[ i ] );
  42839. }
  42840. }
  42841. currentOcclusionQueryBuffer.destroy();
  42842. renderContextData.occluded = occluded;
  42843. }
  42844. }
  42845. updateViewport( renderContext ) {
  42846. const { currentPass } = this.get( renderContext );
  42847. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  42848. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  42849. }
  42850. clear( color, depth, stencil, renderTargetData = null ) {
  42851. const device = this.device;
  42852. const renderer = this.renderer;
  42853. let colorAttachments = [];
  42854. let depthStencilAttachment;
  42855. let clearValue;
  42856. let supportsDepth;
  42857. let supportsStencil;
  42858. if ( color ) {
  42859. const clearColor = this.getClearColor();
  42860. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  42861. }
  42862. if ( renderTargetData === null ) {
  42863. supportsDepth = renderer.depth;
  42864. supportsStencil = renderer.stencil;
  42865. const descriptor = this._getDefaultRenderPassDescriptor();
  42866. if ( color ) {
  42867. colorAttachments = descriptor.colorAttachments;
  42868. const colorAttachment = colorAttachments[ 0 ];
  42869. colorAttachment.clearValue = clearValue;
  42870. colorAttachment.loadOp = GPULoadOp.Clear;
  42871. colorAttachment.storeOp = GPUStoreOp.Store;
  42872. }
  42873. if ( supportsDepth || supportsStencil ) {
  42874. depthStencilAttachment = descriptor.depthStencilAttachment;
  42875. }
  42876. } else {
  42877. supportsDepth = renderTargetData.depth;
  42878. supportsStencil = renderTargetData.stencil;
  42879. if ( color ) {
  42880. for ( const texture of renderTargetData.textures ) {
  42881. const textureData = this.get( texture );
  42882. const textureView = textureData.texture.createView();
  42883. let view, resolveTarget;
  42884. if ( textureData.msaaTexture !== undefined ) {
  42885. view = textureData.msaaTexture.createView();
  42886. resolveTarget = textureView;
  42887. } else {
  42888. view = textureView;
  42889. resolveTarget = undefined;
  42890. }
  42891. colorAttachments.push( {
  42892. view,
  42893. resolveTarget,
  42894. clearValue,
  42895. loadOp: GPULoadOp.Clear,
  42896. storeOp: GPUStoreOp.Store
  42897. } );
  42898. }
  42899. }
  42900. if ( supportsDepth || supportsStencil ) {
  42901. const depthTextureData = this.get( renderTargetData.depthTexture );
  42902. depthStencilAttachment = {
  42903. view: depthTextureData.texture.createView()
  42904. };
  42905. }
  42906. }
  42907. //
  42908. if ( supportsDepth ) {
  42909. if ( depth ) {
  42910. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  42911. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  42912. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42913. } else {
  42914. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  42915. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  42916. }
  42917. }
  42918. //
  42919. if ( supportsStencil ) {
  42920. if ( stencil ) {
  42921. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  42922. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  42923. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42924. } else {
  42925. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  42926. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  42927. }
  42928. }
  42929. //
  42930. const encoder = device.createCommandEncoder( {} );
  42931. const currentPass = encoder.beginRenderPass( {
  42932. colorAttachments,
  42933. depthStencilAttachment
  42934. } );
  42935. currentPass.end();
  42936. device.queue.submit( [ encoder.finish() ] );
  42937. }
  42938. // compute
  42939. beginCompute( computeGroup ) {
  42940. const groupGPU = this.get( computeGroup );
  42941. const descriptor = {};
  42942. this.initTimestampQuery( computeGroup, descriptor );
  42943. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  42944. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  42945. }
  42946. compute( computeGroup, computeNode, bindings, pipeline ) {
  42947. const { passEncoderGPU } = this.get( computeGroup );
  42948. // pipeline
  42949. const pipelineGPU = this.get( pipeline ).pipeline;
  42950. passEncoderGPU.setPipeline( pipelineGPU );
  42951. // bind groups
  42952. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42953. const bindGroup = bindings[ i ];
  42954. const bindingsData = this.get( bindGroup );
  42955. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42956. }
  42957. passEncoderGPU.dispatchWorkgroups( computeNode.dispatchCount );
  42958. }
  42959. finishCompute( computeGroup ) {
  42960. const groupData = this.get( computeGroup );
  42961. groupData.passEncoderGPU.end();
  42962. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  42963. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  42964. }
  42965. // render object
  42966. draw( renderObject, info ) {
  42967. const { object, geometry, context, pipeline } = renderObject;
  42968. const bindings = renderObject.getBindings();
  42969. const contextData = this.get( context );
  42970. const pipelineGPU = this.get( pipeline ).pipeline;
  42971. const currentSets = contextData.currentSets;
  42972. const renderObjectData = this.get( renderObject );
  42973. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  42974. const renderContextData = this.get( context );
  42975. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  42976. renderContextData.renderBundles.push( renderBundle );
  42977. return;
  42978. }
  42979. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  42980. // pipeline
  42981. if ( currentSets.pipeline !== pipelineGPU ) {
  42982. passEncoderGPU.setPipeline( pipelineGPU );
  42983. currentSets.pipeline = pipelineGPU;
  42984. }
  42985. // bind groups
  42986. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  42987. const bindGroup = bindings[ i ];
  42988. const bindingsData = this.get( bindGroup );
  42989. passEncoderGPU.setBindGroup( i, bindingsData.group );
  42990. }
  42991. // attributes
  42992. const index = renderObject.getIndex();
  42993. const hasIndex = ( index !== null );
  42994. // index
  42995. if ( hasIndex === true ) {
  42996. if ( currentSets.index !== index ) {
  42997. const buffer = this.get( index ).buffer;
  42998. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42999. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  43000. currentSets.index = index;
  43001. }
  43002. }
  43003. // vertex buffers
  43004. const vertexBuffers = renderObject.getVertexBuffers();
  43005. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  43006. const vertexBuffer = vertexBuffers[ i ];
  43007. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  43008. const buffer = this.get( vertexBuffer ).buffer;
  43009. passEncoderGPU.setVertexBuffer( i, buffer );
  43010. currentSets.attributes[ i ] = vertexBuffer;
  43011. }
  43012. }
  43013. // occlusion queries - handle multiple consecutive draw calls for an object
  43014. if ( contextData.occlusionQuerySet !== undefined ) {
  43015. const lastObject = contextData.lastOcclusionObject;
  43016. if ( lastObject !== object ) {
  43017. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  43018. passEncoderGPU.endOcclusionQuery();
  43019. contextData.occlusionQueryIndex ++;
  43020. }
  43021. if ( object.occlusionTest === true ) {
  43022. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  43023. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  43024. }
  43025. contextData.lastOcclusionObject = object;
  43026. }
  43027. }
  43028. // draw
  43029. const drawRange = renderObject.drawRange;
  43030. const firstVertex = drawRange.start;
  43031. const instanceCount = this.getInstanceCount( renderObject );
  43032. if ( instanceCount === 0 ) return;
  43033. if ( object.isBatchedMesh === true ) {
  43034. const starts = object._multiDrawStarts;
  43035. const counts = object._multiDrawCounts;
  43036. const drawCount = object._multiDrawCount;
  43037. const drawInstances = object._multiDrawInstances;
  43038. const bytesPerElement = index.bytesPerElement || 1;
  43039. for ( let i = 0; i < drawCount; i ++ ) {
  43040. const count = drawInstances ? drawInstances[ i ] : 1;
  43041. const firstInstance = count > 1 ? 0 : i;
  43042. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, count, starts[ i ] / 4, 0, firstInstance );
  43043. }
  43044. } else if ( hasIndex === true ) {
  43045. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  43046. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  43047. info.update( object, indexCount, instanceCount );
  43048. } else {
  43049. const positionAttribute = geometry.attributes.position;
  43050. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  43051. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  43052. info.update( object, vertexCount, instanceCount );
  43053. }
  43054. if ( this.renderer._currentRenderBundle ) {
  43055. const renderBundle = passEncoderGPU.finish();
  43056. renderObjectData.lastPipelineGPU = pipelineGPU;
  43057. renderObjectData.renderBundle = renderBundle;
  43058. renderObjectData.bundleEncoder = passEncoderGPU;
  43059. }
  43060. }
  43061. // cache key
  43062. needsRenderUpdate( renderObject ) {
  43063. const data = this.get( renderObject );
  43064. const { object, material } = renderObject;
  43065. const utils = this.utils;
  43066. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  43067. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  43068. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  43069. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  43070. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  43071. let needsUpdate = false;
  43072. if ( data.material !== material || data.materialVersion !== material.version ||
  43073. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  43074. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  43075. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  43076. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  43077. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  43078. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  43079. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  43080. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  43081. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  43082. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  43083. data.primitiveTopology !== primitiveTopology ||
  43084. data.clippingContextVersion !== renderObject.clippingContextVersion
  43085. ) {
  43086. data.material = material; data.materialVersion = material.version;
  43087. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  43088. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  43089. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  43090. data.colorWrite = material.colorWrite;
  43091. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  43092. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  43093. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  43094. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  43095. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  43096. data.sampleCount = sampleCount;
  43097. data.colorSpace = colorSpace;
  43098. data.colorFormat = colorFormat;
  43099. data.depthStencilFormat = depthStencilFormat;
  43100. data.primitiveTopology = primitiveTopology;
  43101. data.clippingContextVersion = renderObject.clippingContextVersion;
  43102. needsUpdate = true;
  43103. }
  43104. return needsUpdate;
  43105. }
  43106. getRenderCacheKey( renderObject ) {
  43107. const { object, material } = renderObject;
  43108. const utils = this.utils;
  43109. const renderContext = renderObject.context;
  43110. return [
  43111. material.transparent, material.blending, material.premultipliedAlpha,
  43112. material.blendSrc, material.blendDst, material.blendEquation,
  43113. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  43114. material.colorWrite,
  43115. material.depthWrite, material.depthTest, material.depthFunc,
  43116. material.stencilWrite, material.stencilFunc,
  43117. material.stencilFail, material.stencilZFail, material.stencilZPass,
  43118. material.stencilFuncMask, material.stencilWriteMask,
  43119. material.side,
  43120. utils.getSampleCountRenderContext( renderContext ),
  43121. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  43122. utils.getPrimitiveTopology( object, material ),
  43123. renderObject.clippingContextVersion
  43124. ].join();
  43125. }
  43126. // textures
  43127. createSampler( texture ) {
  43128. this.textureUtils.createSampler( texture );
  43129. }
  43130. destroySampler( texture ) {
  43131. this.textureUtils.destroySampler( texture );
  43132. }
  43133. createDefaultTexture( texture ) {
  43134. this.textureUtils.createDefaultTexture( texture );
  43135. }
  43136. createTexture( texture, options ) {
  43137. this.textureUtils.createTexture( texture, options );
  43138. }
  43139. updateTexture( texture, options ) {
  43140. this.textureUtils.updateTexture( texture, options );
  43141. }
  43142. generateMipmaps( texture ) {
  43143. this.textureUtils.generateMipmaps( texture );
  43144. }
  43145. destroyTexture( texture ) {
  43146. this.textureUtils.destroyTexture( texture );
  43147. }
  43148. copyTextureToBuffer( texture, x, y, width, height ) {
  43149. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  43150. }
  43151. initTimestampQuery( renderContext, descriptor ) {
  43152. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  43153. const renderContextData = this.get( renderContext );
  43154. if ( ! renderContextData.timeStampQuerySet ) {
  43155. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  43156. // beginning and one for the end of compute pass execution.
  43157. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  43158. const timestampWrites = {
  43159. querySet: timeStampQuerySet,
  43160. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  43161. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  43162. };
  43163. Object.assign( descriptor, {
  43164. timestampWrites,
  43165. } );
  43166. renderContextData.timeStampQuerySet = timeStampQuerySet;
  43167. }
  43168. }
  43169. // timestamp utils
  43170. prepareTimestampBuffer( renderContext, encoder ) {
  43171. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  43172. const renderContextData = this.get( renderContext );
  43173. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  43174. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  43175. renderContextData.currentTimestampQueryBuffers = {
  43176. resolveBuffer: this.device.createBuffer( {
  43177. label: 'timestamp resolve buffer',
  43178. size: size,
  43179. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  43180. } ),
  43181. resultBuffer: this.device.createBuffer( {
  43182. label: 'timestamp result buffer',
  43183. size: size,
  43184. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  43185. } ),
  43186. isMappingPending: false,
  43187. };
  43188. }
  43189. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  43190. if ( isMappingPending === true ) return;
  43191. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  43192. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  43193. }
  43194. async resolveTimestampAsync( renderContext, type = 'render' ) {
  43195. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  43196. const renderContextData = this.get( renderContext );
  43197. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  43198. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  43199. if ( isMappingPending === true ) return;
  43200. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  43201. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  43202. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  43203. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  43204. this.renderer.info.updateTimestamp( type, duration );
  43205. resultBuffer.unmap();
  43206. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  43207. } );
  43208. }
  43209. // node builder
  43210. createNodeBuilder( object, renderer ) {
  43211. return new WGSLNodeBuilder( object, renderer );
  43212. }
  43213. // program
  43214. createProgram( program ) {
  43215. const programGPU = this.get( program );
  43216. programGPU.module = {
  43217. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  43218. entryPoint: 'main'
  43219. };
  43220. }
  43221. destroyProgram( program ) {
  43222. this.delete( program );
  43223. }
  43224. // pipelines
  43225. createRenderPipeline( renderObject, promises ) {
  43226. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  43227. }
  43228. createComputePipeline( computePipeline, bindings ) {
  43229. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  43230. }
  43231. createBundleEncoder( renderContext, renderObject ) {
  43232. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  43233. }
  43234. // bindings
  43235. createBindings( bindGroup ) {
  43236. this.bindingUtils.createBindings( bindGroup );
  43237. }
  43238. updateBindings( bindGroup ) {
  43239. this.bindingUtils.createBindings( bindGroup );
  43240. }
  43241. updateBinding( binding ) {
  43242. this.bindingUtils.updateBinding( binding );
  43243. }
  43244. // attributes
  43245. createIndexAttribute( attribute ) {
  43246. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43247. }
  43248. createAttribute( attribute ) {
  43249. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43250. }
  43251. createStorageAttribute( attribute ) {
  43252. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43253. }
  43254. updateAttribute( attribute ) {
  43255. this.attributeUtils.updateAttribute( attribute );
  43256. }
  43257. destroyAttribute( attribute ) {
  43258. this.attributeUtils.destroyAttribute( attribute );
  43259. }
  43260. // canvas
  43261. updateSize() {
  43262. this.colorBuffer = this.textureUtils.getColorBuffer();
  43263. this.defaultRenderPassdescriptor = null;
  43264. }
  43265. // utils public
  43266. getMaxAnisotropy() {
  43267. return 16;
  43268. }
  43269. hasFeature( name ) {
  43270. return this.device.features.has( name );
  43271. }
  43272. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  43273. let dstX = 0;
  43274. let dstY = 0;
  43275. let srcX = 0;
  43276. let srcY = 0;
  43277. let srcWidth = srcTexture.image.width;
  43278. let srcHeight = srcTexture.image.height;
  43279. if ( srcRegion !== null ) {
  43280. srcX = srcRegion.x;
  43281. srcY = srcRegion.y;
  43282. srcWidth = srcRegion.width;
  43283. srcHeight = srcRegion.height;
  43284. }
  43285. if ( dstPosition !== null ) {
  43286. dstX = dstPosition.x;
  43287. dstY = dstPosition.y;
  43288. }
  43289. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  43290. const sourceGPU = this.get( srcTexture ).texture;
  43291. const destinationGPU = this.get( dstTexture ).texture;
  43292. encoder.copyTextureToTexture(
  43293. {
  43294. texture: sourceGPU,
  43295. mipLevel: level,
  43296. origin: { x: srcX, y: srcY, z: 0 }
  43297. },
  43298. {
  43299. texture: destinationGPU,
  43300. mipLevel: level,
  43301. origin: { x: dstX, y: dstY, z: 0 }
  43302. },
  43303. [
  43304. srcWidth,
  43305. srcHeight
  43306. ]
  43307. );
  43308. this.device.queue.submit( [ encoder.finish() ] );
  43309. }
  43310. copyFramebufferToTexture( texture, renderContext ) {
  43311. const renderContextData = this.get( renderContext );
  43312. const { encoder, descriptor } = renderContextData;
  43313. let sourceGPU = null;
  43314. if ( renderContext.renderTarget ) {
  43315. if ( texture.isDepthTexture ) {
  43316. sourceGPU = this.get( renderContext.depthTexture ).texture;
  43317. } else {
  43318. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  43319. }
  43320. } else {
  43321. if ( texture.isDepthTexture ) {
  43322. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  43323. } else {
  43324. sourceGPU = this.context.getCurrentTexture();
  43325. }
  43326. }
  43327. const destinationGPU = this.get( texture ).texture;
  43328. if ( sourceGPU.format !== destinationGPU.format ) {
  43329. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  43330. return;
  43331. }
  43332. renderContextData.currentPass.end();
  43333. encoder.copyTextureToTexture(
  43334. {
  43335. texture: sourceGPU,
  43336. origin: { x: 0, y: 0, z: 0 }
  43337. },
  43338. {
  43339. texture: destinationGPU
  43340. },
  43341. [
  43342. texture.image.width,
  43343. texture.image.height
  43344. ]
  43345. );
  43346. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  43347. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  43348. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  43349. }
  43350. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43351. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43352. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  43353. renderContextData.currentSets = { attributes: {} };
  43354. }
  43355. }
  43356. /*
  43357. const debugHandler = {
  43358. get: function ( target, name ) {
  43359. // Add |update
  43360. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  43361. return target[ name ];
  43362. }
  43363. };
  43364. */
  43365. class WebGPURenderer extends Renderer {
  43366. constructor( parameters = {} ) {
  43367. let BackendClass;
  43368. if ( parameters.forceWebGL ) {
  43369. BackendClass = WebGLBackend;
  43370. } else if ( WebGPU.isAvailable() ) {
  43371. BackendClass = WebGPUBackend;
  43372. } else {
  43373. BackendClass = WebGLBackend;
  43374. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  43375. }
  43376. const backend = new BackendClass( parameters );
  43377. //super( new Proxy( backend, debugHandler ) );
  43378. super( backend, parameters );
  43379. this.isWebGPURenderer = true;
  43380. }
  43381. }
  43382. const quadMesh = new QuadMesh( new NodeMaterial() );
  43383. class PostProcessing {
  43384. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  43385. this.renderer = renderer;
  43386. this.outputNode = outputNode;
  43387. this.outputColorTransform = true;
  43388. this.needsUpdate = true;
  43389. }
  43390. render() {
  43391. this.update();
  43392. const renderer = this.renderer;
  43393. const toneMapping = renderer.toneMapping;
  43394. const outputColorSpace = renderer.outputColorSpace;
  43395. renderer.toneMapping = NoToneMapping;
  43396. renderer.outputColorSpace = LinearSRGBColorSpace;
  43397. //
  43398. quadMesh.render( renderer );
  43399. //
  43400. renderer.toneMapping = toneMapping;
  43401. renderer.outputColorSpace = outputColorSpace;
  43402. }
  43403. update() {
  43404. if ( this.needsUpdate === true ) {
  43405. const renderer = this.renderer;
  43406. const toneMapping = renderer.toneMapping;
  43407. const outputColorSpace = renderer.outputColorSpace;
  43408. quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  43409. quadMesh.material.needsUpdate = true;
  43410. this.needsUpdate = false;
  43411. }
  43412. }
  43413. async renderAsync() {
  43414. this.update();
  43415. const renderer = this.renderer;
  43416. const toneMapping = renderer.toneMapping;
  43417. const outputColorSpace = renderer.outputColorSpace;
  43418. renderer.toneMapping = NoToneMapping;
  43419. renderer.outputColorSpace = LinearSRGBColorSpace;
  43420. //
  43421. await quadMesh.renderAsync( renderer );
  43422. //
  43423. renderer.toneMapping = toneMapping;
  43424. renderer.outputColorSpace = outputColorSpace;
  43425. }
  43426. }
  43427. class StorageTexture extends Texture {
  43428. constructor( width = 1, height = 1 ) {
  43429. super();
  43430. this.image = { width, height };
  43431. this.magFilter = LinearFilter;
  43432. this.minFilter = LinearFilter;
  43433. this.isStorageTexture = true;
  43434. }
  43435. }
  43436. class StorageBufferAttribute extends BufferAttribute {
  43437. constructor( array, itemSize, typeClass = Float32Array ) {
  43438. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43439. super( array, itemSize );
  43440. this.isStorageBufferAttribute = true;
  43441. }
  43442. }
  43443. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  43444. constructor( array, itemSize, typeClass = Float32Array ) {
  43445. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  43446. super( array, itemSize );
  43447. this.isStorageInstancedBufferAttribute = true;
  43448. }
  43449. }
  43450. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43451. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43452. revision: REVISION,
  43453. } } ) );
  43454. }
  43455. if ( typeof window !== 'undefined' ) {
  43456. if ( window.__THREE__ ) {
  43457. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43458. } else {
  43459. window.__THREE__ = REVISION;
  43460. }
  43461. }
  43462. 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, MRTNode, 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, emissive, 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, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, 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, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, 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, passTexture, 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, refractVector, refractView, 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, 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 };
粤ICP备19079148号